Exemplo n.º 1
0
        private void _WebSocket_OnMessage(object sender, MessageEventArgs e)
        {
            _lastReceivedTime = DateTime.UtcNow;
            string data = "";

            if (e.IsBinary)
            {
                data = GZipDecompresser.Decompress(e.RawData);
            }
            else
            {
                data = System.Text.Encoding.Default.GetString(e.RawData);
            }

            var pingMessage = JsonConvert.DeserializeObject <PingMessage>(data);

            if (pingMessage != null && pingMessage.ping != 0)
            {
                _logger.Log(Log.LogLevel.Trace, $"WebSocekt received data, ping={pingMessage.ping}");
                string pongData = $"{{\"pong\":{pingMessage.ping}}}";
                _WebSocket.Send(pongData);
                _logger.Log(Log.LogLevel.Trace, $"WebSocket replied data, pong={pingMessage.ping}");
            }
            else
            {
                OnResponseReceived?.Invoke(data);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Handles the login as a coroutine.
        /// </summary>
        /// <param name="username">The username that is used.</param>
        /// <param name="password">The password that is used.</param>
        /// <param name="onResponseReceived">The handler to call on success.</param>
        /// <param name="onErrorReceived">The handler to call on error.</param>
        /// <returns>An enumerator.</returns>
        private IEnumerator _LoginCoroutine(string username, string password, OnResponseReceived onResponseReceived, OnErrorReceived onErrorReceived)
        {
            var form = new WWWForm();

            form.AddField("grant_type", "password");
            form.AddField("username", username);
            form.AddField("password", password);


            using (var req = UnityWebRequest.Post(BaseUrl + "token", form))
            {
                req.SetRequestHeader("grant_type", "application/x-www-form-urlencoded");
                req.downloadHandler = new DownloadHandlerBuffer();
                yield return(req.SendWebRequest());

                if (req.isNetworkError || req.isHttpError)
                {
                    onErrorReceived(req.error);
                }
                else
                {
                    onResponseReceived(req.downloadHandler.text);
                }
            }
        }
Exemplo n.º 3
0
        private static async void WebSocketClient_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args)
        {
            if (args.MessageType == SocketMessageType.Utf8)
            {
                string jsonOutput = null;
                using (var dataReader = args.GetDataReader())
                {
                    dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                    jsonOutput = dataReader.ReadString(dataReader.UnconsumedBufferLength);
                }

                // Occasionally, the Direct Line service sends an empty message as a liveness ping. Ignore these messages.
                if (string.IsNullOrWhiteSpace(jsonOutput))
                {
                    return;
                }

                var activitySet = JsonConvert.DeserializeObject <ActivitySet>(jsonOutput);
                var activities  = activitySet.Activities.Where(a => a.From.Id == Settings.Instance.BotId);

                foreach (var activity in activities)
                {
                    Debug.WriteLine(activity.Text);
                    OnResponseReceived?.Invoke(null, new BotEventArgs(activity.Text));

                    // If there is an audio attached to the response, automatically speaks it.
                    var audioResponseUrl = activity.Attachments?.FirstOrDefault(a => a.ContentType == "audio/mp3")?.ContentUrl;
                    if (audioResponseUrl != null)
                    {
                        await TextToSpeech.SpeakAsync(activity.Speak ?? activity.Text, Settings.Instance.Culture, audioResponseUrl);
                    }
                }
            }
        }
        public async Task GetResponse()
        {
            var responseRestService = Container.Instance.Resolve <ResponseRestService>();
            var responsesViewModel  = Container.Instance.Resolve <ResponsesViewModel>();
            var response            = await responseRestService.GetResponse(ResponseId);

            Response = response;
            OnResponseReceived?.Invoke();
            responsesViewModel.HandleResponseModelReceived(response);
        }
Exemplo n.º 5
0
        private async Task Listen()
        {
            var bytesReceived = new byte[256];

            Debug.WriteLine("Blackmagic listener started!");
            while (true)
            {
                try
                {
                    var readTask = _stream.ReadAsync(bytesReceived, 0, bytesReceived.Length, _cancellationTokenSource.Token);
                    await Task.WhenAny(readTask, Task.Delay(-1, _cancellationTokenSource.Token)).ConfigureAwait(false);

                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        throw new OperationCanceledException(_cancellationTokenSource.Token);
                    }

                    if (!readTask.IsCompleted)
                    {
                        continue;
                    }

                    int bytes;
                    if ((bytes = readTask.Result) == 0)
                    {
                        continue;
                    }
                    var response = System.Text.Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                    OnResponseReceived?.Invoke(this, new EventArgs <string>(response));
                }
                catch (OperationCanceledException)
                {
                    Debug.WriteLine("Listener canceled");
                    break;
                }
                catch (System.IO.IOException ioException)
                {
                    if (_tcpClient.Connected)
                    {
                        Debug.WriteLine($"Blackmagic listener encountered error: {ioException}");
                        continue;
                    }
                    Logger.Error(ioException, "Blackmagic listener was closed forcibly, attempting to reconnect to Blackmagic.");
                    Debug.WriteLine($"Blackmagic listener was closed forcibly: {ioException}\n Attempting to reconnect to Blackmagic...");

                    Disconnect();
                    break;
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Unknown Blackmagic listener error");
                    Debug.WriteLine($"Blackmagic listener error. {ex.Message}");
                }
            }
        }
        public void ReceivedCommandResponse(ZToolPacket packet)
        {
            _logger.Trace(" {} received as synchronous command.", packet.GetType().Name);
            lock (packet) {
                OnResponseReceived?.Invoke(this, packet);

                // Do not set response[0] again.
                //response[0] = packet;
                //response.notify();
            }
        }
Exemplo n.º 7
0
 public R Request(S obj)
 {
     using (var client = new NamedPipeClientStream(ServerName, PipeName))
     {
         client.Connect();
         Formatter.Serialize(client, obj);
         OnRequestSended?.Invoke(this, obj);
         var response = Formatter.Deserialize <R>(client);
         OnResponseReceived?.Invoke(this, response);
         return(response);
     }
 }
Exemplo n.º 8
0
        public async Task <R> RequestAsync(S obj, CancellationToken cancellationToken)
        {
            using (var client = new NamedPipeClientStream(ServerName, PipeName))
            {
                await client.ConnectAsync(cancellationToken);

                Formatter.Serialize(client, obj);
                OnRequestSended?.Invoke(this, obj);
                var response = Formatter.Deserialize <R>(client);
                OnResponseReceived?.Invoke(this, response);
                return(response);
            }
        }
Exemplo n.º 9
0
        public void ClearEventHandlers()
        {
            if (OnResponseReceived == null)
            {
                return;
            }

            Delegate[] handlers = OnResponseReceived.GetInvocationList();
            foreach (var handler in handlers)
            {
                OnResponseReceived -= (handler as ResponseReceivedHandler);
            }
        }
 // Send a command asynchronously, and perform the appropriate callback when a response is received,
 // or the request times out.
 public void SendCommandAsync(Command command, OnResponseReceived OnReceived, OnResponseTimeout OnTimeout, TimeSpan timeout)
 {
     connection.SendMessage(
         0,
         command.ID,
         "",
         (string answer) => {
         OnReceived(new List <string>(answer.Split('\n')));
     },
         () => {
         OnTimeout();
     },
         timeout
         );
 }
Exemplo n.º 11
0
 private void EmitResponseReceived(string name, IPEndPoint serviceEndPoint, EndPoint remoteEndPoint, byte[] payload)
 {
     if (ForwardResponse(serviceEndPoint, remoteEndPoint))
     {
         OnResponseReceived?.Invoke(new Service(name,
                                                serviceEndPoint,
                                                _localAddress,
                                                _networkInterfaceId,
                                                payload));
     }
     else
     {
         Log.DebugFormat("Ignoring local service '{0}' from '{1}', we can't possibly connect to it",
                         serviceEndPoint,
                         remoteEndPoint);
     }
 }
Exemplo n.º 12
0
        protected override void PostRequest(ResponseContainer response)
        {
            Logger.Instance.Log(LogLevel.Debug, $"Got {response.StatusCode} to {response.RequestMessage.RequestUri}, ({response.ParsedObjects.Count:N0} parsed objects)");

            Debug.WriteLine($"Response to {response.RequestMessage.RequestUri}, ({response.ParsedObjects.Count:N0} parsed objects)");
            foreach (DataObject dataObject in response.ParsedObjects)
            {
                Debug.WriteLine($"Parsed object by {dataObject.ParserType}: {dataObject}");
            }

            // Save to DB
            foreach (SaverBase saver in _savers)
            {
                saver.Run(response.ParsedObjects);
            }

            // Execute other interests
            OnResponseReceived?.Invoke(response);
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Handles the getting of a profile as a coroutine.
        /// </summary>
        /// <param name="id">The profile's id</param>
        /// <param name="onResponseReceived">The handler to call on success.</param>
        /// <param name="onErrorReceived">The handler to call on error.</param>
        /// <returns>An enumerator.</returns>
        private IEnumerator _GetProfileCoroutine(string id, OnResponseReceived onResponseReceived, OnErrorReceived onErrorReceived)
        {
            using (var req = UnityWebRequest.Get(BaseUrl + "api/user-contexts/" + id))
            {
                req.SetRequestHeader("content-type", "application/json");
                req.SetRequestHeader("authorization", _loginResponse.Token);
                req.downloadHandler = new DownloadHandlerBuffer();
                yield return(req.SendWebRequest());

                if (req.isNetworkError || req.isHttpError)
                {
                    onErrorReceived(req.error);
                }
                else
                {
                    onResponseReceived(req.downloadHandler.text);
                }
            }
        }
Exemplo n.º 14
0
        /*
         * The Listen method.
         * The method works as long as the connection
         * to the remote host is alive. It gets a buffer
         * from the stream, and if it's not null - it writes
         * it to the console (When we will have a GUI, it will
         * be shown as a responsive design).
         */
        private void Listen()
        {
            try
            {
                // As long as the connection is alive...
                while (_connected)
                {
                    try
                    {
                        Nullable <char> c        = null;
                        string          response = string.Empty;
                        // Read a buffer from the stream
                        while ((c = (char)(_streamReader.Read())) != '|' && !_streamReader.EndOfStream)
                        {
                            response += c;
                        }

                        // If it is null, raise an exception.
                        if (response == null || string.IsNullOrWhiteSpace(response))
                        {
                            _connected = false;
                            continue;
                        }

                        // Otherwise, write the data to the console.
                        if (!string.IsNullOrWhiteSpace(response))
                        {
                            OnResponseReceived?.Invoke(response);
                            _streamReader.BaseStream.Flush();
                        }
                    }
                    catch (Exception)
                    {
                        _connected = false;
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Exemplo n.º 15
0
    public void Receive(Response response)
    {
        if (response.GetType() == typeof(FailureDetectionResponse))
        {
            (response as FailureDetectionResponse).DeadEdges.ForEach(edge => comms.Node.Router.DeleteEdge(edge.Item1, edge.Item2));
        }

        new Thread(() =>
        {
            Thread.Sleep(Constants.SEND_DURATION_TIME / Constants.TimeScale);

            if (response.DestinationID == comms.Node.Id)
            {
                OnResponseReceived?.Invoke(this, new ResponseEventArgs(response));
            }
            else
            {
                uint?nextHop = comms.Node.Router.NextHop(comms.Node.Id, response.DestinationID);
                Send(nextHop, response);
            }
        }).Start();
    }
Exemplo n.º 16
0
        public void Start(string[] ips, int count = 4)
        {
            var goal  = ips.Length * count;
            var local = LocalIp;

            OnResponseReceived?.Invoke($"Current IP: {local} ({GetIpLocation(local)})");
            new Thread(new ThreadStart(() =>
            {
                foreach (var ip in ips.Select((value, index) => new { value, index }))
                {
                    var roundTrip = new List <int>();
                    var head      = $">>>>>>>>>>>>>>>>> Started to ping [{ip.value}]:  ";
                    OnResponseReceived?.Invoke(head);
                    for (int i = 0; i < count; i++)
                    {
                        OnResponseReceived(DoPing(ip.value));
                        OnProgressUpdated(ip.index * 4 + i + 1, goal);
                        Thread.Sleep(1000);
                    }
                }
                OnResponseReceived?.Invoke("================== Done ===================");
            })).Start();
        }
        private void _WebSocket_OnMessage(object sender, MessageEventArgs e)
        {
            _lastReceivedTime = DateTime.UtcNow;

            if (e.IsBinary)
            {
                string data = GZipDecompresser.Decompress(e.RawData);

                var pingMessage = JsonConvert.DeserializeObject <PingMessage>(data);
                if (pingMessage != null && pingMessage.ping != 0)
                {
                    //Console.WriteLine($"received ping:{pingMessage.ping}");
                    string pongData = $"{{\"pong\":{pingMessage.ping}}}";
                    _WebSocket.Send(pongData);
                    //Console.WriteLine($"replied pong:{pingMessage.ping}");
                }
                else
                {
                    var response = JsonConvert.DeserializeObject <DataResponseType>(data);

                    OnResponseReceived?.Invoke(response);
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Method implements initial request. Returned result sets to Atomics.UnitDescription property and
        /// to internal this._xmlDescription variable.
        /// </summary>
        /// <param name="hostNameorAddress">Host name or IP address of the AV receiver</param>
        public bool RequestUnitDescription(string hostNameorAddress)
        {
            Atomics.HostNameOrIPAddress = hostNameorAddress;

            bool result = false;

            try
            {
                if (PingIpAddress(3, hostNameorAddress) == true)
                {
                    string ynccmd = YNCCommand.CreateCommand(MethodType.NONE);

                    Atomics.UnitDescription = Http.Send(hostNameorAddress, Atomics.UnitDescriptionPath, HttpMethod.Get, ynccmd);
                    UnitDescription         = Atomics.UnitDescription;
                    OnResponseReceived?.Invoke(this, new CommEventArgs()
                    {
                        Success = true, UnitDescription = Atomics.UnitDescription, YNCFunction = CommandListFunctionType.UnitDescription
                    });

                    result = true;
                }
                else
                {
                    throw new Exception("Receiver is not accessible.");
                }
            }
            catch (Exception ex)
            {
                OnResponseReceived?.Invoke(this, new CommEventArgs()
                {
                    Success = false, ErrorMessage = ex.Message, YNCFunction = CommandListFunctionType.UnitDescription
                });
            }

            return(result);
        }
 public void ReceivedCommandResponse(ZToolPacket packet)
 {
     Log.Verbose(" {Packet} received as synchronous command.", packet.GetType().Name);
     OnResponseReceived?.Invoke(this, packet);
 }
Exemplo n.º 20
0
        private static void CallHandler(object obj, HttpResponseMessage response)
        {
            var args = new ResponseEventArguments(DateTime.Now, response.StatusCode);

            OnResponseReceived.Invoke(obj, args);
        }
Exemplo n.º 21
0
 private void sender_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
 {
     inUse = false;
     OnResponseReceived?.Invoke(this, new ResponseReceivedEventArgs(asyncResponse));
 }
 private void SocketOnResponseReceived(Service service)
 {
     OnResponseReceived?.Invoke(service);
 }
Exemplo n.º 23
0
 private Task HandleResponse(JsonObject data)
 {
     OnResponseReceived?.Invoke(this, data);
     return(Task.CompletedTask);
 }
Exemplo n.º 24
0
 public AppServiceResponseListener(OnResponseReceived onReceived)
 {
     this.onResponseReceived = onReceived;
 }
Exemplo n.º 25
0
        public static async void StartService()
        {
            try
            {
                if (isRunning)
                {
                    // If the service is already running, exits.
                    return;
                }

                isRunning = true;

                var isConnected = false;
                while (!isConnected)
                {
                    // Be sure to be connected to the Internet.
                    var profile = NetworkInformation.GetInternetConnectionProfile();
                    isConnected = profile?.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
                    await Task.Delay(200);
                }

                if (Settings.Instance == null)
                {
                    await LoadSettingsAsync();
                }

                if (directLineClient == null)
                {
                    // Obtain a token using the Direct Line secret
                    var tokenResponse = await new DirectLineClient(Settings.Instance.DirectLineSecret).Tokens.GenerateTokenForNewConversationAsync();

                    // Use token to create conversation
                    directLineClient = new DirectLineClient(tokenResponse.Token);
                    conversation     = await directLineClient.Conversations.StartConversationAsync();

                    // Connect using a WebSocket.
                    webSocketClient = new MessageWebSocket();
                    webSocketClient.MessageReceived += WebSocketClient_MessageReceived;
                    await webSocketClient.ConnectAsync(new Uri(conversation.StreamUrl));
                }

                if (assistantInvokerSpeechRecognizer == null)
                {
                    // Create an instance of SpeechRecognizer.
                    assistantInvokerSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));
                    assistantInvokerSpeechRecognizer.Timeouts.InitialSilenceTimeout = TimeSpan.MaxValue;
                    assistantInvokerSpeechRecognizer.Timeouts.BabbleTimeout         = TimeSpan.MaxValue;

                    // Add a list constraint to the recognizer.
                    var listConstraint = new SpeechRecognitionListConstraint(new string[] { Settings.Instance.AssistantName }, "assistant");
                    assistantInvokerSpeechRecognizer.Constraints.Add(listConstraint);
                    await assistantInvokerSpeechRecognizer.CompileConstraintsAsync();
                }

                if (commandSpeechRecognizer == null)
                {
                    commandSpeechRecognizer = new SpeechRecognizer(new Language(Settings.Instance.Culture));

                    // Apply the dictation topic constraint to optimize for dictated freeform speech.
                    var dictationConstraint = new SpeechRecognitionTopicConstraint(SpeechRecognitionScenario.WebSearch, "dictation");
                    commandSpeechRecognizer.Constraints.Add(dictationConstraint);
                    await commandSpeechRecognizer.CompileConstraintsAsync();
                }

                // The assistant is ready to receive input.
                SoundPlayer.Instance.Play(Sounds.SpeechActive);

                while (isRunning)
                {
                    try
                    {
                        var assistantInvocationResult = await assistantInvokerSpeechRecognizer.RecognizeAsync();

                        if (assistantInvocationResult.Status == SpeechRecognitionResultStatus.Success && assistantInvocationResult.Confidence != SpeechRecognitionConfidence.Rejected)
                        {
                            OnStartRecognition?.Invoke(null, EventArgs.Empty);
                            SoundPlayer.Instance.Play(Sounds.Ready);

                            // Starts command recognition. It returns when the first utterance has been recognized.
                            var commandResult = await commandSpeechRecognizer.RecognizeAsync();

                            if (commandResult.Status == SpeechRecognitionResultStatus.Success && commandResult.Confidence != SpeechRecognitionConfidence.Rejected)
                            {
                                var command = commandResult.NormalizeText();
                                Debug.WriteLine(command);

                                OnCommandReceived?.Invoke(null, EventArgs.Empty);

                                // Sends the activity to the Bot. The answer will be received in the WebSocket received event handler.
                                var userMessage = new Activity
                                {
                                    From = new ChannelAccount(Settings.Instance.UserName),
                                    Text = command,
                                    Type = ActivityTypes.Message
                                };

                                await directLineClient.Conversations.PostActivityAsync(conversation.ConversationId, userMessage);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
                    }
                }

                // Clean up used resources.
                SoundPlayer.Instance.Play(Sounds.SpeechStopped);
            }
            catch (Exception ex)
            {
                OnResponseReceived?.Invoke(null, new BotEventArgs(ex.Message));
                SoundPlayer.Instance.Play(Sounds.SpeechStopped);
            }

            assistantInvokerSpeechRecognizer?.Dispose();
            commandSpeechRecognizer?.Dispose();
            webSocketClient?.Dispose();
            directLineClient?.Dispose();

            assistantInvokerSpeechRecognizer = null;
            commandSpeechRecognizer          = null;
            webSocketClient  = null;
            conversation     = null;
            directLineClient = null;

            isRunning = false;
        }