public void can_wait_for_a_condition()
        {
            var hub = new MessagingHub();
            var listener = new RemoteListener(hub);

            var m1 = new Message(){Number = 1};
            var m2 = new Message() { Number = 2 };
            var m3 = new Message() { Number = 3 };
            var m4 = new Message() { Number = 4 };

            var result = listener.WaitForMessage<Message>(m => m.Number == 4, () => {
                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(100);
                    listener.SendObject(m1);
                    Thread.Sleep(100);
                    listener.SendObject(m2);
                    Thread.Sleep(100);
                    listener.SendObject(m3);
                    Thread.Sleep(100);
                    listener.SendObject(m4);
                });
            });

            result.ShouldBe(m4);
            hub.Listeners.Any().ShouldBeFalse(); // want it to remove the condition as it goes
        }
Example #2
0
        public async Task Connect(string host)
        {
            if (Connection != null)
            {
                await Connection.StopAsync();

                await Connection.DisposeAsync();
            }

            if (MessagingHub != null)
            {
                await MessagingHub.StopAsync();

                await MessagingHub.DisposeAsync();
            }

            Connection = new HubConnectionBuilder()
                         .WithUrl($"{host}/RCDeviceHub")
                         .AddMessagePackProtocol()
                         .WithAutomaticReconnect()
                         .Build();

            MessagingHub = new HubConnectionBuilder()
                           .WithUrl($"{host}/MessagingHub")
                           .AddMessagePackProtocol()
                           .WithAutomaticReconnect()
                           .Build();

            ApplyConnectionHandlers();

            await Connection.StartAsync();
        }
Example #3
0
        public RaceMainPage(GlobalModel model)
        {
            var grid = new Grid();

            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(1, GridUnitType.Star)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(1, GridUnitType.Star)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(2)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(UIConfiguration.PanelWidth)
            });
            grid.ColumnSpacing = 0;
            grid.RowSpacing    = 0;

            grid.Children.Add(new LeftPanelBuilder(model).Build(), 0, 0);
            grid.Children.Add(new BoxView()
            {
                Color = UIConfiguration.ButtonColor, WidthRequest = 2, HeightRequest = -1
            }, 1, 0);
            grid.Children.Add(new RightPanelBuilder(model).Build(), 2, 0);

            Content         = grid;
            BackgroundColor = Color.Black;

            MessagingHub.Subscribe <GlobalCommand>(this, QueueType.AskConfirmation, (cmd) => ProcessCommand(cmd));
            MessagingHub.Subscribe <string>(this, QueueType.Gesture, (msg) => ShowMessage(msg));
            //Navigation.PushModalAsync(cp);
        }
Example #4
0
        public void can_wait_for_a_condition()
        {
            var hub = new MessagingHub();
            var listener = new RemoteListener(hub);

            var m1 = new Message(){Number = 1};
            var m2 = new Message() { Number = 2 };
            var m3 = new Message() { Number = 3 };
            var m4 = new Message() { Number = 4 };

            var result = listener.WaitForMessage<Message>(m => m.Number == 4, () => {
                Task.Factory.StartNew(() =>
                {
                    Thread.Sleep(100);
                    listener.SendObject(m1);
                    Thread.Sleep(100);
                    listener.SendObject(m2);
                    Thread.Sleep(100);
                    listener.SendObject(m3);
                    Thread.Sleep(100);
                    listener.SendObject(m4);
                });
            });

            result.ShouldEqual(m4);
            hub.Listeners.Any().ShouldBeFalse(); // want it to remove the condition as it goes
        }
Example #5
0
 public void OnLocationChanged(Location location)
 {
     if (location != null)
     {
         MessagingHub.Send(QueueType.Location, LocationData.CreateFrom(location));
     }
 }
        public RemoteController(string path)
        {
            _remoteSetup.ServiceDirectory = path;
            _project   = Project.LoadForFolder(path);
            _path      = path;
            _messaging = new MessagingHub();

            _messaging.AddListener(this);
        }
Example #7
0
        public void SetUp()
        {
            theListener = new RecordingListener();
            var hub = new MessagingHub();

            hub.AddListener(theListener);

            var remoteListener = new RemoteListener(hub);

            EventAggregator.Start(remoteListener);
        }
Example #8
0
 public void OnProviderEnabled(string provider)
 {
     if (_providerName == provider)
     {
         var location = _locationManager.GetLastKnownLocation(provider);
         if (location != null)
         {
             MessagingHub.Send(QueueType.Location, LocationData.CreateFrom(location));
         }
     }
 }
        public void SetUp()
        {
            theListener = new RecordingListener();
            var hub = new MessagingHub();

            hub.AddListener(theListener);

            var remoteListener = new RemoteListener(hub);

            GlobalMessageTracking.Start(remoteListener);
        }
Example #10
0
 public void FinishRace()
 {
     foreach (var c in CountersGroup.All)
     {
         c.Stop();
     }
     Race.FinishRace();
     if (LastLocaton != null)
     {
         MessagingHub.Send(QueueType.Race, new RaceEvent(LastLocaton, RaceEventTypes.Finish));
         MessagingHub.Send(new VibrateCommand("99"));
     }
 }
Example #11
0
        private void ProcessClickCommand(GlobalCommand cmd)
        {
            switch (cmd.Code)
            {
            case GlobalCommandCodes.StartFinish:
                if (Race.IsRunning)
                {
                    MessagingHub.Send(QueueType.AskConfirmation, GlobalCommand.AskConfirmation(cmd, "Do you really want to finish the race?"));
                }
                else
                {
                    StartRace();
                }
                break;

            case GlobalCommandCodes.ResetAll:
                if (Race.IsRunning)
                {
                    MessagingHub.Send(QueueType.AskConfirmation, GlobalCommand.AskConfirmation(cmd, "Do you really want to reset after start?"));
                }
                else
                {
                    ResetAll();
                }
                break;

            case GlobalCommandCodes.ResetTime:
                Race.ResetTimeOnCheckpoint();
                break;

            case GlobalCommandCodes.ClearAll:
                MessagingHub.Send(QueueType.AskConfirmation, GlobalCommand.AskConfirmation(cmd, "Delete all data?"));
                break;

            case GlobalCommandCodes.GPSReset:
                MessagingHub.Send(QueueType.Global, cmd);
                break;

            case GlobalCommandCodes.Turn:
                MakeATurn();
                break;

            case GlobalCommandCodes.Back:
                GoBack();
                break;

            case GlobalCommandCodes.DelSegment:
                Race.DeleteLastSegment();
                break;
            }
        }
Example #12
0
        public void SetUp()
        {
            theHub = new MessagingHub();

            listener1 = createListener();
            listener2 = createListener();
            listener3 = createListener();

            listener4 = createListener <Message1>();
            listener5 = createListener <Message1>();
            listener6 = createListener <Message1>();
            listener7 = createListener <Message2>();
            listener8 = createListener <Message2>();
        }
Example #13
0
 public void StartRace()
 {
     foreach (var c in CountersGroup.All)
     {
         c.Reset();
         c.Start();
     }
     Race.StartRace();
     if (LastLocaton != null)
     {
         MessagingHub.Send(QueueType.Race, new RaceEvent(LastLocaton, RaceEventTypes.Start));
         MessagingHub.Send(new VibrateCommand("11"));
     }
     Speech?.Speak("Поехали");
 }
Example #14
0
        private async void ProcessCommand(GlobalCommand cmd)
        {
            if (cmd.Code == GlobalCommandCodes.AskConfirmation)
            {
                var answer = await DisplayAlert("Alert", cmd.Message, "Yes", "No");

                //var answer = await DisplayAlert("Alert", cmd.Message, "Yes", "No");
                if (answer)
                {
                    MessagingHub.Send(QueueType.Confirmed, GlobalCommand.ReplyConfirmation(cmd.CommandToConfirm));
                }
                else
                {
                    MessagingHub.Send(QueueType.Canceled, GlobalCommand.ReplyConfirmation(cmd.CommandToConfirm));
                }
            }
        }
Example #15
0
        public void send_json_message()
        {
            var message = new Message2 {
                Name = "that one"
            };


            var json = MessagingHub.ToJson(message);

            theHub.SendJson(json);

            listener1.AssertWasCalled(x => x.Receive(message));
            listener2.AssertWasCalled(x => x.Receive(message));
            listener3.AssertWasCalled(x => x.Receive(message));

            listener7.AssertWasCalled(x => x.Receive(message));
            listener8.AssertWasCalled(x => x.Receive(message));
        }
        public async Task <HttpResponseMessage> signalRPushPost(Post post)
        {
            Post data = post;

            try
            {
                ApiResponseModel <Post> model = new ApiResponseModel <Post>()
                {
                };
                model.data.records = data;
                MessagingHub.sendPost(data);
                return(Response.Success <Post>(model));
            }
            catch (Exception ex)
            {
                return(Response.Exception(ex));
            }
        }
Example #17
0
        public GlobalModel()
        {
            Numpad = new NumpadModel();
            Race   = new Race();
            Numpad.NewDataTextEntered += Race.ParseAndAddNewSegments;


            CountersGroup = new CountersContainer(this);
            CountersGroup.Init();
            ShowDebugInfo = true;

            MessagingHub.Subscribe <GlobalCommand>(this, QueueType.Click, (cmd) => ProcessClickCommand(cmd));
            MessagingHub.Subscribe <GlobalCommand>(this, QueueType.Confirmed, (cmd) => ProcessConfirmedCommand(cmd));
            MessagingHub.Subscribe <GlobalCommand>(this, QueueType.Canceled, (cmd) => ProcessCanceledCommand(cmd));
            MessagingHub.Subscribe <LocationData>(this, QueueType.Location, (loc) => ProcessNewLocation(loc));
            InitSpeech();
            UseBadLanguage = false;
        }
Example #18
0
 public void GoBack()
 {
     foreach (var c in CountersGroup.Segment)
     {
         var h = c as ISupportHistory;
         if (h != null)
         {
             h.Pop();
         }
         else
         {
             c.Reset();
         }
     }
     Race.RemoveLastTurn();
     if (LastLocaton != null)
     {
         MessagingHub.Send(QueueType.Race, new RaceEvent(LastLocaton, RaceEventTypes.Back));
         MessagingHub.Send(new VibrateCommand("3"));
     }
 }
Example #19
0
 public void MakeATurn()
 {
     Race.AddTurn();
     foreach (var c in CountersGroup.Segment)
     {
         var h = c as ISupportHistory;
         if (h != null)
         {
             h.Push();
         }
         else
         {
             c.Reset();
         }
     }
     if (LastLocaton != null)
     {
         MessagingHub.Send(QueueType.Race, new RaceEvent(LastLocaton, RaceEventTypes.Turn));
         MessagingHub.Send(new VibrateCommand("1"));
     }
     //Speech?.Speak("Поворот");
 }
Example #20
0
        private void Worker(object state)
        {
            var rspeed = state as IRaceCounter <double?>;

            if (rspeed == null)
            {
                return;
            }
            if (!model.Race.IsRunning)
            {
                return;
            }
            samples = ++samples % 60;


            var targetSpeed = rspeed?.Value;

            targetSpeed = targetSpeed > 80 ? 80 : targetSpeed;
            var delta = Math.Round(Math.Abs(targetSpeed.GetValueOrDefault() - speed), 0);

            //speed += targetSpeed > (speed + delta/2) ? delta/2 : (targetSpeed < (speed - delta/2) ? -delta/2: 0);
            speed = 10;
            //if (speed.HasValue)
            //{
            //	speed = speed > 80 ? 80 : speed;
            //	speed += r.Next(16) - 8;
            //}
            //else
            //{
            //	speed = r.Next(10) + 15;
            //}
            //if (samples > 30) speed = 5;
            if (samples > 50)
            {
                speed = 0;
            }
            //speed = 8;

            var k = LocationData.DistanceBetween(
                new LocationData()
            {
                Longitude = 50.0001, Latitude = 30.0001
            },
                new LocationData()
            {
                Longitude = 50.0002, Latitude = 30.0002
            });

            var loc = new LocationData()
            {
                Latitude  = prevLoc.Latitude + 0.0001 / k * (speed / 3.6),
                Longitude = prevLoc.Longitude + 0.0001 / k * (speed / 3.6),
                Speed     = speed / 3.6,
                Time      = DateTime.Now.ToUniversalTime()
            };

            prevLoc = loc;
            MessagingHub.Send(QueueType.Location, loc);

            tick += 1000;
        }
Example #21
0
        public void SendRemotely <T>(T message)
        {
            string json = MessagingHub.ToJson(message);

            _proxy.SendJson(json);
        }
Example #22
0
 public void OnProviderDisabled(string provider)
 {
     MessagingHub.Send(QueueType.Location, LocationData.Offline);
 }
Example #23
0
        public void ApplyConnectionHandlers()
        {
            var conductor = ServiceContainer.Instance.GetRequiredService <Conductor>();

            Connection.Closed += ex =>
            {
                Logger.Write($"Connection closed.  Error: {ex?.Message}");
                return(Task.CompletedTask);
            };

            Connection.On("ReceiveIceCandidate",
                          (string candidate, int sdpMlineIndex, string sdpMid, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                    {
                        viewer.RtcSession.AddIceCandidate(sdpMid, sdpMlineIndex, candidate);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("ReceiveRtcAnswer", (string sdp, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                    {
                        viewer.RtcSession.SetRemoteDescription("answer", sdp);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("ClipboardTransfer", (string transferText, bool typeText, string viewerID) =>
            {
                try
                {
                    if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                    {
                        if (typeText)
                        {
                            KeyboardMouseInput.SendText(transferText, viewer);
                        }
                        else
                        {
                            ClipboardService.SetText(transferText);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("CtrlAltDel", async(string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    await Connection.InvokeAsync("CtrlAltDel");
                }
            });

            Connection.On("Disconnect", async(string reason) =>
            {
                Logger.Write($"Disconnecting caster socket.  Reason: {reason}");
                foreach (var viewer in conductor.Viewers.Values.ToList())
                {
                    await Connection.InvokeAsync("ViewerDisconnected", viewer.ViewerConnectionID);
                    viewer.DisconnectRequested = true;
                }
            });

            Connection.On("GetScreenCast", (string viewerID, string requesterName) =>
            {
                try
                {
                    ScreenCaster.BeginScreenCasting(new ScreenCastRequest
                    {
                        ViewerID = viewerID, RequesterName = requesterName
                    });
                }
                catch (Exception ex)
                {
                    Logger.Write(ex);
                }
            });

            Connection.On("RequestScreenCast",
                          (string viewerID, string requesterName) =>
            {
                conductor.InvokeScreenCastRequested(new ScreenCastRequest
                {
                    ViewerID = viewerID, RequesterName = requesterName
                });
            });

            Connection.On("KeyDown", (string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyDown(key, viewer);
                }
            });

            Connection.On("KeyUp", (string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyUp(key, viewer);
                }
            });

            Connection.On("KeyPress", async(string key, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendKeyDown(key, viewer);
                    await Task.Delay(1);
                    KeyboardMouseInput.SendKeyUp(key, viewer);
                }
            });

            Connection.On("MouseMove", (double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendMouseMove(percentX, percentY, viewer);
                }
            });

            Connection.On("MouseDown", (int button, double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    if (button == 0)
                    {
                        KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer);
                    }
                    else if (button == 2)
                    {
                        KeyboardMouseInput.SendRightMouseDown(percentX, percentY, viewer);
                    }
                }
            });

            Connection.On("MouseUp", (int button, double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    if (button == 0)
                    {
                        KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer);
                    }
                    else if (button == 2)
                    {
                        KeyboardMouseInput.SendRightMouseUp(percentX, percentY, viewer);
                    }
                }
            });

            Connection.On("MouseWheel", (double deltaX, double deltaY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendMouseWheel(-(int)deltaY, viewer);
                }
            });

            Connection.On("ViewerDisconnected", async(string viewerID) =>
            {
                await Connection.InvokeAsync("ViewerDisconnected", viewerID);
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.DisconnectRequested = true;
                }
                conductor.InvokeViewerRemoved(viewerID);
            });
            Connection.On("LatencyUpdate", (DateTime sentTime, int bytesReceived, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    var latency            = DateTime.UtcNow - sentTime;
                    viewer.Latency         = latency.TotalMilliseconds;
                    viewer.WebSocketBuffer = Math.Max(0, viewer.WebSocketBuffer - bytesReceived);
                }
            });

            Connection.On("SelectScreen", (int screenIndex, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.Capturer.SetSelectedScreen(screenIndex);
                }
            });

            Connection.On("QualityChange", (int qualityLevel, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.ImageQuality = qualityLevel;
                }
            });

            Connection.On("AutoQualityAdjust", (bool isOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer))
                {
                    viewer.AutoAdjustQuality = isOn;
                }
            });

            Connection.On("ToggleAudio", (bool toggleOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    AudioCapturer.ToggleAudio(toggleOn);
                }
            });
            Connection.On("ToggleBlockInput", (bool toggleOn, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.ToggleBlockInput(toggleOn);
                }
            });


            Connection.On("TouchDown", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendLeftMouseDown(point.X, point.Y);
                }
            });
            Connection.On("LongPress", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendRightMouseDown(point.X, point.Y);
                    //Win32Interop.SendRightMouseUp(point.X, point.Y);
                }
            });
            Connection.On("TouchMove", (double moveX, double moveY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendMouseMove(point.X + moveX, point.Y + moveY);
                }
            });
            Connection.On("TouchUp", (string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    //User32.GetCursorPos(out var point);
                    //Win32Interop.SendLeftMouseUp(point.X, point.Y);
                }
            });
            Connection.On("Tap", (double percentX, double percentY, string viewerID) =>
            {
                if (conductor.Viewers.TryGetValue(viewerID, out var viewer) && viewer.HasControl)
                {
                    KeyboardMouseInput.SendLeftMouseDown(percentX, percentY, viewer);
                    KeyboardMouseInput.SendLeftMouseUp(percentX, percentY, viewer);
                }
            });
            Connection.On("SharedFileIDs", (List <string> fileIDs) =>
            {
                fileIDs.ForEach(id =>
                {
                    var url         = $"{conductor.Host}/API/FileSharing/{id}";
                    var webRequest  = WebRequest.CreateHttp(url);
                    var response    = webRequest.GetResponse();
                    var contentDisp = response.Headers["Content-Disposition"];
                    var fileName    = contentDisp
                                      .Split(";".ToCharArray())
                                      .FirstOrDefault(x => x.Trim().StartsWith("filename"))
                                      .Split("=".ToCharArray())[1];

                    var legalChars = fileName.ToCharArray()
                                     .Where(x => !Path.GetInvalidFileNameChars().Any(y => x == y));

                    fileName = new string(legalChars.ToArray());

                    var dirPath = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "RemotelySharedFiles"))
                                  .FullName;
                    var filePath = Path.Combine(dirPath, fileName);
                    using (var fs = new FileStream(filePath, FileMode.Create))
                    {
                        using (var rs = response.GetResponseStream())
                        {
                            rs.CopyTo(fs);
                        }
                    }

                    Process.Start("explorer.exe", dirPath);
                });
            });

            Connection.On("SessionID", (string sessionID) => { conductor.InvokeSessionIDChanged(sessionID); });

            MessagingHub.On <string, string>("ReceiveMessage",
                                             (senderName, message) => { conductor.InvokeMessageReceived(senderName, message); });
        }
Example #24
0
 public LocationService(LocationManager manager)
 {
     _locationManager = manager;
     MessagingHub.Subscribe <GlobalCommand>(this, QueueType.Global, (cmd) => ProcessCommand(cmd));
 }
Example #25
0
 public VibrationService(Vibrator vibrationService)
 {
     vibrator = vibrationService;
     MessagingHub.Subscribe <VibrateCommand>(this, (cmd) => ProcessCommand(cmd));
 }
 public void Init()
 {
     MessagingHub.Subscribe <LocationData>(this, QueueType.Location, (loc) => ProcessNewLocation(loc));
     MessagingHub.Subscribe <RaceEvent>(this, QueueType.Race, (evt) => ProcessRaceEvent(evt));
     serializer = new XmlSerializer(typeof(GPX));
 }
 public SystemRecycledListener(MessagingHub messaging)
 {
     _messaging  = messaging;
     _completion = new TaskCompletionSource <SystemRecycled>();
 }
        private View BuildLeftPanel()
        {
            var cmd = new Command((param) => { MessagingHub.Send(QueueType.Click, (GlobalCommand)param); });

            var btnFunc = new Func <string, GlobalCommand, Button>((text, cmdCode) =>
            {
                var btn = new Button()
                {
                    Text             = text,
                    WidthRequest     = UIConfiguration.LargeButtonWidth,
                    HeightRequest    = -1,
                    BackgroundColor  = UIConfiguration.ButtonColor,
                    FontSize         = UIConfiguration.LargeButtonFontSize,
                    BindingContext   = model.Race,
                    Margin           = new Thickness(2, 0, 2, 0),
                    BorderRadius     = 0,
                    TextColor        = UIConfiguration.CounterColors[CounterColor.White],
                    CommandParameter = cmdCode,
                };
                btn.Command = cmd;
                return(btn);
            });


            var speechSwitcher = new Switch
            {
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions   = LayoutOptions.CenterAndExpand,
                BindingContext    = model,
                Margin            = new Thickness(2, 0, 2, 0),
                BackgroundColor   = Color.Black,
                IsToggled         = model.Speech != null,
                WidthRequest      = UIConfiguration.LargeButtonWidth / 2,
            };

            speechSwitcher.Toggled += SpeechSwitcher_Toggled;

            var badlangSwitcher = new Switch
            {
                HorizontalOptions = LayoutOptions.CenterAndExpand,
                VerticalOptions   = LayoutOptions.CenterAndExpand,
                BindingContext    = model,
                Margin            = new Thickness(2, 0, 2, 0),
                BackgroundColor   = Color.Black,
                IsToggled         = model.UseBadLanguage,
                WidthRequest      = UIConfiguration.LargeButtonWidth / 2,
            };

            badlangSwitcher.Toggled += BadlangSwitcher_Toggled;

            var startFinishButton = btnFunc(null, GlobalCommand.StartFinish);

            startFinishButton.SetBinding(Button.TextProperty,
                                         FuncBinding.Create <bool, string>("IsRunning", x => x ? "Finish" : "Start"));

            var resetButton     = btnFunc("Reset", GlobalCommand.ResetAll);
            var resetTimeButton = btnFunc("Reset time", GlobalCommand.ResetTime);

            var clearButton = btnFunc("Clear", GlobalCommand.ClearAll);

            clearButton.SetBinding(VisualElement.IsEnabledProperty, FuncBinding.Create <bool, bool>("IsRunning", x => !x));

            var gpsButton = btnFunc("GPS", GlobalCommand.GPSReset);

            var backButton = btnFunc("Back", GlobalCommand.Back).With(x =>
            {
                x.SetBinding(VisualElement.IsEnabledProperty, "CanGoBack");
            });

            var dummyButton = btnFunc("", GlobalCommand.None).With(x =>
            {
                x.IsEnabled       = false;
                x.BackgroundColor = Color.Black;
                x.WidthRequest    = UIConfiguration.LargeButtonWidth / 2;
            });

            var turnButton = btnFunc("Turn", GlobalCommand.Turn).With(x =>
            {
                x.WidthRequest = UIConfiguration.LargeButtonWidth * 2;
                x.SetBinding(VisualElement.IsEnabledProperty, "IsRunning");
                x.SetBinding(Button.TextProperty,
                             FuncBinding.Create <ObservableCollection <TurnInfo>, string>(
                                 "Turns", y => y.Count > 1 ? $"Turn ({y.Count - 1})" : "Turn"));
            });

            var deleteButton = btnFunc("Del", GlobalCommand.DelSegment).With(x =>
            {
                x.WidthRequest = UIConfiguration.LargeButtonWidth;
                x.SetBinding(VisualElement.IsEnabledProperty, "CanDelete");
            });



            var grid = new Grid()
            {
                RowDefinitions =
                {
                    new RowDefinition {
                        Height = new GridLength(UIConfiguration.LargeButtonHeight)
                    },
                    new RowDefinition {
                        Height = new GridLength(1, GridUnitType.Star)
                    },
                    //new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                    new RowDefinition {
                        Height = new GridLength(UIConfiguration.LargeButtonHeight * 1.5)
                    }
                },
                ColumnDefinitions =
                {
                    new ColumnDefinition {
                        Width = new GridLength(1, GridUnitType.Star)
                    }
                },
                ColumnSpacing = 0,
                RowSpacing    = 2
            }.With(x =>
            {
                x.Children.Add(BuildButtonsPanel(startFinishButton, resetButton, resetTimeButton, clearButton, gpsButton, deleteButton), 0, 0);
                x.Children.Add(new CountersPanelBuilder(model).Build(), 0, 1);
                x.Children.Add(BuildButtonsPanel(badlangSwitcher, speechSwitcher, turnButton, backButton), 0, 2);
            });

            return(grid);
        }
 public ResponseExpression(Action sendAction, MessagingHub messaging)
 {
     _sendAction = sendAction;
     _messaging  = messaging;
 }