Beispiel #1
0
        public void GetWeight(out decimal?weight, out bool?isStable)
        {
            weight   = null;
            isStable = false;

            if (this.IsConnected)
            {
                inData = scale.Read(250);
                // Byte 0 == Report ID?
                // Byte 1 == Scale Status (1 == Fault, 2 == Stable @ 0, 3 == In Motion, 4 == Stable, 5 == Under 0, 6 == Over Weight, 7 == Requires Calibration, 8 == Requires Re-Zeroing)
                // Byte 2 == Weight Unit
                // Byte 3 == Data Scaling (decimal placement) - signed byte is power of 10
                // Byte 4 == Weight LSB
                // Byte 5 == Weight MSB

                weight = (decimal?)BitConverter.ToInt16(new byte[] { inData.Data[4], inData.Data[5] }, 0) *
                         Convert.ToDecimal(Math.Pow(10, (sbyte)inData.Data[3]));

                switch (Convert.ToInt16(inData.Data[2]))
                {
                case 3: // Kilos
                    weight = weight * (decimal?)2.2;
                    break;

                case 11: // Ounces
                    weight = weight * (decimal?)0.0625;
                    break;

                case 12: // Pounds
                    // already in pounds, do nothing
                    break;
                }
                isStable = inData.Data[1] == 0x4;
            }
        }
Beispiel #2
0
        public void Read()
        {
            HidDeviceData dataPoint = usbDevice.Read();

            if (dataPoint.Status != HidDeviceData.ReadStatus.Success)
            {
                throw new InvalidOperationException($"Cannot read from USB device! State was {dataPoint.Status}");
            }

            // this is the same behaviour as the CAM software.
            // Somehow it sometimes spits random, fixed values and nobody really knows why.
            if (dataPoint.Data[10] != deviceId)
            {
                return;
            }

            if (dataPoint.Data[0] == 4)
            {
                LastStates.Enqueue(ParseDataPackage(dataPoint));
            }

            while (LastStates.Count > 255)
            {
                LastStates.Dequeue();
            }
        }
Beispiel #3
0
        static void listen()
        {
            //ignore the first byte, it is always 0
            HidDeviceData data = device.Read(2000);

            char[] chars = new char[12];
            int    index = 0;

            if (data.Data.Length < 64)
            {
                return;
            }
            //extract RFID
            int j = 0;

            for (int i = 3; i < 15; i++)
            {
                chars[j++] = (char)data.Data[i];
            }
            //check to see if id should be opened or closed
            if (data.Data[1] == 255 && data.Data[2] == 255) //open code
            {
                open(new String(chars));
            }
            else
            {
                close(new String(chars));
            }

            listen();
        }
        private void ReadCallback(HidDeviceData data)
        {
            LogTo.Debug("Got a ReadCallback of length {0}", data.Data.Length);

            if (open)
            {
                _device.Read(ReadCallback);
            }
            else
            {
                LogTo.Trace("Ignored incoming data, device is closed");
                return;
            }

            if (DataReceived == null)
            {
                return;
            }

            var bytes      = data.Data;
            var preparsed  = _preparser.InterpretPacket(bytes);
            var dataString = _parser.CurrentParser.InterpretPacket(preparsed, bytes);
            var args       = new DataReceivedEventArgs(dataString);

            DataReceived(this, args);
        }
Beispiel #5
0
        private async void ReadLoop()
        {
            HidDeviceData dataPoint = await usbDevice.ReadAsync();

            GetDeviceId(dataPoint);
            while (keepReading)
            {
                dataPoint = await usbDevice.ReadAsync();

                if (dataPoint.Status != HidDeviceData.ReadStatus.Success)
                {
                    throw new InvalidOperationException($"Cannot read from USB device! State was {dataPoint.Status}");
                }

                // this is the same behaviour as the CAM software.
                // Somehow it sometimes spits random, fixed values and nobody really knows why.
                if (dataPoint.Data[10] != deviceId)
                {
                    // Console.WriteLine("Disposed");
                    continue;
                }

                if (dataPoint.Data[0] == 4)
                {
                    LastStates.Enqueue(ParseDataPackage(dataPoint));
                }

                while (LastStates.Count > 255)
                {
                    LastStates.Dequeue();
                }
            }
        }
Beispiel #6
0
        void ReadG13Data(HidDeviceData data)
        {
            KeyState state = new KeyState();

            if (data.Status == HidDeviceData.ReadStatus.Success)
            {
                var bytes = data.Data;

                var reportId  = bytes[0];
                var joystickX = bytes[1] - 0x80;
                var joystickY = bytes[2] - 0x80;

                state.B0 = bytes[3];
                state.B1 = bytes[4];
                state.B2 = bytes[5] < 0x80 ? bytes[5] : (byte)(bytes[5] - 0x80);
                state.B3 = bytes[6];
                state.B4 = bytes[7] < 0x80 ? bytes[7] : (byte)(bytes[7] - 0x80);

                var sb = new StringBuilder();

#if display_verbose_data
                sb.Append("Joystick: ")
                .Append(joystickX.ToString().PadLeft(4, ' ')).Append(", ")
                .Append(joystickY.ToString().PadLeft(4, ' ')).Append("; ");
                for (int i = 3; i < bytes.Length; i++)
                {
                    sb
                    .Append(i > 3 ? ", " : "")
                    .Append(bytes[i].ToString("x").PadLeft(2, ' '));
                }

                sb.Append(" : ").Append(state.UL.ToString("x").PadLeft(10, '0'));
#else
                var dif = currentState.UL ^ state.UL;
                sb.Append(((G13Keys)dif).ToString());
                var pressed = (dif & state.UL) > 0;
                sb.Append(" ").Append(pressed);

                if ((G13Keys)dif == G13Keys.G1)
                {
                    if (pressed)
                    {
                        SendInputManager.KeyDown(SendInputManager.ScanCode.a, false, true);
                    }
                    else
                    {
                        SendInputManager.KeyUp(SendInputManager.ScanCode.a);
                    }

                    //SendInputManager.KeyTap(SendInputManager.ScanCode.a);
                }
#endif

                sb.Append(Environment.NewLine);
                currentState = state;

                rtbInfo.AppendText(sb.ToString());
            }
        }
Beispiel #7
0
 private void GetDeviceId(HidDeviceData data)
 {
     // is there actually a likelyhood to hit the one case, where it breaks by getting the garbled
     // packet with the unidentified data?
     readAnyBytes    = true;
     deviceId        = data.Data[10];
     firmwareVersion = data.Data[11] * 1000 + data.Data[12] * 100 + data.Data[13] * 10 + data.Data[14];
 }
Beispiel #8
0
        private void listen()
        {
            //ignore the first byte, it is always 0
            HidDeviceData data = device.Read(2000);

            if (data.Status == HidDeviceData.ReadStatus.NotConnected)
            {
                return;
            }

            //check to see if an event has been sent
            //so far only two are established, so if starts with 0 then ignore.

            //if the first two bytes are 255,then we are being sent a request for character
            //data.
            if (data.Data[1] == 255 && data.Data[2] == 255) //open code
            {
                if (InvokeRequired)
                {
                    this.Invoke(new MethodInvoker(highlightText));
                }
                else
                {
                    highlightText();
                }
            }
            else if (data.Data[1] > 0) //a code exists, so do something.
            {
                //must be a message, so add to buffer and display
                //extract size of message
                int    sz       = Convert.ToInt32(data.Data[1]);
                string response = "";
                if (sz > 64)
                {
                    response = System.Text.ASCIIEncoding.ASCII.GetString(data.Data, 2, 62);
                    usbBuffer.Append(response);
                    listen();
                }
                else
                {
                    response = System.Text.ASCIIEncoding.ASCII.GetString(data.Data, 2, sz);
                    usbBuffer.Append(response);
                    if (InvokeRequired)
                    {
                        this.Invoke(new MethodInvoker(printUSB));
                    }
                    else
                    {
                        printUSB();
                    }
                }
            }
        }
Beispiel #9
0
        private KrakenState ParseDataPackage(HidDeviceData data)
        {
            var bytes = data.Data;
            var decimalTemperature = (float)bytes[2];

            while (decimalTemperature > 1)
            {
                decimalTemperature /= 10f;
            }

            return(new KrakenState(bytes[1] + decimalTemperature,
                                   bytes[3] << 8 | bytes[4],
                                   bytes[5] << 8 | bytes[6],
                                   DateTime.Now));
        }
Beispiel #10
0
        /// <summary>
        /// Will return the weight
        /// </summary>
        /// <remarks>
        /// A little help from http://stackoverflow.com/questions/11961412/read-weight-from-a-fairbanks-scb-9000-usb-scale
        /// for the full conversion
        /// </remarks>
        /// <param name="weight"></param>
        /// <param name="isStable"></param>
        /// <returns></returns>
        public WeightResult GetWeight()
        {
            CheckStatusAndThrow();
            WeightResult result = new WeightResult();

            if (mScale.IsConnected)
            {
                HidDeviceData inData = mScale.Read(10);
                if (inData.Status != HidDeviceData.ReadStatus.Success)
                {
                    throw new Exception("Data Read Failure");
                }
                result = HelpGetWeight(inData.Data);
            }            //end if is connected
            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// Reading HID device and write on Com port
        /// </summary>
        private void hidReader()
        {
            while (true)
            {
                if (FailNoDevice() || FailDeviceClosed())
                {
                    return;
                }

                HidDeviceData hddData = mhdDevice.Read();
                vsText = BitConverter.ToString(hddData.Data);
                serialPort.WriteLine(vsText);

                Thread.Sleep(1);
            }
        }
Beispiel #12
0
        public DeviceStatus GetStatus()
        {
            if (!device.Write(statusCommand, 100))
            {
                return(DeviceStatus.Errored);
            }

            HidDeviceData data = device.Read(100);

            if (data.Status != HidDeviceData.ReadStatus.Success)
            {
                return(DeviceStatus.Errored);
            }

            return((DeviceStatus)data.Data[1]);
        }
Beispiel #13
0
        private void GetServoAxes_ReadCallback(HidDeviceData data)
        {
            UpdateStatsLabels(dispatchTimers[1], 1, LabelPing, true);

            DataWriter dataWriter = new DataWriter();

            dataWriter.WriteBytes(data.Data);

            DataReader dataReader = DataReader.FromBuffer(dataWriter.DetachBuffer());

            dataReader.ByteOrder = ByteOrder.LittleEndian;

            if (data.Status == HidDeviceData.ReadStatus.Success)
            {
                if (dataReader.ReadByte() == 0 && dataReader.ReadUInt16() == 0x5555)
                {
                    int length = dataReader.ReadByte();

                    RobotCommand command = (RobotCommand)dataReader.ReadByte();

                    Dispatcher.Invoke(new Action(() =>
                    {
                        int count = dataReader.ReadByte();

                        DrawStatusCanvasReceiveCanvasBlip(PingCount == 1 ? Brushes.Green : Brushes.Yellow, PingCount == 1 ? 2 : 1);
                        PingCount--;

                        while (count-- > 0)
                        {
                            int servo = dataReader.ReadByte();
                            int angle = dataReader.ReadInt16();
                            var grid  = (Grid)RobotAxisControlGrid.Children[servo - 1];
                            RobotAxisControl control  = (RobotAxisControl)grid.Children[1];
                            control.sliderAngle.Value = angle;
                        }
                    }));
                }
                else
                {
                    DrawStatusCanvasReceiveCanvasBlip(Brushes.Red, 2);
                }
            }
            else
            {
                DrawStatusCanvasReceiveCanvasBlip(Brushes.Orange, 2);
            }
        }
Beispiel #14
0
        //
        //         read data on the IN endpoint associated to the HID interface
        //
        public List <byte> read(int size = -1, int timeout = -1)
        {
            // HidReport report = this.device.ReadReport();
            HidDeviceData result = this.device.Read(this.packet_size);

            if (result.Status == HidDeviceData.ReadStatus.Success)
            //if (report.Exists)
            {
                // return report.Data.ToList();
                List <byte> bytes = result.Data.ToList();
                return(bytes.GetRange(1, bytes.Count - 1));
            }
            else
            {
                throw new Exception();
            }
        }
Beispiel #15
0
        /// <summary>
        /// Receive data from USB device. The return value will always be 48 bytes, and the
        /// data will only be sent if we request it via a command. There is no unsoliced data.
        /// First two bytes of HID buffer are TI's HID protcol:
        /// Byte 0: 0x3F
        ///      1: Length of user payload (0x30 = 48)
        ///      2: First byte of user data
        ///      49: Last byte of user data
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="len"></param>
        /// <returns></returns>
        static public bool USBRecvData(out byte[] buffer)
        {
            buffer = new byte[0];

            HidDeviceData hdd = Msp430.FastRead(Timeout);

            if (hdd != null)
            {
                buffer = new byte[hdd.Data[1]];
                Array.Copy(hdd.Data, 2, buffer, 0, hdd.Data[1]);
                return(true);
            }

            else
            {
                return(false);
            }
        }
Beispiel #16
0
        public void GetWeight(out decimal?weight, out bool?isStable)
        {
            weight   = null;
            isStable = false;

            if (scale.IsConnected)
            {
                inData = scale.Read(250);

                weight = (Convert.ToDecimal(inData.Data[4]) +
                          Convert.ToDecimal(inData.Data[5]) * 256) *
                         Convert.ToDecimal(Math.Pow(10, (sbyte)inData.Data[3]));

                Convert.ToInt16(inData.Data[2]);

                isStable = inData.Data[1] == 0x4;
            }
        }
Beispiel #17
0
        public void Update()
        {
            HidDeviceData data = sensor.Read(2);

            if (data.Status == HidDeviceData.ReadStatus.Success)
            {
                int    size = Marshal.SizeOf(this.sensorResult);
                IntPtr ptr  = Marshal.AllocHGlobal(size);
                Marshal.Copy(data.Data, 0, ptr, size);
                this.sensorResult = (SensorDataResult)Marshal.PtrToStructure(ptr, sensorResult.GetType());
                Marshal.FreeHGlobal(ptr);
                failure = false;
            }
            else
            {
                failure           = true;
                sensorResult.temp = 0;
            }
        }
Beispiel #18
0
        public void GetWeight(out decimal?weight, out bool?isStable)
        {
            weight   = null;
            isStable = false;

            if (scale.IsConnected)
            {
                inData = scale.Read(250);
                // Byte 0 == Report ID?
                // Byte 1 == Scale Status (1 == Fault, 2 == Stable @ 0, 3 == In Motion, 4 == Stable, 5 == Under 0, 6 == Over Weight, 7 == Requires Calibration, 8 == Requires Re-Zeroing)
                // Byte 2 == Weight Unit
                // Byte 3 == Data Scaling (decimal placement)
                // Byte 4 == Weight LSB
                // Byte 5 == Weight MSB

                // FIXME: dividing by 100 probably wont work with
                // every scale, need to figure out what to do with
                // Byte 3
                weight = (Convert.ToDecimal(inData.Data[4]) +
                          Convert.ToDecimal(inData.Data[5]) * 256) / 100;

                switch (Convert.ToInt16(inData.Data[2]))
                {
                case 3: // Kilos
                    weight = weight * (decimal?)2.2;
                    break;

                case 11: // Ounces
                    weight = weight * (decimal?)0.625;
                    break;

                case 12: // Pounds
                    // already in pounds, do nothing
                    break;
                }
                isStable = inData.Data[1] == 0x4;
            }
        }
Beispiel #19
0
        private static async void ReadLoop(HidDevice usbDevice)
        {
            HidDeviceData dataPoint = await usbDevice.ReadAsync();

            while (true)
            {
                dataPoint = await usbDevice.ReadAsync();

                if (dataPoint.Status != HidDeviceData.ReadStatus.Success)
                {
                    throw new InvalidOperationException($"Cannot read from USB device! State was {dataPoint.Status}");
                }

                foreach (var bit in dataPoint.Data)
                {
                    if (bit == 0)
                    {
                        continue;
                    }
                    // Console.WriteLine(bit);
                }
            }
        }
        public TEMPerNancyModule()
        {
            byte[]           temp              = { 0x01, 0x80, 0x33, 0x01, 0x00, 0x00, 0x00, 0x00 };
            HidDevice[]      _deviceList       = HidDevices.Enumerate().ToArray();
            List <HidDevice> _TemperInterfaces = _deviceList.Where(x => x.Attributes.ProductHexId == "0x7401" & x.Attributes.VendorHexId == "0x0C45").ToList();

            device = _TemperInterfaces.Find(x => x.DevicePath.Contains("mi_01"));
            var outData = device.CreateReport();

            outData.ReportId = 0x00;
            outData.Data     = temp;
            device.WriteReport(outData);
            while (outData.ReadStatus == HidDeviceData.ReadStatus.NoDataRead)
            {
                ;
            }
            HidDeviceData data = device.Read();

            byte[] value              = data.Data;
            int    RawReading         = (value[4] & 0xFF) + (value[3] << 8);
            double temperatureCelsius = (Calibration_Scale * (RawReading * (125.0 / 32000.0))) + Calibration_Offset;

            Get["/"] = _ => temperatureCelsius.ToString("0.00");
        }
Beispiel #21
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 ButtonData(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 ButtonData(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;
            }
        }
Beispiel #22
0
        public static void GetWeight()
        {
            if (scaleDevice.IsConnected)
            {
                inData = scaleDevice.Read(250);

                status = inData.Data[1];

                totalOunces = (Convert.ToDouble(inData.Data[4]) + Convert.ToDouble(inData.Data[5]) * 256) / 10;

            }

            ounces = Math.Round(totalOunces % 16.0, 1);
            pounds = (int)(Math.Floor(totalOunces) / 16.0);
            grams = Math.Round(totalOunces * 28.3495231, 1);
        }
Beispiel #23
0
        private void input_thread(HidDevice Device, ScpBus scpBus, int index)
        {
            scpBus.PlugIn(index);
            X360Controller controller = new X360Controller();
            int            timeout    = 10;
            //long last_changed = 0;
            //long last_mi_button = 0;
            bool ss_button_pressed = false;
            bool ss_button_held    = false;

            while (Running)
            {
                HidDeviceData data         = Device.Read(timeout);
                var           currentState = data.Data;
                //bool changed = false;
                if (data.Status == HidDeviceData.ReadStatus.Success && currentState.Length >= 10 && currentState[0] == 3)
                {
                    // NOTE: Console.WriteLine is blocking. If main thread sends a WriteLine while we do a WriteLine here, we're boned and will miss reports!
                    //Console.WriteLine(Program.ByteArrayToHexString(currentState));

                    X360Buttons Buttons = X360Buttons.None;
                    if ((currentState[3] & 64) != 0)
                    {
                        Buttons |= X360Buttons.A;
                    }
                    if ((currentState[3] & 32) != 0)
                    {
                        Buttons |= X360Buttons.B;
                    }
                    if ((currentState[3] & 16) != 0)
                    {
                        Buttons |= X360Buttons.X;
                    }
                    if ((currentState[3] & 8) != 0)
                    {
                        Buttons |= X360Buttons.Y;
                    }
                    if ((currentState[3] & 4) != 0)
                    {
                        Buttons |= X360Buttons.LeftBumper;
                    }
                    if ((currentState[3] & 2) != 0)
                    {
                        Buttons |= X360Buttons.RightBumper;
                    }
                    if ((currentState[3] & 1) != 0)
                    {
                        Buttons |= X360Buttons.LeftStick;
                    }
                    if ((currentState[2] & 128) != 0)
                    {
                        Buttons |= X360Buttons.RightStick;
                    }
                    ss_button_pressed = (currentState[2] & 1) != 0;
                    // [2] & 2 == Assistant, [2] & 1 == Screenshot

                    switch (currentState[1])
                    {
                    default:
                        break;

                    case 0:
                        Buttons |= X360Buttons.Up;
                        break;

                    case 1:
                        Buttons |= X360Buttons.UpRight;
                        break;

                    case 2:
                        Buttons |= X360Buttons.Right;
                        break;

                    case 3:
                        Buttons |= X360Buttons.DownRight;
                        break;

                    case 4:
                        Buttons |= X360Buttons.Down;
                        break;

                    case 5:
                        Buttons |= X360Buttons.DownLeft;
                        break;

                    case 6:
                        Buttons |= X360Buttons.Left;
                        break;

                    case 7:
                        Buttons |= X360Buttons.UpLeft;
                        break;
                    }

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

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


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

                    // Note: The HID reports do not allow stick values of 00.
                    // This seems to make sense: 0x80 is center, so usable values are:
                    // 0x01 to 0x7F and 0x81 to 0xFF.
                    // For our purposes I believe this is undesirable. Subtract 1 from negative
                    // values to allow maxing out the stick values.
                    // TODO: Get an Xbox controller and verify this is standard behavior.
                    for (int i = 4; i <= 7; ++i)
                    {
                        if (currentState[i] <= 0x7F && currentState[i] > 0x00)
                        {
                            currentState[i] -= 0x01;
                        }
                    }

                    ushort LeftStickXunsigned = (ushort)(currentState[4] << 8 | (currentState[4] << 1 & 255));
                    if (LeftStickXunsigned == 0xFFFE)
                    {
                        LeftStickXunsigned = 0xFFFF;
                    }
                    short LeftStickX = (short)(LeftStickXunsigned - 0x8000);

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

                    ushort LeftStickYunsigned = (ushort)(currentState[5] << 8 | (currentState[5] << 1 & 255));
                    if (LeftStickYunsigned == 0xFFFE)
                    {
                        LeftStickYunsigned = 0xFFFF;
                    }
                    short LeftStickY = (short)(-LeftStickYunsigned + 0x7FFF);
                    if (LeftStickY == -1)
                    {
                        LeftStickY = 0;
                    }
                    //if (LeftStickY != controller.LeftStickY)
                    {
                        //	changed = true;
                        controller.LeftStickY = LeftStickY;
                    }

                    ushort RightStickXunsigned = (ushort)(currentState[6] << 8 | (currentState[6] << 1 & 255));
                    if (RightStickXunsigned == 0xFFFE)
                    {
                        RightStickXunsigned = 0xFFFF;
                    }
                    short RightStickX = (short)(RightStickXunsigned - 0x8000);

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

                    ushort RightStickYunsigned = (ushort)(currentState[7] << 8 | (currentState[7] << 1 & 255));
                    if (RightStickYunsigned == 0xFFFE)
                    {
                        RightStickYunsigned = 0xFFFF;
                    }
                    short RightStickY = (short)(-RightStickYunsigned + 0x7FFF);
                    if (RightStickY == -1)
                    {
                        RightStickY = 0;
                    }

                    //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);

                    if (outputReport[1] == 0x08)
                    {
                        byte bigMotor   = outputReport[3];
                        byte smallMotor = outputReport[4];

                        if (smallMotor != Vibration[3] || Vibration[1] != bigMotor)
                        {
                            // We only need to take the mutex if we're modifying the data
                            rumble_mutex.WaitOne();
                            Vibration[1] = bigMotor;
                            Vibration[3] = smallMotor;
                            rumble_mutex.ReleaseMutex();
                            rumbleWaitHandle.Set();
                        }
                    }

                    //last_changed = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
                }

                if (ss_button_pressed && !ss_button_held)
                {
                    ss_button_held = true;
                    try
                    {
                        // TODO: Allow configuring this keybind.
                        ssThread = new Thread(() => System.Windows.Forms.SendKeys.SendWait("^+Z"));
                        ssThread.Start();
                    }
                    catch
                    {
                    }
                }
                else if (ss_button_held && !ss_button_pressed)
                {
                    ss_button_held = false;
                }
            }
        }
Beispiel #24
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;
                if (data.Status == HidDeviceData.ReadStatus.Success && currentState.Length >= 21 && currentState[0] == 4)
                {
                    //Console.WriteLine(Program.ByteArrayToHexString(currentState));
                    X360Buttons Buttons = X360Buttons.None;
                    if ((currentState[1] & 1) != 0)
                    {
                        Buttons |= X360Buttons.A;
                    }
                    if ((currentState[1] & 2) != 0)
                    {
                        Buttons |= X360Buttons.B;
                    }
                    if ((currentState[1] & 8) != 0)
                    {
                        Buttons |= X360Buttons.X;
                    }
                    if ((currentState[1] & 16) != 0)
                    {
                        Buttons |= X360Buttons.Y;
                    }
                    if ((currentState[1] & 64) != 0)
                    {
                        Buttons |= X360Buttons.LeftBumper;
                    }
                    if ((currentState[1] & 128) != 0)
                    {
                        Buttons |= X360Buttons.RightBumper;
                    }

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

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

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



                    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[5] - 128) / 127) * 32767);
                    if (LeftStickX != controller.LeftStickX)
                    {
                        changed = true;
                        controller.LeftStickX = LeftStickX;
                    }

                    short LeftStickY = (short)((Math.Max(-127.0, currentState[6] - 128) / 127) * -32767);
                    if (LeftStickY != controller.LeftStickY)
                    {
                        changed = true;
                        controller.LeftStickY = LeftStickY;
                    }

                    short RightStickX = (short)((Math.Max(-127.0, currentState[7] - 128) / 127) * 32767);
                    if (RightStickX != controller.RightStickX)
                    {
                        changed = true;
                        controller.RightStickX = RightStickX;
                    }

                    short RightStickY = (short)((Math.Max(-127.0, currentState[8] - 128) / 127) * -32767);
                    if (RightStickY != controller.RightStickY)
                    {
                        changed = true;
                        controller.RightStickY = RightStickY;
                    }

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

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

                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);

                    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;
                }
            }
        }
Beispiel #25
0
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            rotateWithMouse = !rotateWithMouse;
        }
        if (!rotateWithMouse)
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                xp += 10.0f;
                movePlayer(xp, yp, zp);
            }
            else if (Input.GetKeyDown(KeyCode.D))
            {
                xp -= 10.0f;
                movePlayer(xp, yp, zp);
            }

            if (Input.GetKeyDown(KeyCode.W))
            {
                zp += 10.0f;
                movePlayer(xp, yp, zp);
            }
            else if (Input.GetKeyDown(KeyCode.S))
            {
                zp -= 10.0f;
                movePlayer(xp, yp, zp);
            }

            if (Input.GetKeyDown(KeyCode.Q))
            {
                yp += 10.0f;
                movePlayer(xp, yp, zp);
            }
            else if (Input.GetKeyDown(KeyCode.E))
            {
                yp -= 10.0f;
                movePlayer(xp, yp, zp);
            }
        }
        else
        {
            float h = 2.0f * Input.GetAxis("Mouse X");
            float v = 2.0f * Input.GetAxis("Mouse Y");
            transform.Rotate(v, h, 0);
        }

        InData = HidDevice.Read();
        Byte[] InDataByteArray = InData.Data;

        //Euler xyz
        x = BitConverter.ToSingle(InDataByteArray, 1);
        y = BitConverter.ToSingle(InDataByteArray, 5);
        z = BitConverter.ToSingle(InDataByteArray, 9);

        //quat wxyz
        qw = BitConverter.ToSingle(InDataByteArray, 13);
        qx = BitConverter.ToSingle(InDataByteArray, 17);
        qy = BitConverter.ToSingle(InDataByteArray, 21);
        qz = BitConverter.ToSingle(InDataByteArray, 25);
        print(x.ToString() + " " + y.ToString() + " " + z.ToString() + " " + qw.ToString() + " " + qx.ToString() + " " + qy.ToString() + " " + qz.ToString());

        movePlayer(x, y, z, qw, qx, qy, qz);
    }
Beispiel #26
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;
                     */
                }
            }
        }
Beispiel #27
0
 private void ControlServosHome_Callback(HidDeviceData data)
 {
     DrawStatusCanvasReceiveCanvasBlip(data.Status == HidDeviceData.ReadStatus.Success ? Brushes.Green : Brushes.Red, 2);
 }
Beispiel #28
0
        public void GetWeight(out decimal?weightInG, out decimal?weightInOz, out decimal?weightInLb, out decimal?weightInKg, out bool?isStable)
        {
            decimal?weight;

            weight     = null;
            weightInG  = null;
            weightInOz = null;
            weightInLb = null;
            weightInKg = null;
            isStable   = false;

            if (scale.IsConnected)
            {
                inData = scale.Read(250);
                // Byte 0 == Report ID?
                // Byte 1 == Scale Status (1 == Fault, 2 == Stable @ 0, 3 == In Motion, 4 == Stable, 5 == Under 0, 6 == Over Weight, 7 == Requires Calibration, 8 == Requires Re-Zeroing)
                // Byte 2 == Weight Unit
                // Byte 3 == Data Scaling (decimal placement)
                // Byte 4 == Weight LSB
                // Byte 5 == Weight MSB

                // FIXME: dividing by 100 probably wont work with
                // every scale, need to figure out what to do with
                // Byte 3
                //weight = (Convert.ToDecimal(inData.Data[4]) + Convert.ToDecimal(inData.Data[5]) * 256) / 10;

                Console.WriteLine("scale status {0}", inData.Data[1]);

                switch (Convert.ToInt16(inData.Data[2]))
                {
                case 2:      // g
                    weight     = (Convert.ToDecimal(inData.Data[4]) + Convert.ToDecimal(inData.Data[5]) * 256);
                    weightInG  = weight;
                    weightInOz = weight * (decimal?)0.035274;
                    weightInLb = weight * (decimal?)0.00220462;
                    weightInKg = weight * (decimal?)0.001;
                    break;

                case 3:      // kg
                    weight     = (Convert.ToDecimal(inData.Data[4]) + Convert.ToDecimal(inData.Data[5]) * 256) / 100;
                    weightInG  = weight * (decimal?)1000;
                    weightInOz = weight * (decimal?)35.274;
                    weightInLb = weight * (decimal?)2.20462;
                    weightInKg = weight;
                    break;

                case 11:     // Ounces
                    weight     = (Convert.ToDecimal(inData.Data[4]) + Convert.ToDecimal(inData.Data[5]) * 256) / 10;
                    weightInG  = weight * (decimal?)28.3495;
                    weightInOz = weight;
                    weightInLb = weight * (decimal?)0.0625;
                    weightInKg = weight * (decimal?)0.0283495;
                    break;

                case 12:     // Pounds
                    // already in pounds, do nothing
                    weight = (decimal?)BitConverter.ToInt16(new byte[] { inData.Data[4], inData.Data[5] }, 0) *
                             Convert.ToDecimal(Math.Pow(10, (sbyte)inData.Data[3]));
                    weightInG  = weight * (decimal?)453.592;
                    weightInOz = weight * (decimal?)16;
                    weightInLb = weight;
                    weightInKg = weight * (decimal?)0.453592;
                    break;
                }
                isStable = inData.Data[1] == 0x4;
            }
        }
Beispiel #29
0
 void device_DataRead(HidDevice device, HidDeviceData data)
 {
     Debug.WriteLine(data.ToString());
 }