/// <summary>
        /// Retrieves the Predicted Observed Values for a specified PredictedObserved Id
        /// </summary>
        /// <param name="connectStr"></param>
        /// <param name="predictedObservedId"></param>
        /// <returns></returns>
        private static DataTable GetPredictedObservedValues(SqlConnection sqlCon, int predictedObservedId)
        {
            DataTable dtResults = new DataTable();

            try
            {
                string strSQL = "SELECT * FROM PredictedObservedValues WHERE PredictedObservedDetailsId = @PredictedObservedDetailsId ORDER BY ID DESC";
                using (SqlCommand commandER = new SqlCommand(strSQL, sqlCon))
                {
                    commandER.CommandType = CommandType.Text;
                    commandER.Parameters.AddWithValue("@PredictedObservedDetailsId", predictedObservedId);

                    //SqlDataReader reader = commandER.ExecuteReader();
                    //dtResults.Load(reader);
                    //reader.Close();
                    string response   = Comms.SendQuery(commandER, "reader");
                    var    jsonObject = JsonConvert.DeserializeObject(response);
                    dtResults = JsonConvert.DeserializeObject <DataTable>(jsonObject.ToString());
                }
            }
            catch (Exception ex)
            {
                Utilities.WriteToLogFile(string.Format("ERROR:  Unable to retrieve Predicted Observed Values for PredictedObserved Id {0}: {1}", predictedObservedId.ToString(), ex.Message.ToString()));
            }
            return(dtResults);
        }
Пример #2
0
        static void Main(string[] args)
        {
            Calls    call  = new Calls();
            CommNode comm1 = new Comms(1);
            CommNode comm2 = new Comms(2);

            comm1.LinkCallback(new Ping(), new CallBack(call.PingCallback));
            comm2.LinkCallback(new Ping(), new CallBack(call.PingCallback));

            comm1.InitConnection(TransportProtocol.ZIGBEE_LINK, "COM5", "", 57600);
            comm2.InitConnection(TransportProtocol.ZIGBEE_LINK, "COM6", "", 57600);
            Console.WriteLine(comm1.AddAddress(2, "0013A2004067E4AE", 0));
            Console.WriteLine(comm2.AddAddress(1, "0013A20040917A31", 0));
            //comm1.InitConnection(TransportProtocol.UDP_LINK, "1337", "127.0.0.1", 57600);
            //comm2.InitConnection(TransportProtocol.UDP_LINK, "1338", "127.0.0.1", 57600);
            //Console.WriteLine(comm1.AddAddress(2, "127.0.0.1", 1338));
            //Console.WriteLine(comm2.AddAddress(1, "127.0.0.1", 1337));
            //Ping ping = new Ping("I am from C#!");
            comm1.Run();
            comm2.Run();
            Ping ping = new Ping("From C#, From the xbee!!");

            //TargetDesignationCommand command = new TargetDesignationCommand(45.34f, 23.22f, 234.44f);
            while (true)
            {
                comm1.Send(ping, 2);
                //comm1.Send(command, 1);
                System.Threading.Thread.Sleep(1000);
            }
            comm1.Stop(); //This call is essential to stop threads because finalizer may not be called.
            comm2.Stop();
        }
Пример #3
0
        public override async Task Started()
        {
            // Request server configuration
            this.config = await Comms.Event(CharacterCustomizationEvents.Configuration).ToServer().Request <CharactersCustomizationConfiguration>();

            //Comms.Event(CharacterEvents.Selected).FromServer().On<CharacterSession>(OnCharacterSelected);
        }
        public void RegionLoaded(Scene scene)
        {
            if (!Enabled)
            {
                return;
            }

            BaseScene = scene;

            Comms = BaseScene.RequestModuleInterface <IScriptModuleComms>();
            if (Comms == null)
            {
                m_log.WarnFormat("{0} ScriptModuleComms interface not defined", LogHeader);
                Enabled = false;

                return;
            }

            // Register as LSL functions all the [ScriptInvocation] marked methods.
            Comms.RegisterScriptInvocations(this);
            Comms.RegisterConstants(this);

            // When an object is modified, we might need to update its extended physics parameters
            BaseScene.EventManager.OnObjectAddedToScene     += EventManager_OnObjectAddedToScene;
            BaseScene.EventManager.OnSceneObjectPartUpdated += EventManager_OnSceneObjectPartUpdated;
        }
Пример #5
0
 // Start is called before the first frame update
 void Start()
 {
     this.ui            = GameObject.Find("UI").GetComponent <UI>();
     this.comms         = GameObject.Find("WebSocket").GetComponent <Comms>();
     this.environment   = GameObject.Find("Environment").GetComponent <Environment>();
     this.playerManager = GameObject.Find("PlayerManager").GetComponent <PlayerManager>();
 }
Пример #6
0
            public void select()
            {
                ushort cType = 0;

                byte[] serialarray = new byte[4];
                byte[] serBytes    = new byte[serialarray.Length];

                int sersize  = Marshal.SizeOf(byte.MaxValue) * serialarray.Length;
                int datasize = Marshal.SizeOf(byte.MaxValue) * carddata.Length;

                serial = Marshal.AllocHGlobal(sersize);
                data   = Marshal.AllocHGlobal(datasize);

                StringBuilder cardcap = new StringBuilder();

                String serialNumber = "";
                int    serialLength = 0;

                byte serlength;
                byte datalength;

                int i = 0;

                while (Comms.rf_request(_icDev, (char)0x26, ref cType) != 0)
                {
                    System.Threading.Thread.Sleep(500);
                }


                if (Comms.rf_anticoll(_icDev, (char)0x04, serial, out serlength) != 0)
                {
                    Debug.WriteLine("LS8000:: Could not perform anti collision on card!");
                }

                if (serlength != null)
                {
                    serBytes = new byte[serialarray.Length];
                    Marshal.Copy(serial, serBytes, 0, serialarray.Length);
                    serialNumber = BitConverter.ToString(serBytes);
                }

                if (serialNumber == null)
                {
                    Debug.WriteLine("LS8000:: Serial number is null!!");
                }

                if (serlength != null)
                {
                    serialLength = serlength;
                }

                if (Comms.rf_select(_icDev, serBytes, serlength, ref cardcap) != 0)
                {
                    Debug.WriteLine("LS8000:: Could not activate card!");
                }

                serialNumber = serial.ToString();
                Debug.WriteLine("LS8000:: Serial is " + serialNumber);
                Marshal.FreeHGlobal(serial);
            }
Пример #7
0
        private void BeginGetNodes(Node node)
        {               // GetFilesInFolder
            Comms helper = new Comms(new Uri(_website + "FileUploadService.asmx/GetFoldersInFolder"), "POST", false, new KeyValuePair <string, string>("folder", HttpUtility.UrlEncode(node.ID)));

            helper.ResponseComplete += new HttpResponseCompleteEventHandler(EndGetNodes);
            helper.Execute(node);
        }
Пример #8
0
        public Form1()
        {
            InitializeComponent();

            // start a new instance of the xbox one controller
            xb1c = new XInputController();

            // if there is a connection then update the current values
            if (xb1c.connected)
            {
                base_val     = xb1c.leftThumb.X;
                shoulder_val = xb1c.leftThumb.Y;
                elbow_val    = xb1c.rightThumb.Y;
                gripper_val  = xb1c.rightThumb.X;
            }
            else
            {
                MessageBox.Show(this, "The Xbox One controller did not connect properly.\n", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            //init xbees
            comms = new Comms(THIS_ID);
            comms.InitConnection(TransportProtocol.ZIGBEE_LINK, "COM3", "", 57600);
            comms.AddAddress(UGV_ID, "0013A20040917A31", 0);
            comms.LinkCallback(new NGCP.ArmPosition(0, 0, 0, 0), new CallBack(ArmPositionCallBack));
            comms.LoadKey("NGCP Project 2016");
            comms.Run();
            // set timer event to start reading and updating from the controller
            timer1.Start();
        }
Пример #9
0
        public override void Clear()
        {
            Temps.Clear();
            Comms.Clear();
            LastXact = null;

            base.Clear();
        }
Пример #10
0
        private void BeginNewFolder(string path, string folderName)
        {               // GetFilesInFolder
            Comms helper = new Comms(new Uri(_website + "FileUploadService.asmx/NewFolder"), "POST", false, new KeyValuePair <string, string>("path", HttpUtility.UrlEncode(path)),
                                     new KeyValuePair <string, string>("folderName", HttpUtility.UrlEncode(folderName)));

            helper.ResponseComplete += new HttpResponseCompleteEventHandler(EndNewFolder);
            helper.Execute(testTree.Selected);
        }
Пример #11
0
 public void OnDestroy()
 {
     CloseChannel();
     if (Comms != null)
     {
         Comms.UnsubscribeFromVoiceActivation(this);
     }
 }
Пример #12
0
        private void updateSAC()
        {
            Comms.txrx("SMS " + Globals.Speed.ToString());
            Comms.txrx("SAS " + Globals.Acc.ToString());

            if (SD.controller == controllerType.ProScan)
            {
                Comms.txrx("SCS " + Globals.Curve.ToString());
            }
        }
Пример #13
0
        protected override void OnDestroy()
        {
            CloseChannel();

            if (Comms != null)
            {
                Comms.UnsubscribeFromVoiceActivation(this);
            }

            base.OnDestroy();
        }
Пример #14
0
 private bool openConnection()
 {
     if (Comms.txrx("COMP 0") != "")
     {
         Comms.txrx("RES S 1");
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #15
0
 private bool checkConnection()
 {
     if (Comms.txrx("$") == "")
     {
         connectionLost();
         return(false);
     }
     else
     {
         return(true);
     }
 }
Пример #16
0
 public bool authenticate(byte[] key, byte block)
 {
     if (Comms.rf_M1_authentication2(_icDev, _authMode, block, key) != 0)
     {
         Debug.WriteLine("LS8000:: Could not authenticate card, key error!");
         return(false);
     }
     else
     {
         return(true);
     }
 }
Пример #17
0
        public void InitilizeComms(ChatManagerServer ChatServer, MultiplayerManagerBase Multiplayer)
        {
            Comms = new Comms(this);
            Comms.RegisterHandlers();

            _ChatManager = ChatServer;
            _MP          = Multiplayer;

            //initilize PlayerWatcher
            MP.PlayerJoined += MP_PlayerJoined;
            MP.PlayerLeft   += MP_PlayerLeft;
        }
Пример #18
0
        private void cmdGetPvrList_Click(object sender, EventArgs e)
        {
            Comms c = new Comms();

            c.IPAddress = this.txtIP.Text;
            pvr         = c.GetPvrList();

            c = null;

            RefreshList();

            MessageBox.Show("PVR Information Downloaded");
        }
Пример #19
0
        private void MarkersTick()
        {
            var pedPos = Game.PlayerPed.Position;

            foreach (var marker in this.markers)
            {
                API.DrawMarker(marker.MarkerType,
                               marker.Location.X, marker.Location.Y, marker.Location.Z,
                               marker.Rotation.X, marker.Rotation.Y, marker.Rotation.Z,
                               marker.Direction.X, marker.Direction.Y, marker.Direction.Z,
                               marker.Scale.X, marker.Scale.Y, marker.Scale.Z,
                               marker.Color.Red, marker.Color.Green, marker.Color.Blue, marker.IsVisible ? marker.Color.Alpha : 0,
                               marker.BobUpDown, marker.FaceCamera, 2, marker.RotateWithHeading,
                               marker.TextureDictionary, marker.TextureName, marker.DrawOnEnts);

                var markerLocation    = ToCfxVector(marker.Location);
                var pedMarkerDistance = markerLocation.DistanceToSquared(pedPos);

                // Check if inside marker
                if (pedMarkerDistance < marker.Scale.X + 1.5f && pedMarkerDistance < marker.Scale.Y + 1.5f && pedMarkerDistance <= marker.Scale.Z + 1.5f)
                {
                    // Check if the player has entered the marker already
                    if (!marker.HasPlayerInside)
                    {
                        // If not, set as is inside
                        marker.HasPlayerInside = true;
                        // Emit the event
                        Comms.Event(MarkersEvents.MarkerEntered).ToClient().Emit(marker);
                    }
                }
                else if (marker.HasPlayerInside)
                {
                    // If not inside the marker anymore, but the marker previously had the player inside
                    // set as not inside
                    marker.HasPlayerInside = false;
                    // Emit the event
                    Comms.Event(MarkersEvents.MarkerLeft).ToClient().Emit(marker);
                }
            }

            foreach (var marker in this.GetInsideMarkersList())
            {
                // Check if the marker's key was clicked while inside marker
                if (marker.IsClickable && marker.Hotkey.IsJustPressed())
                {
                    Logger.Info("Pressed " + marker.Hotkey.ControlNativeName);
                    Comms.Event(MarkersEvents.MarkerClicked).ToClient().Emit(marker);
                }
            }
        }
Пример #20
0
        public ProcessHandler(Form1 form)
        {
            this.form     = form;
            this.comms    = new Comms();
            this.messages = new Messages(comms);

            comms.setterMessages(messages);

            Thread listener = new Thread(() => comms.StartListening(8081));

            listener.Start();

            Set_apps();
        }
Пример #21
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById <Button>(Resource.Id.MyButton);
            Comms  comms  = new Comms(new TcpClient("192.168.0.30", 1490));

            button.Click += delegate { comms.Send("Request Build"); };
        }
Пример #22
0
        public UserUI()
        {
            string PortParams = "";

            InitializeComponent();

            try
            {
                XmlDocument config = new XmlDocument();

                config.Load(Application.StartupPath + "\\App.config");

                foreach (XmlNode N in config.SelectNodes("Config/*"))
                {
                    switch (N.Name)
                    {
                    case "PortParams":
                        PortParams = N.InnerText;
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show("Config file not found or invalid.", this.Text);
                System.Environment.Exit(1);
            }

#if DEBUG
            PortParams = "com29:115200,N,8,1,P";
#endif

            new SerialComms(PortParams, Comms.ResetMode.None);

            if (!Comms.com.IsOpen)
            {
                this.com = null;
                MessageBox.Show("Unable to open serial port!", this.Text);
                System.Environment.Exit(2);
            }

            GrblLanguage.language = "en_US";

            GrblInfo.Get();
            GrblSettings.Load();

            this.Text += ", Grbl version " + GrblInfo.Version;
        }
Пример #23
0
        public override async Task Started()
        {
            // Lookup local identity from server
            this.Identity = await this.Comms.Event(IdentityManagerEvents.Identity).ToServer().Request <Identity>();

            // Create events
            Comms.Event(IdentityManagerEvents.GetLocalIdentity).FromClient().OnRequest(e => e.Reply(GetLocalIdentity()));

            #region Example Debug
            this.Logger.Debug($"From server config: {this.Identity.UserId.ToString()}");
            foreach (CharacterData c in this.Identity.Characters)
            {
                this.Logger.Debug($"Character: {c.CharacterId.ToString()} - {c.FirstName} {c.LastName}");
            }
            #endregion
        }
Пример #24
0
        /// <summary>
        /// This method prints the default check with respect to your assembly name, MessageLanguage and individual user settings
        /// </summary>
        public void Notify()
        {
            if (notified)
            {
                return;
            }

            notified = true;

            // ex. "You are using the latest version of [NAME]"
            Comms.Print(
                Translations.GetTranslation(
                    ("updater_" + (Success ? GitVersion == LocalVersion ? "updated" : "available" : "error")).Replace(
                        "[NAME]",
                        aName),
                    MessageLanguage));
        }
Пример #25
0
        /// <summary>
        /// This method prints the default check with respect to your assembly name, MessageLanguage and individual user settings
        /// </summary>
        public void Notify()
        {
            string key;

            if (!this.Success)
            {
                key = "updater_failure";
            }
            else if (this.IsUpdated)
            {
                key = "updater_updated";
            }
            else
            {
                key = "updater_outdated";
            }

            Comms.Print(Creator.MainMenu.GetTranslation(key).Replace("[NAME]", this.assemblyName));
        }
Пример #26
0
        // constructor
        public CHopper()
        {
            // init SSP handles
            m_cmd    = new SSP_COMMAND();
            m_keys   = new SSP_KEYS();
            m_sspKey = new SSP_FULL_KEY();
            m_info   = new SSP_COMMAND_INFO();

            m_NumberOfChannels    = 0;
            m_ProtocolVersion     = 0;
            m_CoinMechEnabled     = true;
            m_Comms               = new CCommsWindow("SMART Hopper");
            m_UnitDataList        = new List <ChannelData>();
            m_CurrentPollResponse = new byte[255];

            if (Properties.Settings.Default.Comms)
            {
                Comms.Show();
            }
        }
Пример #27
0
        /// <summary>
        /// Deletes all Data for a specified Pull RequestId
        /// </summary>
        /// <param name="connectStr"></param>
        /// <param name="pullRequestId"></param>
        private static void DeleteByPullRequest(SqlConnection sqlCon, int pullRequestId)
        {
            try
            {
                using (SqlCommand commandENQ = new SqlCommand("usp_DeleteByPullRequestId", sqlCon))
                {
                    // Configure the command and parameter.
                    commandENQ.CommandType    = CommandType.StoredProcedure;
                    commandENQ.CommandTimeout = 0;
                    commandENQ.Parameters.AddWithValue("@PullRequestID", pullRequestId);

                    //commandENQ.ExecuteNonQuery();
                    Comms.SendQuery(commandENQ, "stored");
                }
            }
            catch (Exception ex)
            {
                Utilities.WriteToLogFile(string.Format("    ERROR:  Unable to remove data for Pull Request Id: {0}: {1}.", pullRequestId, ex.Message.ToString()));
            }
        }
Пример #28
0
            public byte[] readBlock(byte block)
            {
                //StringBuilder carddata = new StringBuilder();
                byte datalength;

                if (Comms.rf_M1_read(_icDev, block, data, out datalength) != 0)
                {
                    Debug.WriteLine("LS8000:: Could not read card!");
                }

                Marshal.Copy(data, carddata, 0, carddata.Length);
                Marshal.FreeHGlobal(data);

                Debug.WriteLine("LS8000:: Card-data: " + carddata);

                Comms.rf_halt(_icDev);
                Comms.rf_beep(_icDev, '9');
                Comms.rf_light(_icDev, '2');

                return(carddata);
            }
Пример #29
0
        public IHttpActionResult GetAcceptedStatsStatusAndUpdateGithub(int id)
        {
            Utilities.WriteToLogFile("-----------------------------------");
            double PercentPassed = 0;
            bool   passed        = false;

            string connectStr = Utilities.GetConnectionString();

            using (SqlConnection sqlCon = new SqlConnection(connectStr))
            {
                sqlCon.Open();
                try
                {
                    string strSQL = "SELECT  100 * COUNT(CASE WHEN [PassedTests] = 100 THEN 1 ELSE NULL END) / COUNT(CASE WHEN [PassedTests] IS NOT NULL  THEN 1 ELSE 0 END) as PercentPassed "
                                    + " FROM  [dbo].[ApsimFiles] AS a "
                                    + "    INNER JOIN[dbo].[PredictedObservedDetails] AS p ON a.ID = p.ApsimFilesID "
                                    + "  WHERE a.[PullRequestId] = @PullRequestId ";
                    using (SqlCommand commandES = new SqlCommand(strSQL, sqlCon))
                    {
                        commandES.CommandType = CommandType.Text;
                        commandES.Parameters.AddWithValue("@PullRequestId", id);
                        //object obj = commandES.ExecuteScalar();
                        //PercentPassed = double.Parse(obj.ToString());
                        string response = Comms.SendQuery(commandES, "scalar");
                        PercentPassed = JsonConvert.DeserializeObject <double>(response);
                    }
                    if (PercentPassed == 100)
                    {
                        passed = true;
                    }
                }
                catch (Exception ex)
                {
                    Utilities.WriteToLogFile(string.Format("ERROR:  Pull Request Id {0}, Unable to determine Passed/Failed status: {1}", id.ToString(), ex.Message.ToString()));;
                }
                CallGitHubWithPassFail(id, passed);
                Utilities.WriteToLogFile(string.Format("   Pull Request Id {0}, PassedTestsStatus verified and Github updated.", id.ToString()));;
            }
            return(Ok());
        }
Пример #30
0
        public UasBase(LagoVista.IoT.DeviceManagement.Core.Models.Device device)
        {
            _device = device;

            Acc = new ObservableCollection <DOF3Sensor>();
            Acc.Add(new DOF3Sensor());
            Gyro = new ObservableCollection <DOF3Sensor>();
            Gyro.Add(new DOF3Sensor());
            Magnometer = new ObservableCollection <DOF3Sensor>();
            Magnometer.Add(new DOF3Sensor());
            EKFStatus = new EKF();
            GPSs      = new ObservableCollection <GPS>();
            GPSs.Add(new GPS());
            Batteries = new ObservableCollection <Battery>();
            Batteries.Add(new Battery());
            SystemStatus     = new SystemStatus();
            Attitude         = new Attitude();
            FlightController = new FlightController();
            PowerStatus      = new PowerStatus();
            RangeFinder      = new RangeFinder();
            Comms            = new Comms();
            Location         = new GeoLocation();

            Channels = new ObservableCollection <RCChannel>();
            for (var idx = 0; idx < 16; ++idx)
            {
                Channels.Add(new RCChannel());
            }

            ServoOutputs = new ObservableCollection <ServoOutput>();
            for (var idx = 0; idx < 16; ++idx)
            {
                ServoOutputs.Add(new ServoOutput());
            }

            ComponentId = 1;
            SystemId    = 1;

            Sensors = new SensorList();
        }
 public TwoPlayerServerWrapper(TwoPlayerBaseGame game, Comms.Server server)
 {
     this.game = game;
     this.server = server;
 }
Пример #32
0
		private void BeginNewFolder(string path, string folderName)
		{	// GetFilesInFolder
            Comms helper = new Comms(new Uri(_website + "FileUploadService.asmx/NewFolder"), "POST", false, new KeyValuePair<string, string>("path", HttpUtility.UrlEncode(path)),
				new KeyValuePair<string, string>("folderName", HttpUtility.UrlEncode(folderName)));
			helper.ResponseComplete += new HttpResponseCompleteEventHandler(EndNewFolder);
			helper.Execute(testTree.Selected);
		}
Пример #33
0
		private void BeginGetNodes(Node node)
		{	// GetFilesInFolder
            Comms helper = new Comms(new Uri(_website + "FileUploadService.asmx/GetFoldersInFolder"), "POST", false, new KeyValuePair<string, string>("folder", HttpUtility.UrlEncode(node.ID)));
			helper.ResponseComplete += new HttpResponseCompleteEventHandler(EndGetNodes);
			helper.Execute(node);
		}
Пример #34
0
        static void receiver_DataReceived(object sender, Comms.DataArgs e)
        {
            try
            {
                Dictionary<Comms.CommandEncoding.CommandFields, short> state = Comms.CommandEncoding.Encoder.Decode(e.Data);
                if (useAutonomy)
                {
                    // Read mode
                    if (state.ContainsKey(CommandFields.Mode))
                        if ((Mode)state[CommandFields.Mode] != Mode.Null)
                        {
                            // Reset timer
                            stopwatch.Restart();
                            // Switch mode
                            mode = (Mode)state[CommandFields.Mode];
                            Console.WriteLine("Switched to: " + mode.ToString());
                        }

                    // Enqueue state if not autonomous
                    switch (mode)
                    {
                        case Mode.Manual:
                            // Stop autonomy if active
                            if (autonomy.Started)
                                autonomy.Stop();
                            // Enqueue current state from controller
                            stateQueue.Enqueue(state);
                            break;
                        case Mode.Autonomous:
                            // Do nothing
                            break;
                        case Mode.BinLowerMacro:
                            if (!feedback.BinLowerSwitchDepressed)
                            {
                                // Check limit switch
                                state[CommandFields.LeftBucketActuator] = -1000;
                                state[CommandFields.RightBucketActuator] = -1000;
                            }
                            else
                            {
                                mode = Mode.Manual;
                            }

                            // Enqueue current state from controller
                            stateQueue.Enqueue(state);

                            break;
                        case Mode.BinRaiseMacro:
                            if (!feedback.BinUpperSwitchDepressed)
                            {
                                // Check limit switch
                                state[CommandFields.LeftBucketActuator] = 1000;
                                state[CommandFields.RightBucketActuator] = 1000;
                            }
                            else
                            {
                                mode = Mode.Manual;
                            }

                            // Enqueue current state from controller
                            stateQueue.Enqueue(state);
                            break;
                        case Mode.CollectScoopMacro:
                            if (!feedback.BinUpperSwitchDepressed)
                            {
                                // Move actuators in and raise scoop
                                state[CommandFields.BucketPitch] = -1000;
                                state[CommandFields.BucketPivot] = 1000;
                                stopwatch.Restart();
                            }
                            else if (stopwatch.ElapsedMilliseconds < 700)
                            {
                                state[CommandFields.TranslationalVelocity] = 1000;
                            }
                            else
                            {
                                mode = Mode.Manual;
                            }

                            // Enqueue current state from controller
                            stateQueue.Enqueue(state);
                            break;
                        case Mode.DockRobotMacro:
                            // Calcuate orientation error
                            double orientationError = feedback.RearProximityLeft - feedback.RearProximityRight;

                            // Check orientation, TODO: un-hard-code
                            if (orientationError > 30)
                            {
                                double gain = 1.0; // TODO: tune this

                                state[CommandFields.RotationalVelocity] = (short)(orientationError * gain);
                                state[CommandFields.TranslationalVelocity] = 0;
                            }
                            else
                            {
                                // Calculate average distance
                                double distanceError = (feedback.RearProximityLeft + feedback.RearProximityRight) / 2.0d;

                                // Check distance error, TODO
                                if (distanceError > 15)
                                {
                                    // Backup slowly
                                    state[CommandFields.RotationalVelocity] = 0;
                                    state[CommandFields.TranslationalVelocity] = -500;
                                }
                                else
                                {
                                    // Close enough, move scoop all the way down
                                    state[CommandFields.BucketPivot] = -1000;
                                    // Check for done
                                    if (feedback.BinLowerSwitchDepressed)
                                    {
                                        // All done
                                        mode = Mode.Manual;
                                    }
                                }
                            }

                            // Enqueue current state from controller
                            stateQueue.Enqueue(state);
                            break;
                        default:

                            break;
                    }
                }
                else
                {
                    // Just load as usual
                    stateQueue.Enqueue(state);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error deserializing state: " + ex.Message);
            }
        }
Пример #35
0
        void receiver_DataReceived(object sender, Comms.DataArgs e)
        {
            Console.WriteLine("UDP Received");
            // todo : validate against jpeg header/footer
            // header: 255, 216 (0xFF, 0xD8)
            // footer: 255, 217 (0xFF, 0xD9)
            //check header...
            try
            {
                Debug.WriteLine(e.Data.Length);
                if (e.Data[0] == 0xFF && e.Data[1] == 0xD8 && e.Data[e.Data.Length - 2] == 0xFF && e.Data[e.Data.Length - 1] == 0xD9)
                { //image is validated!
                    using (MemoryStream ms = new MemoryStream(e.Data))
                    {
                        BitmapSource source = BitmapFrame.Create(ms, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); //OnLoad option is necessary so stream doesn't go away

                        if (ImageReceived != null)
                            ImageReceived(this, new ImageReceivedEventArgs(source));
                    }
                }
                else
                    Debug.WriteLine("Data did not have correct Jpeg header/footer");
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Пример #36
0
 static void telemetryHandler_TelemetryFeedbackProcessed(object sender, Comms.TelemetryEncoding.TelemetryFeedbackArgs e)
 {
     // Obtain measurements and copy to feedback object
     feedback = (TelemetryFeedback)e.UpdatedState.Clone();
 }
Пример #37
0
 void receiver_ReceiverError(object sender, Comms.ErrorArgs e)
 {
     if (this.ReceiveError != null)
         this.ReceiveError(this, e);
 }
Пример #38
0
 void serverTransever_newConnectionMade(object sender, Comms.EventArgs.ReceiverHolderEventArgs e)
 {
     String playerName = e.rec.getEndpoint().Address.ToString();
     this.serverTransever.sendMessage(new Messages.LobbyMessages.NewPlayerConnected(playerName));
     base.fireNewPlayerConnected(new EventArgs.PlayerConnectedEventArgs(playerName));
 }
Пример #39
0
 void comms_playerConnected(object sender, Comms.Lobby.EventArgs.PlayerConnectedEventArgs e)
 {
     this.lobbyControl.addPlayer(e.PlayerName);
 }
Пример #40
0
 void comms_chatReceved(object sender, Comms.Lobby.EventArgs.ChatRecevedEventArgs e)
 {
     this.lobbyControl.addChatMessage(e.line);
 }