Example #1
0
 public void EnterStation()
 {
     state = BusState.Pickup;
     drive.Toggle();
     StartCoroutine(StatsOpen());
     audioManager.PlaySound(AudioManager.Sound.Stop);
 }
Example #2
0
        public HealthResult CheckHealth(BusState busState, string healthMessage)
        {
            var results = _endpoints.Values.Select(x => new
            {
                x.InputAddress,
                Result = x.HealthResult
            }).ToArray();

            var unhealthy = results.Where(x => x.Result.Status == BusHealthStatus.Unhealthy).ToArray();
            var degraded  = results.Where(x => x.Result.Status == BusHealthStatus.Degraded).ToArray();

            var unhappy = unhealthy.Union(degraded).ToArray();

            var names = unhappy.Select(x => x.InputAddress.AbsolutePath.Split('/').LastOrDefault()).ToArray();

            Dictionary <string, EndpointHealthResult> data = results.ToDictionary(x => x.InputAddress.ToString(), x => x.Result);

            var exception = results.Where(x => x.Result.Exception != null).Select(x => x.Result.Exception).FirstOrDefault();

            if (busState != BusState.Started || unhealthy.Any() && unhappy.Length == results.Length)
            {
                return(HealthResult.Unhealthy($"Not ready: {healthMessage}", exception, data));
            }

            if (unhappy.Any())
            {
                return(HealthResult.Degraded($"Degraded Endpoints: {string.Join(",", names)}", exception, data));
            }

            return(HealthResult.Healthy("Ready", data));
        }
        public async Task ShouldSendMessageToAggregatorProcessor()
        {
            _mockConfiguration.SetupGet(x => x.MessageProcessingMiddleware).Returns(new List <Type>());

            var message = new FakeMessage1(Guid.NewGuid())
            {
                Username = "******"
            };

            var processor = new Mock <IAggregatorProcessor>();

            processor.Setup(x => x.ProcessMessage <FakeMessage1>(JsonConvert.SerializeObject(message)));

            var busState = new BusState();

            busState.AggregatorProcessors[typeof(FakeMessage1)] = processor.Object;

            var pipeline = new ProcessMessagePipeline(_mockConfiguration.Object, busState);
            await pipeline.ExecutePipeline(_consumeContext, typeof(FakeMessage1), new Envelope
            {
                Headers = new Dictionary <string, object>(),
                Body    = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))
            });

            processor.Verify(x => x.ProcessMessage <FakeMessage1>(It.Is <string>(y => JsonConvert.DeserializeObject <FakeMessage1>(y).Username == "Tim")), Times.Once);
        }
Example #4
0
        public int Read(byte[] readBuf, int maxReadLen = 0)
        {
            lock (this.busLock)
            {
                try
                {
                    if (this.Info == null || this.State == BusState.Error || this.State == BusState.Closed)
                    {
                        throw new Exception(string.Format("Bus:{0} is at {1} state,could not do write", this.Info.ReadableValue, this.State));
                    }

                    this.State = BusState.Reading;
                    this.OnBusOperationStarting(new BusOperationEventArgs(this, BusOperation.Reading, readBuf, 0, maxReadLen == 0 ? readBuf.Length : maxReadLen));

                    int ret = this.ReadImplement(readBuf, maxReadLen == 0 ? readBuf.Length : maxReadLen);

                    this.State = BusState.Readed;
                    this.OnBusOperationCompleted(new BusOperationEventArgs(this, BusOperation.Reading, readBuf, 0, ret));

                    return(ret);
                }
                catch
                {
                    this.State = BusState.Error;
                    throw;
                }
            }
        }
Example #5
0
        public void Write(byte[] writeBuf, int offset, int len)
        {
            lock (this.busLock)
            {
                try
                {
                    if (this.Info == null || this.State == BusState.Error || this.State == BusState.Closed)
                    {
                        throw new Exception(string.Format("Bus:{0} is at {1} state,could not do write", this.Info.ReadableValue, this.State));
                    }

                    this.State = BusState.Writing;
                    this.OnBusOperationStarting(new BusOperationEventArgs(this, BusOperation.Writing, writeBuf, offset, len));

                    this.WriteImplement(writeBuf, offset, len);

                    this.State = BusState.Writed;
                    this.OnBusOperationCompleted(new BusOperationEventArgs(this, BusOperation.Writing, writeBuf, offset, len));
                }
                catch
                {
                    this.State = BusState.Error;
                    throw;
                }
            }
        }
Example #6
0
 public void ExitStation()
 {
     state = BusState.Drive;
     drive.Toggle();
     StartCoroutine(StatsClose());
     difficulty++;
     SetDifficulty(difficulty);
 }
Example #7
0
    private void Die()
    {
        state = BusState.Finish;
        StopAllCoroutines();
        GameObject exp = Instantiate(explosion);

        exp.transform.position = transform.position;
        Destroy(exp, 1);
        Destroy(transform.Find("Model").gameObject);
        Destroy(transform.Find("Passengers").gameObject);
        StartCoroutine(DeathScreen());
    }
 /// <summary>
 /// this function happend when thread done is runing
 /// the function clean the progress bar, update the bus to be ready and all the implicit as a result of that.
 /// </summary>
 private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     state = BusState.Ready;
     mainW.UpdatePB(_licNum, 0);
     mainW.UpdateTime(_licNum);
     mainW.UpdateColor(this);
     if (busDat != null)
     {
         busDat.UpdateInfo();
         BusDat.updateColor();
     }
 }
Example #9
0
        public I2CBus()
        {
            pollEntries = new Dictionary<int, PollEntry>();
            stateLock = new object();
            socketLock = new object();

            state = BusState.Disconnected;
            channelConnectEvent = new AutoResetEvent(false);

            pollThread = new Thread(StartPollThread) {Name = "I2c Bus Poll Thread"};
            pollThread.Start();
        }
 /// <summary>
 /// This function refuels the bus and lowers it's KmFromfuel to 0.
 /// </summary>
 public void ReFual()
 {
     worker = new BackgroundWorker();
     worker.WorkerReportsProgress = true;
     worker.DoWork             += Worker_DoWork;
     worker.ProgressChanged    += Worker_ProgressChanged;
     worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
     worker.RunWorkerAsync(12);
     state       = BusState.Refueling;
     _kmFromFuel = 0;
     mainW.UpdateColor(this);
     if (BusDat != null)
     {
         BusDat.updateColor();
     }
     UpdateEarns(-500);
 }
        }                                                        //property

        /// <summary>
        /// constructor for Bus cless
        /// </summary>
        /// <param name="licNum">the Bus's licesnse number</param>
        /// <param name="date">the date that the bus started working </param>
        /// <param name="kmFromFuel">the km that droven from last fuel</param>
        /// <param name="kmFromtreat">the km that droven from last treatment</param>
        /// <param name="kmT">the total km </param>
        /// <param name="lastTreat">the date of the last treatment</param>
        /// <param name="startDate">the date of the start acivity of the bus</param>
        public Bus(int licNum, DateTime startDate, int kmT = 0, int kmFromFuel = 0, int kmFromtreat = 0, DateTime lastTreat = default(DateTime))
        {
            _kmTotal     = kmT;
            _kmFromFuel  = kmFromFuel;
            _kmFromtreat = kmFromtreat;
            _licNum      = licNum;
            _start       = startDate;
            if (lastTreat == default(DateTime))
            {
                _lastTreat = DateTime.Now; // the default is the date of the inserting the bus
            }
            else
            {
                _lastTreat = lastTreat;
            }
            state   = BusState.Ready;
            counter = 0;
            busDat  = null; // for check if the bus data win is open or not
        }
 /// <summary>
 /// This function treatments the bus and lowers it's KmFromtreat to 0.
 /// </summary>
 public void Treatment()
 {
     worker = new BackgroundWorker();
     worker.WorkerReportsProgress = true;
     worker.DoWork             += Worker_DoWork;
     worker.ProgressChanged    += Worker_ProgressChanged;
     worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
     worker.RunWorkerAsync(144);
     state        = BusState.Treatment;
     _kmFromtreat = 0;
     _kmFromFuel  = 0;//that how we undrstood the assignment - when make treatment make refuel too.
     _lastTreat   = DateTime.Now;
     mainW.UpdateColor(this);
     if (BusDat != null)
     {
         BusDat.updateColor();
     }
     UpdateEarns(-2000);
 }
        /// <summary>
        /// this function make a thread for make the operetion of driving of bus
        /// </summary>
        /// <param name="Length">the length of the drive</param>
        /// <param name="passengers">the number of passengers in the current drive </param>
        public void Drive(int Length, int passengers)
        {
            worker = new BackgroundWorker();
            worker.WorkerReportsProgress = true;
            worker.DoWork             += Worker_DoWork;
            worker.ProgressChanged    += Worker_ProgressChanged;
            worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
            worker.RunWorkerAsync(Length);
            state = BusState.Driving;
            mainW.UpdateColor(this);
            if (BusDat != null)
            {
                BusDat.updateColor();
            }

            UpdateEarns(passengers * 20 - Length);
            totalPass += passengers;
            drives++;
        }
Example #14
0
        public Bus(IConfiguration configuration)
        {
            _busState = new BusState();

            Configuration = configuration;

            _logger    = configuration.GetLogger();
            _container = configuration.GetContainer();
            _producer  = configuration.GetProducer();
            _processMessagePipeline = configuration.GetProcessMessagePipeline(_busState);
            _sendMessagePipeline    = configuration.GetSendMessagePipeline();

            _container.Initialize();

            if (configuration.AddBusToContainer)
            {
                _container.AddBus(this);
            }

            if (configuration.ScanForMesssageHandlers)
            {
                _container.ScanForHandlers();
            }

            if (configuration.TransportSettings.AuditingEnabled)
            {
                StartHeartbeatTimer();
            }

            if (configuration.AutoStartConsuming)
            {
                StartConsuming();
            }

            if (configuration.EnableProcessManagerTimeouts)
            {
                _expiredTimeoutsPoller = new ExpiredTimeoutsPoller(this);
                _expiredTimeoutsPoller.Start();
            }
        }
Example #15
0
 public void Close()
 {
     lock (this.busLock)
     {
         try
         {
             if (this.State == BusState.Closed)
             {
                 return;
             }
             this.State = BusState.Closing;
             this.CloseImplement();
             this.Info  = null;
             this.State = BusState.Closed;
         }
         catch
         {
             this.State = BusState.Error;
             throw;
         }
     }
 }
Example #16
0
 public void Open(BusInfo busInfo)
 {
     lock (this.busLock)
     {
         try
         {
             this.Info = busInfo;
             if (this.State != BusState.Closed && this.State != BusState.Error && this.State != BusState.Created)
             {
                 throw new Exception(string.Format("Bus:{0} is {1} could not open", busInfo.ReadableValue, this.State));
             }
             this.State = BusState.Opening;
             this.OpenImplement(busInfo);
             this.State = BusState.Opened;
         }
         catch
         {
             this.State = BusState.Error;
             this.Info  = null;
             throw;
         }
     }
 }
Example #17
0
        /// <summary>
        /// Attempts to establish a connection with the i2cproxy running on the robot.
        /// </summary>
        /// <exception cref="InvalidOperationException">If Host, CommandPort or PollPort aren't setup correctly, or is not in the Disconnected state.</exception>
        /// <returns>True if successful, false otherwise.</returns>
        public bool Connect()
        {
            if (String.IsNullOrEmpty(Host)) throw new InvalidOperationException("Host hasn't been set.");
            if (CommandPort == 0) throw new InvalidOperationException("CommandPort hasn't been set.");
            if (PollPort == 0) throw new InvalidOperationException("PollPort hasn't been set.");

            lock (stateLock)
            {
                if (State != BusState.Disconnected) throw new InvalidOperationException("Can't connect unless in the disconnected state.");
                State = BusState.Connecting;
            }

            Debug.WriteLine(String.Format("Creating command socket: host={0}, port={1}", Host, CommandPort));
            commandSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            commandSocket.ReceiveTimeout = 5000;
            commandSocket.SendTimeout = 5000;
            try { commandSocket.Connect(Host, CommandPort); }
            catch (SocketException e)
            {
                Debug.WriteLine(String.Format("Couldn't connect to {0}:{1}. The error was: {2}", Host, CommandPort, e.Message));
                lock (stateLock) State = BusState.Disconnected;
                commandSocket.Close();
                return false;
            }
            commandLineReader = new BufferedLineReader((buffer, index, count) => commandSocket.Receive(buffer, index, count, SocketFlags.None), CommandSocketBufferSize);

            Debug.WriteLine(String.Format("Creating poll socket: host={0}, port={1}", Host, PollPort));
            pollSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            pollSocket.SendTimeout = 5000;
            try { pollSocket.Connect(Host, PollPort); }
            catch (SocketException e)
            {
                Debug.WriteLine(String.Format("Couldn't connect to {0}:{1}. The error was: {2}", Host, PollPort, e.Message));
                lock (stateLock) State = BusState.Disconnected;
                pollSocket.Close();
                commandSocket.Close();
                return false;
            }
            pollLineReader = new BufferedLineReader((buffer, index, count) => ReadFromSocket(pollSocket, buffer, index, count), PollSocketBufferSize);

            lock (stateLock) State = BusState.Connected;
            channelConnectEvent.Set();

            Debug.WriteLine("Connected");
            return true;
        }
Example #18
0
 public HealthResult CheckHealth(BusState busState, string healthMessage)
 {
     return(ReceiveEndpoints.CheckHealth(busState, healthMessage));
 }
Example #19
0
        public async Task <BusHandle> StartAsync(CancellationToken cancellationToken)
        {
            LogContext.SetCurrentIfNull(_logContext);

            if (_busHandle != null)
            {
                LogContext.Warning?.Log("StartAsync called, but the bus was already started: {Address} ({Reason})", Address, "Already Started");
                return(_busHandle);
            }

            await _busObservable.PreStart(this).ConfigureAwait(false);

            Handle busHandle = null;

            CancellationTokenSource tokenSource = null;

            try
            {
                if (cancellationToken == default)
                {
                    tokenSource       = new CancellationTokenSource(TimeSpan.FromSeconds(60));
                    cancellationToken = tokenSource.Token;
                }

                var hostHandle = _host.Start(cancellationToken);

                busHandle = new Handle(_host, hostHandle, this, _busObservable, _logContext);

                try
                {
                    await busHandle.Ready.OrCanceled(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException exception) when(exception.CancellationToken == cancellationToken)
                {
                    try
                    {
                        await busHandle.StopAsync(TimeSpan.FromSeconds(30)).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        LogContext.Warning?.Log(ex, "Bus start faulted, and failed to stop host");
                    }

                    await busHandle.Ready.ConfigureAwait(false);
                }

                await _busObservable.PostStart(this, busHandle.Ready).ConfigureAwait(false);

                _busHandle = busHandle;

                _busState      = BusState.Started;
                _healthMessage = "";

                LogContext.Info?.Log("Bus started: {HostAddress}", _host.Address);

                return(_busHandle);
            }
            catch (Exception ex)
            {
                try
                {
                    if (busHandle != null)
                    {
                        LogContext.Debug?.Log(ex, "Bus start faulted, stopping host");

                        await busHandle.StopAsync(cancellationToken).ConfigureAwait(false);
                    }
                }
                catch (OperationCanceledException)
                {
                }
                catch (Exception stopException)
                {
                    LogContext.Warning?.Log(stopException, "Bus start faulted, and failed to stop host");
                }

                _busState      = BusState.Faulted;
                _healthMessage = $"start faulted: {ex.Message}";

                await _busObservable.StartFaulted(this, ex).ConfigureAwait(false);

                throw;
            }
            finally
            {
                tokenSource?.Dispose();
            }
        }
Example #20
0
 public void FinishLevel()
 {
     drive.Toggle();
     state = BusState.Finish;
     StartCoroutine(LevelEnd(time, passengers));
 }
Example #21
0
    private IEnumerator LevelStart()
    {
        float center = Screen.width / 2;
        float rigth  = Screen.width * 2;

        levelText.text = "Level " + level;
        levelText.rectTransform.position = new Vector3(rigth, levelText.rectTransform.position.y, levelText.rectTransform.position.z);
        stopsText.text = noStops + " stops";
        stopsText.rectTransform.position = new Vector3(rigth, stopsText.rectTransform.position.y, stopsText.rectTransform.position.z);
        lengthText.text = length + " km";
        lengthText.rectTransform.position = new Vector3(rigth, lengthText.rectTransform.position.y, lengthText.rectTransform.position.z);
        options.rectTransform.position    = new Vector3(rigth, options.rectTransform.position.y, options.rectTransform.position.z);
        canvasbg.fillAmount = 0;
        countdown.gameObject.SetActive(false);
        yield return(new WaitForSeconds(1));

        //BG Appear
        float t    = 0;
        float time = 0;

        while (t < 1)
        {
            time += Time.deltaTime;
            t     = Mathf.InverseLerp(0, 0.25f, time);
            canvasbg.fillAmount = t;
            yield return(null);
        }
        canvasbg.fillAmount = 1;

        Text text = levelText;

        for (int i = 0; i < 3; i++)
        {
            if (i == 1)
            {
                text = stopsText;
            }
            if (i == 2)
            {
                text = lengthText;
            }
            //Text Appear
            t    = 0;
            time = 0;
            while (t < 1)
            {
                time += Time.deltaTime;
                t     = Mathf.InverseLerp(0, 0.75f, time);
                text.rectTransform.position = new Vector3(Mathf.Lerp(rigth, center, t), text.rectTransform.position.y, text.rectTransform.position.z);
                yield return(null);
            }
            text.rectTransform.position = new Vector3(center, text.rectTransform.position.y, text.rectTransform.position.z);
            yield return(new WaitForSeconds(0.25f));
        }
        yield return(new WaitForSeconds(1.75f));

        //Disapear
        t    = 0;
        time = 0;
        while (t < 1)
        {
            time += Time.deltaTime;
            t     = Mathf.InverseLerp(0, 0.25f, time);
            levelText.rectTransform.position  = new Vector3(Mathf.Lerp(center, -rigth, t), levelText.rectTransform.position.y, levelText.rectTransform.position.z);
            stopsText.rectTransform.position  = new Vector3(Mathf.Lerp(center, -rigth, t), stopsText.rectTransform.position.y, stopsText.rectTransform.position.z);
            lengthText.rectTransform.position = new Vector3(Mathf.Lerp(center, -rigth, t), lengthText.rectTransform.position.y, lengthText.rectTransform.position.z);
            canvasbg.fillAmount = Mathf.Lerp(1, 0, t);
            yield return(null);
        }
        yield return(new WaitForSeconds(0.25f));

        //Countdown
        countdown.gameObject.SetActive(true);
        countdown.text = "3";
        for (int i = 0; i < 4; i++)
        {
            countdown.fontSize = 0;
            countdown.text     = "" + (3 - i);
            if (i == 3)
            {
                countdown.text = "GO!";
            }
            t    = 0;
            time = 0;
            while (t < 1)
            {
                time += Time.deltaTime;
                t     = Mathf.InverseLerp(0, 0.48f, time);
                countdown.fontSize = (int)Mathf.Lerp(0f, 300, t);
                yield return(null);
            }
            yield return(new WaitForSeconds(0.25f));
        }
        state = BusState.Drive;
        drive.Toggle();
        yield return(new WaitForSeconds(0.75f));

        //Disapear
        t    = 0;
        time = 0;
        while (t < 1)
        {
            time += Time.deltaTime;
            t     = Mathf.InverseLerp(0, 0.25f, time);
            countdown.rectTransform.position = new Vector3(Mathf.Lerp(center, -rigth, t), countdown.rectTransform.position.y, countdown.rectTransform.position.z);
            yield return(null);
        }
    }
Example #22
0
        public void Disconnect()
        {
            Debug.WriteLine("Disconnecting");

            channelConnectEvent.Reset();
            lock (stateLock)
            {
                if (State == BusState.Disconnecting || State == BusState.Disconnected) return;
                if (State == BusState.Connecting) throw new InvalidOperationException();
                State = BusState.Disconnecting;
            }

            try { commandSocket.Close(); }
            catch (SocketException e) { Debug.WriteLine("Error disconnecting command socket: " + e.Message); }

            try { pollSocket.Close(); }
            catch (SocketException e) { Debug.WriteLine("Error disconnecting poll socket: " + e.Message); }

            lock (stateLock) State = BusState.Disconnected;

            Debug.WriteLine("Disconnected");
        }
 public BusStateChangedEventArgs(IBus bus, BusState preState, BusState currentState)
 {
     this.Bus          = bus;
     this.PreState     = preState;
     this.CurrentState = currentState;
 }
Example #24
0
 public BusBase()
 {
     this.busLock = new object();
     this.State   = BusState.Created;
 }