Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi
im writing the wireless program that using ,
joy stick class that i downloaded from this site
, but there is delay when i send command , with joy stick,
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX.DirectInput;
using System.Diagnostics;

namespace new_joystick
{
        public class Joystick
        {
            private Device joystickDevice;
            private JoystickState state;

            private int axisCount;
            /// <summary>
            /// Number of axes on the joystick.
            /// </summary>
            public int AxisCount
            {
                get { return axisCount; }
            }

            private int axisA;
            /// <summary>
            /// The first axis on the joystick.
            /// </summary>
            public int AxisA
            {
                get { return axisA; }
            }

            private int axisB;
            /// <summary>
            /// The second axis on the joystick.
            /// </summary>
            public int AxisB
            {
                get { return axisB; }
            }

            private int axisC;
            /// <summary>
            /// The third axis on the joystick.
            /// </summary>
            public int AxisC
            {
                get { return axisC; }
            }

            private int axisD;
            /// <summary>
            /// The fourth axis on the joystick.
            /// </summary>
            public int AxisD
            {
                get { return axisD; }
            }

            private int axisE;
            /// <summary>
            /// The fifth axis on the joystick.
            /// </summary>
            public int AxisE
            {
                get { return axisE; }
            }

            private int axisF;
            /// <summary>
            /// The sixth axis on the joystick.
            /// </summary>
            public int AxisF
            {
                get { return axisF; }
            }
            private IntPtr hWnd;

            private bool[] buttons;
            /// <summary>
            /// Array of buttons availiable on the joystick. This also includes PoV hats.
            /// </summary>
            public bool[] Buttons
            {
                get { return buttons; }
            }

            private string[] systemJoysticks;

            /// <summary>
            /// Constructor for the class.
            /// </summary>
            /// <param name="window_handle">Handle of the window which the joystick will be "attached" to.</param>
            public Joystick(IntPtr window_handle)
            {
                hWnd = window_handle;
                axisA = -1;
                axisB = -1;
                axisC = -1;
                axisD = -1;
                axisE = -1;
                axisF = -1;
                axisCount = 0;
            }

            private void Poll()
            {
                try
                {
                    // poll the joystick
                    joystickDevice.Poll();
                    // update the joystick state field
                    state = joystickDevice.CurrentJoystickState;
                }
                catch (Exception err)
                {
                    // we probably lost connection to the joystick
                    // was it unplugged or locked by another application?
                    Debug.WriteLine("Poll()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                }
            }

            /// <summary>
            /// Retrieves a list of joysticks attached to the computer.
            /// </summary>
            /// <example>
            /// [C#]
            /// <code>
            /// JoystickInterface.Joystick jst = new JoystickInterface.Joystick(this.Handle);
            /// string[] sticks = jst.FindJoysticks();
            /// </code>
            /// </example>
            /// <returns>A list of joysticks as an array of strings.</returns>
            public string[] FindJoysticks()
            {
                systemJoysticks = null;

                try
                {
                    // Find all the GameControl devices that are attached.
                    DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

                    // check that we have at least one device.
                    if (gameControllerList.Count > 0)
                    {
                        systemJoysticks = new string[gameControllerList.Count];
                        int i = 0;
                        // loop through the devices.
                        foreach (DeviceInstance deviceInstance in gameControllerList)
                        {
                            // create a device from this controller so we can retrieve info.
                            joystickDevice = new Device(deviceInstance.InstanceGuid);
                            joystickDevice.SetCooperativeLevel(hWnd,
                                CooperativeLevelFlags.Background |
                                CooperativeLevelFlags.NonExclusive);

                            systemJoysticks[i] = joystickDevice.DeviceInformation.InstanceName;

                            i++;
                        }
                    }
                }
                catch (Exception err)
                {
                    Debug.WriteLine("FindJoysticks()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                }

                return systemJoysticks;
            }

            /// <summary>
            /// Acquire the named joystick. You can find this joystick through the <see cref="FindJoysticks"/> method.
            /// </summary>
            /// <param name="name">Name of the joystick.</param>
            /// <returns>The success of the connection.</returns>
            public bool AcquireJoystick(string name)
            {
                try
                {
                    DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
                    int i = 0;
                    bool found = false;
                    // loop through the devices.
                    foreach (DeviceInstance deviceInstance in gameControllerList)
                    {
                        if (deviceInstance.InstanceName == name)
                        {
                            found = true;
                            // create a device from this controller so we can retrieve info.
                            joystickDevice = new Device(deviceInstance.InstanceGuid);
                            joystickDevice.SetCooperativeLevel(hWnd,
                                CooperativeLevelFlags.Background |
                                CooperativeLevelFlags.NonExclusive);
                            break;
                        }

                        i++;
                    }

                    if (!found)
                        return false;

                    // Tell DirectX that this is a Joystick.
                    joystickDevice.SetDataFormat(DeviceDataFormat.Joystick);

                    // Finally, acquire the device.
                    joystickDevice.Acquire();

                    // How many axes?
                    // Find the capabilities of the joystick
                    DeviceCaps cps = joystickDevice.Caps;
                    Debug.WriteLine("Joystick Axis: " + cps.NumberAxes);
                    Debug.WriteLine("Joystick Buttons: " + cps.NumberButtons);

                    axisCount = cps.NumberAxes;

                    UpdateStatus();
                }
                catch (Exception err)
                {
                    Debug.WriteLine("FindJoysticks()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                    return false;
                }

                return true;
            }

            /// <summary>
            /// Unaquire a joystick releasing it back to the system.
            /// </summary>
            public void ReleaseJoystick()
            {
                joystickDevice.Unacquire();
            }

            /// <summary>
            /// Update the properties of button and axis positions.
            /// </summary>
            public void UpdateStatus()
            {
                Poll();

                int[] extraAxis = state.GetSlider();
                //Rz Rx X Y Axis1 Axis2
                axisA = state.Rz;
                axisB = state.Rx;
                axisC = state.X;
                axisD = state.Y;
                axisE = extraAxis[0];
                axisF = extraAxis[1];
 }

i think there is section that make a delay
C#
// not using buttons, so don't take the tiny amount of time it takes to get/parse  please
                byte[] jsButtons = state.GetButtons();
                buttons = new bool[jsButtons.Length];

                int i = 0;
                foreach (byte button in jsButtons)
                {
                    buttons[i] = button &gt;= 20;
                    i++;
                }
            }
        }

i think that the delay of the button (button not axis) it`s depend on this last block.
and it ` s section that connect and send data
void senddata(string messagebody)
        {
            try
            {
                byte[] data = new byte[100];
                data = Encoding.ASCII.GetBytes(messagebody);
                client.Send(data, data.Length, SocketFlags.None);
            }
            catch(Exception F)
            {
                label2.Text = F.Message;
            }
        }
        Socket client;
        Socket newsock;
        private void button3_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[100];
            IPAddress ip = IPAddress.Parse("192.168.0.100");
            IPEndPoint ipep = new IPEndPoint(ip, 8001);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(1);
            client = newsock.Accept();
            IPEndPoint newclinet = (IPEndPoint)client.RemoteEndPoint;
            label2.Text = "Connected with  " + newclinet.Address + "   at port  " + newclinet.Port;
            string welcome = "Welcome goh to U.S.R.F wireless program";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);
            timer1.Enabled = true;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            int recv;
            data = new byte[1024];
            recv = client.Receive(data);
            if (recv != 0)
            {
                label3.Text = " ";
                label3.Text += Encoding.ASCII.GetString(data, 0, recv);
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            senddata(textBox1.Text); 
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }
i use two timer for send and recieve data in server program and one thread and one timer for send and recieve in client ,,, can anyone tell me why my program has delay ???
Posted
Updated 29-Mar-10 6:26am
v2

First of all, you provided way too much code. We're not going to debug your program for you. It's up to you to figure out what's going on and where things aren't working.

Secondly, it's nearly impossible to tell where you're seeing a "delay".

I would suggest using the DateTime class and the Now() method to determine what is taking so long, and then come back to us with the code that it taking a long time.

To do that, create a new variable called something like StartTime and set it to DateTime.Now(). For instance something like:
C#
private void Poll()
{
      DateTime startTime = DateTime.Now;

      try
      {
           // poll the joystick
           joystickDevice.Poll();

           Debug.Print("joystickDevice.Poll(): " + 
                       DateTime.Now.Subtract(startTime).TotalMilliseconds.ToString() +
                       " ms")

           // update the joystick state field
           state = joystickDevice.CurrentJoystickState;
      }
      catch (Exception err)
      {
           // we probably lost connection to the joystick
           // was it unplugged or locked by another application?
           Debug.WriteLine("Poll()");
           Debug.WriteLine(err.Message);
           Debug.WriteLine(err.StackTrace);
      }
}


Try that in places you think could be slowing it down and you will be able to see what is "delaying" your program.
 
Share this answer
 
v2
Hi,

add one method:
public static void log(string s) {
    if (s.Length!=0) s=DateTime.Now.ToString("HH:mm:ss.fff  ")+s;
    Console.WriteLine(s);
    // optionally uncomment:
    // File.AppendAllText("logfile.txt", s+Environment.NewLine);
}


then replace all debug printing by calls to it. That way all your output will be timestamped and the delays should be obvious.

:)
 
Share this answer
 
There are numerous reasons why there could be 'delay'. If it seems to be taking too long to actually register that you've pressed a button then you may want to look into where you call UpdateStatus, it should be called frequently because without it you will not get any information on which keys have been pressed since the last call.

Secondly, if you're sending the input over a network then there are going to be small delays (5 - 100's of milliseconds) and if you are using timers to send and receive data then the delay could simply be the time between Ticks of the timer. It is difficult for use to know, use the information others have given to determine where the delay is and then you will stand a good chance of fixing it.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900