示例#1
0
        /// <summary>
        /// Sends a success response to the client. Used for indicating successful executed commands.
        /// </summary>
        private static void SendSuccess(int deviceIndex)
        {
            Console.WriteLine($"Successfully executed command for device {deviceIndex}");
            ServerResponse response = new ServerResponse(new SuccessResponse(deviceIndex));

            SendData(deviceIndex, response.ToJson());
        }
示例#2
0
        /// <summary>
        /// Sends a <see cref="HeartRateResponse"/> to the client.
        /// </summary>
        /// <param name="heartRateResponse">The HeartRateResponse holding the measurement data.</param>
        private static void OnHeartRateChange(HeartRateResponse heartRateResponse)
        {
            Console.WriteLine("Sending heart rate to client: {0}", heartRateResponse.HeartRate);
            ServerResponse response = new ServerResponse(heartRateResponse);

            SendData(heartRateResponse.DeviceIndex, response.ToJson());
        }
示例#3
0
        /// <summary>
        /// Sends a <see cref="DeviceConnectionResponse"/> to the client.
        /// </summary>
        /// <param name="deviceIndex">The index of the device</param>
        /// <param name="isConnected">Whether the device is connected or not.</param>
        private static void OnDeviceConnectionStatusChanged(int deviceIndex, bool isConnected)
        {
            Console.WriteLine("Sending device connection status to client: isConnected = {0}", isConnected);
            ServerResponse response =
                new ServerResponse(new DeviceConnectionResponse(deviceIndex, isConnected));

            SendData(deviceIndex, response.ToJson());
        }
示例#4
0
        public Server()
        {
            Console.Write("Server started\n");

            m_Clients = new Dictionary <IWebSocketConnection, Client>();
            m_Socket  = new WebSocketServer($"ws://0.0.0.0:1000");
            ServerResponse response = new ServerResponse();

            m_Socket.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    Console
                    .WriteLine($"[Client: connected] " +
                               $"{socket.ConnectionInfo.ClientIpAddress}");
                };

                socket.OnMessage = (string message) =>
                {
                    var request = Json.FromJson <ClientRequest>(message);

                    switch (request.Operation)
                    {
                    case OperationType.Login:
                        {
                            if (m_Clients.ContainsValue(request.Client))
                            {
                                return;
                            }

                            m_Clients.Add(socket, request.Client);
                            response.Message      = $"{request.Client.Nickname} connected to chat!";
                            response.ResponseType = ResponseType.Login;
                            foreach (var client in m_Clients)
                            {
                                if (client.Value.Nickname != request.Client.Nickname)
                                {
                                    client.Key.Send(response.ToJson());
                                }
                            }
                        }
                        break;

                    case OperationType.Logout:
                        {
                            lock (sync)
                            {
                                socket.Close();
                                m_Clients.Remove(socket);
                            }
                        }
                        break;

                    case OperationType.PostMessage:
                        {
                            string messageToSend =
                                $"{request.Client.Nickname}: " +
                                $"{request.Client.Message}";
                            response.Message      = messageToSend;
                            response.ResponseType = ResponseType.Message;
                            foreach (var client in m_Clients)
                            {
                                if (client.Value.Nickname != request.Client.Nickname)
                                {
                                    client.Key.Send(response.ToJson());
                                }
                            }
                        }
                        break;

                    default:
                        //Console.WriteLine(message);
                        break;
                    }
                };

                socket.OnError = (Exception exception) =>
                {
                    lock (sync)
                    {
                        Console
                        .WriteLine($"[Error: client disconnected] " +
                                   $"{socket.ConnectionInfo.ClientIpAddress}");
                        if (m_Clients.ContainsKey(socket))
                        {
                            var clientToDelete    = m_Clients[socket];
                            response.Message      = $"{clientToDelete.Nickname} disconnected from chat!";
                            response.ResponseType = ResponseType.Logout;
                            m_Clients.Remove(socket);
                            foreach (var client in m_Clients)
                            {
                                client.Key.Send(response.ToJson());
                            }
                        }
                    }
                };

                socket.OnClose = () =>
                {
                    lock (sync)
                    {
                        Console
                        .WriteLine($"[Client: disconnected] " +
                                   $"{socket.ConnectionInfo.ClientIpAddress}");

                        if (m_Clients.ContainsKey(socket))
                        {
                            //handling disconnecting of client
                        }
                    }
                };
            });
        }
示例#5
0
        /// <summary>
        /// Executes the given command. Will send any exception that occures to the client.
        /// </summary>
        /// <param name="serverCommand">The ServerCommand containing the deviceIndex and the command.</param>
        private static async Task ExecuteCommand(ServerCommand serverCommand)
        {
            int deviceIndex = serverCommand.DeviceIndex;

            if (deviceIndex > MiBands.Count - 1)
            {
                MiBands.Add(new MiBand2(MiBands.Count));
            }
            MiBand2 miBand2 = MiBands[deviceIndex];

            try
            {
                switch (serverCommand.Command)
                {
                case Consts.Command.ConnectBand:
                    await miBand2.ConnectBandAsync();

                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.DisconnectBand:
                    miBand2.DisconnectBand();
                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.AuthenticateBand:
                    await miBand2.AuthenticateBandAsync();

                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.StartMeasurement:
                    await miBand2.StartMeasurementAsync();

                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.StopMeasurement:
                    await miBand2.StopMeasurementAsync();

                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.SubscribeToHeartRateChange:
                    miBand2.SubscribeToHeartRateChange(OnHeartRateChange);
                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.SubscribeToDeviceConnectionStatusChanged:
                    miBand2.DeviceConnectionChanged += OnDeviceConnectionStatusChanged;
                    break;

                case Consts.Command.AskUserForTouch:
                    await miBand2.AskUserForTouchAsync();

                    SendSuccess(deviceIndex);
                    break;

                case Consts.Command.StopServer:
                    if (miBand2.Connected)
                    {
                        miBand2.DisconnectBand();
                    }
                    _listenForCommands = false;
                    _server.Stop();
                    break;

                default:
                    ArgumentOutOfRangeException exception =
                        new ArgumentOutOfRangeException(nameof(serverCommand.Command), serverCommand.Command,
                                                        "Could not find command.");
                    SendData(serverCommand.DeviceIndex, new ServerResponse(exception).ToJson());
                    break;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("EXCEPTION OCCURED:");
                Console.WriteLine("Type: {0}\nMessage{1}", exception.GetType(), exception.Message);
                ServerResponse response = new ServerResponse(exception);
                SendData(serverCommand.DeviceIndex, response.ToJson());
            }
        }