Exemplo n.º 1
0
 private void ParseAntennaReplyParam(XmlTextReader replyReader, ref CommandReply result)
 {
     // do until end XML tag </returnValue> is found
     while (replyReader.Read() &&
            !(replyReader.Name == "returnValue" && replyReader.NodeType == XmlNodeType.EndElement))
     {
         // start XML tag <antenna>: we get an paramblock for antennas
         if (replyReader.Name == "antenna" && replyReader.NodeType == XmlNodeType.Element)
         {
             ParameterDesc container = new ParameterDesc("antenna", true, true);
             result.Parameters.Add(container);
             // do until end XML tag </antenna> is found
             while (replyReader.Read() &&
                    !(replyReader.Name == "antenna" && replyReader.NodeType == XmlNodeType.EndElement))
             {
                 if (replyReader.NodeType == XmlNodeType.Element)
                 {
                     string paramName = replyReader.Name;
                     if (replyReader.Read() && (XmlNodeType.Text == replyReader.NodeType))
                     {
                         ParameterDesc param = new ParameterDesc(paramName, replyReader.Value);
                         result.Parameters.Add(param);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 2
0
        public async Task Ipv6()
        {
            var commandReply = new CommandReply(
                CommandReplyType.Succeeded,
                new IPEndPoint(IPAddress.Parse("2001:db8:85a3:8d3:1319:8a2e:370:7348"), 65534));

            var stream = new MemoryWriteOnlyStream();
            await commandReply.WriteToAsync(stream, this._bufferPool).ConfigureAwait(true);

            stream.ToArray().Should().Equal(
                5,
                (byte)CommandReplyType.Succeeded,
                0,
                (byte)AddressType.Ipv6,
                32,
                1,
                13,
                184,
                133,
                163,
                8,
                211,
                19,
                25,
                138,
                46,
                3,
                112,
                115,
                72,
                255,
                254);
        }
        public override async void ChannelRead(IChannelHandlerContext context,
                                               object message)
        {
            switch (message)
            {
            case EslMessage msg when !string.IsNullOrEmpty(msg?.ContentType()):
                switch (msg.ContentType())
                {
                case EslHeadersValues.AuthRequest:
                    await _outboundListener.OnAuthentication();

                    break;

                case EslHeadersValues.CommandReply:
                    var commandAsyncEvent1 = CommandAsyncEvents.Dequeue();
                    var cmdResponse        = new CommandReply(commandAsyncEvent1.Command.Command,
                                                              msg);
                    commandAsyncEvent1.Complete(cmdResponse);
                    break;

                case EslHeadersValues.ApiResponse:
                    var commandAsyncEvent = CommandAsyncEvents.Dequeue();
                    var apiResponse       = new ApiResponse(commandAsyncEvent.Command.Command,
                                                            msg);
                    commandAsyncEvent.Complete(apiResponse);
                    break;

                case EslHeadersValues.TextEventPlain:
                    _outboundListener.OnEventReceived(msg);
                    break;

                case EslHeadersValues.TextDisconnectNotice:
                    var channel = context.Channel;
                    var address = channel.RemoteAddress;

                    await _outboundListener.OnDisconnectNotice(msg,
                                                               address);

                    break;

                case EslHeadersValues.TextRudeRejection:
                    await _outboundListener.OnRudeRejection();

                    break;

                default:
                    // Unexpected freeSwitch message
                    _logger.Warn("Unexpected message content type [{0}]",
                                 msg.ContentType());
                    break;
                }
                break;

            default:
                // Unexpected freeSwitch message
                _logger.Warn("Unexpected message [{0}]",
                             message);
                return;
            }
        }
Exemplo n.º 4
0
 public void SendCommandReply(Command command, Action messageCompletedAction = null)
 {
     using (Stream message = Convert(CommandReply.Parse(command)))
     {
         communicationProtocol.SendMessage(message, messageCompletedAction);
     }
 }
Exemplo n.º 5
0
        public async Task Domain()
        {
            var commandReply = new CommandReply(CommandReplyType.Succeeded, new DnsEndPoint("google.com", 65534));
            var stream       = new MemoryWriteOnlyStream();
            await commandReply.WriteToAsync(stream, this._bufferPool).ConfigureAwait(true);

            stream.ToArray().Should().Equal(
                5,
                (byte)CommandReplyType.Succeeded,
                0,
                (byte)AddressType.DomainName,
                10,
                103,
                111,
                111,
                103,
                108,
                101,
                46,
                99,
                111,
                109,
                255,
                254);
        }
Exemplo n.º 6
0
        async Task RunProxyAsync(CancellationToken cancellationToken)
        {
            IProxy proxy;

            try
            {
                var command = await Command.ReadFromAsync(this._clientStream, this._bufferPool).ConfigureAwait(false);

                switch (command.CommandType)
                {
                case CommandType.Connect:
                    proxy = this._proxyFactory.CreateTcpProxy(
                        this._clientStream,
                        command.EndPoint,
                        this._bufferPool);
                    break;

                case CommandType.UdpAssociate:
                    proxy = this._proxyFactory.CreateUdpProxy(this._clientStream, this._bufferPool);
                    break;

                default:
                    throw new ProtocolException(CommandReplyType.CommandNotSupported);
                }
            }
            catch (Exception ex)
            {
                var commandReplyType = CommandReplyType.GeneralFailure;
                switch (ex)
                {
                case ProtocolException socksEx:
                    this._log.LogError(socksEx, "Protocol error");
                    commandReplyType = socksEx.ErrorCode;
                    break;

                case IOException _:
                case SocketException _:
                    this._log.LogError("Network error: {0}", ex.Message);
                    break;

                default:
                    this._log.LogError("Connection error.", ex);
                    break;
                }

                await new CommandReply(commandReplyType, s_EmptyEndPoint)
                .WriteToAsync(this._clientStream, this._bufferPool)
                .ConfigureAwait(false);
                return;
            }

            var reply = new CommandReply(CommandReplyType.Succeeded, proxy.BindEndPoint);
            await reply.WriteToAsync(this._clientStream, this._bufferPool).ConfigureAwait(false);

            using (proxy)
            {
                await proxy.RunAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Exemplo n.º 7
0
 private void OnCallIdReply(CmdBase command, CommandReply reply)
 {
     if (!reply.Success)
     {
         Debug.WriteLine("OnCallIdReply " + reply.ErrorMessage);
     }
     command.ReplyReceived -= OnCallIdReply;
 }
Exemplo n.º 8
0
 private static void OnCommandReply(CmdBase command, CommandReply reply)
 {
     command.ReplyReceived -= OnCommandReply;
     if (!reply.Success)
     {
         Console.WriteLine("Command failed: " + reply.ErrorMessage);
     }
 }
        public override async void ChannelRead(IChannelHandlerContext context,
                                               object message)
        {
            var eslMessage  = message as EslMessage;
            var contentType = eslMessage?.ContentType();

            if (string.IsNullOrEmpty(contentType))
            {
                return;
            }
            // Handle command/reply
            if (contentType.Equals(EslHeadersValues.CommandReply))
            {
                var commandAsyncEvent = CommandAsyncEvents.Dequeue();
                var reply             = new CommandReply(commandAsyncEvent.Command.Command, eslMessage);
                commandAsyncEvent.Complete(reply);
                return;
            }

            // Handle api/response
            if (contentType.Equals(EslHeadersValues.ApiResponse))
            {
                var commandAsyncEvent = CommandAsyncEvents.Dequeue();
                var apiResponse       = new ApiResponse(commandAsyncEvent.Command.Command,
                                                        eslMessage);
                commandAsyncEvent.Complete(apiResponse);
                return;
            }

            // Handle text/event-plain
            if (contentType.Equals(EslHeadersValues.TextEventPlain))
            {
                await _inboundListener.OnEventReceived(eslMessage);

                return;
            }

            // Handle disconnect/notice message
            if (contentType.Equals(EslHeadersValues.TextDisconnectNotice))
            {
                var channel = context.Channel;
                var address = channel.RemoteAddress;
                await _inboundListener.OnDisconnectNotice(eslMessage, address);

                return;
            }

            // Handle rude/rejection message
            if (contentType.Equals(EslHeadersValues.TextRudeRejection))
            {
                await _inboundListener.OnRudeRejection();

                return;
            }

            // Unexpected freeSwitch message
            _logger.Warn("Unexpected message content type [{0}]", contentType);
        }
Exemplo n.º 10
0
 public virtual void HandleReply(CommandReply reply)
 {
     // a command is only invoked once.
     if (ReplyReceived != null)
     {
         ReplyReceived(this, reply);
         ReplyReceived = null;
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Handle an message
        /// </summary>
        /// <param name="context">Context unique for this handler instance</param>
        /// <param name="message">Message to process</param>
        /// <remarks>
        /// All messages that can't be handled MUST be send up the chain using <see cref="IPipelineHandlerContext.SendUpstream"/>.
        /// </remarks>
        public void HandleUpstream(IPipelineHandlerContext context, IPipelineMessage message)
        {
            if (message is EventRecieved)
            {
                HandleBackgroundCompletion(context, (EventRecieved)message);
                return;
            }
            if (!(message is ReceivedMessage))
            {
                context.SendUpstream(message);
                return;
            }


            var msg  = (ReceivedMessage)message;
            var type = msg.Message.Headers["Content-Type"];

            if (type == null || type != "command/reply")
            {
                context.SendUpstream(message);
                return;
            }

            SendCommandMessage nextCommand = null;
            ICommand           curMsg;

            lock (_outbound)
            {
                if (_current == null)
                {
                    throw new InvalidOperationException("No active command set.");
                }
                _logger.Trace("Got reply for " + _current);
                curMsg      = _current;
                nextCommand = _outbound.Count > 0 ? _outbound.Dequeue() : null;
                _current    = null;
            }

            if (curMsg is BgApiCmd)
            {
                HandleBgApi(context, msg.Message, (BgApiCmd)curMsg);
            }
            else
            {
                var result = msg.Message.Headers["Reply-Text"].StartsWith("+");
                var body   = msg.Message.Headers["Reply-Text"];
                var reply  = new CommandReply(curMsg, result, body);
                _logger.Debug("Sending reply " + body);
                context.SendUpstream(reply);
            }

            if (nextCommand != null)
            {
                _logger.Trace("Sending next command down: " + nextCommand.Command);
                SendCommand(context, nextCommand);
            }
        }
        /// <summary>
        ///
        /// </summary>
        ///
        public void Unsubscribe(string typeOfChannel)
        {
            PerfTiming perfTimer1 = new PerfTiming();

            perfTimer1.Start();


            // Validate current state of Reader API
            if (!RfReaderApi.IsValid)
            {
                throw new RfReaderApiInvalidModeException();
            }

            if (RfReaderApi.TER == typeOfChannel || RfReaderApi.ALARM == typeOfChannel || RfReaderApi.ALL == typeOfChannel)
            {
                UnSubscribeChannelListener(typeOfChannel);
            }
            else
            {
                throw new RfReaderApiException(RfReaderApiException.ResultCode_System, RfReaderApiException.Error_InvalidParameter);
            }

            // Send unsubscribe command to ReaderService
            // We do this deliberately after turning down our channels in order not
            // to prevent channel shutdowns if exception during unsubscribe commands occur
            // Do a security check whether we are connected at all
            if (!this.CommandChannel.IsConnected())
            {
                throw new RfReaderApiException(RfReaderApiException.ResultCode_System, RfReaderApiException.Error_NoConnection);
            }
            List <ParameterDesc> unsubscribeParams = new List <ParameterDesc>();

            unsubscribeParams.Add(new ParameterDesc("type", typeOfChannel));

            Command      rpCommand = new Command("unsubscribe", unsubscribeParams);
            string       commandID = "";
            string       replyMsg  = this.CommandChannel.execute(rpCommand.getXmlCommand(ref commandID), commandID);
            CommandReply rpReply   = CommandReply.DecodeXmlCommand(replyMsg);

            if (rpReply == null)
            {
                // There is no reply from our connected reader
                throw new RfReaderApiException(RfReaderApiException.ResultCode_System,
                                               RfReaderApiException.Error_NoReply);
            }
            if (rpReply.ResultCode != 0)
            {
                // forward errors as exceptions
                throw new RfReaderApiException(rpReply.ResultCode, rpReply.Error,
                                               rpReply.Cause);
            }

            if (RfReaderApi.showPerformanceInfo)
            {
                ProvideInformation(this, "Unsubscribe took " + perfTimer1.End().ToString("##.###") + "s");
            }
        }
Exemplo n.º 13
0
        public void Unsupported_endpoint_type_should_throw()
        {
            var commandReply = new CommandReply(CommandReplyType.Succeeded, new DummyEndPoint());
            var stream       = new MemoryWriteOnlyStream();

            commandReply
            .Awaiting(x => x.WriteToAsync(stream, this._bufferPool))
            .Should()
            .Throw <InvalidDataException>()
            .And.Message.Should().ContainEquivalentOf(nameof(EndPoint));
        }
Exemplo n.º 14
0
        public virtual CommandReply CreateReply(string dataToParse)
        {
            if (string.IsNullOrEmpty(dataToParse.Trim()))
            {
                return(new CommandReply(false));
            }

            CommandReply reply = new CommandReply(dataToParse.Trim()[0] == '+');

            reply.ErrorMessage = dataToParse;
            return(reply);
        }
Exemplo n.º 15
0
 public override CommandReply CreateReply(string dataToParse)
 {
     if (dataToParse == "OK")
     {
         return(new CommandReply(true));
     }
     else
     {
         CommandReply reply = new CommandReply(false);
         reply.ErrorMessage = dataToParse;
         return(reply);
     }
 }
Exemplo n.º 16
0
        private void HandleCommandReply(MpvEvent @event)
        {
            if (CommandReply == null)
            {
                return;
            }

            var replyUserData = @event.ReplyUserData;
            var error         = @event.Error;

            var eventArgs = new MpvCommandReplyEventArgs(replyUserData, error);

            CommandReply.Invoke(this, eventArgs);
        }
Exemplo n.º 17
0
        private void OnBridgeCallId(CmdBase command, CommandReply reply)
        {
            GetVariableReply gvr = (GetVariableReply)reply;

            if (!gvr.Success)
            {
                Debug.WriteLine("OnBridgeCallId " + reply.ErrorMessage);
            }

            string      otherChannelId = (string)command.ContextData;
            SetVariable sv             = new SetVariable(otherChannelId, "gate_callid", gvr.Value);

            sv.ReplyReceived += OnCallIdReply;
            _eventMgr.Send(sv);
            command.ReplyReceived -= OnBridgeCallId;
        }
Exemplo n.º 18
0
        public void ChannelDataParserAsCommandReplyTest()
        {
            var eventData = AppDomain.CurrentDomain.BaseDirectory +
                            "\\Messages\\ChannelData.txt";
            var backgroundJobBytes = File.ReadAllBytes(eventData);
            var byteBuffer         = Unpooled.CopiedBuffer(backgroundJobBytes);
            var channel            = new EmbeddedChannel(new EslFrameDecoder());

            channel.WriteInbound(byteBuffer);

            var message      = channel.ReadInbound <EslMessage>();
            var commandReply = new CommandReply("connect", message);

            Assert.Equal("+OK", commandReply.ReplyText);
            Assert.Equal(true, commandReply.IsOk);
            Assert.Equal("command/reply", commandReply.ContentType);
        }
Exemplo n.º 19
0
        public async Task can_send_multple_commands()
        {
            using (var listener = new OutboundListener(0))
            {
                listener.Start();

                bool         commandRequestReceived = false;
                CommandReply commandReply           = null;

                listener.Connections.Subscribe(
                    async(socket) =>
                {
                    await socket.Connect();

                    commandReply = await socket.Linger();

                    commandReply = await socket.NoLinger();
                });

                using (var freeSwitch = new FakeFreeSwitchSocket(listener.Port))
                {
                    freeSwitch.MessagesReceived.FirstAsync(m => m.StartsWith("connect"))
                    .Subscribe(async _ => await freeSwitch.SendChannelDataEvent());

                    freeSwitch.MessagesReceived.FirstAsync(m => m.StartsWith("linger"))
                    .Subscribe(async _ =>
                    {
                        await freeSwitch.SendCommandReplyOk();
                    });

                    freeSwitch.MessagesReceived.FirstAsync(m => m.StartsWith("nolinger"))
                    .Subscribe(async _ =>
                    {
                        await freeSwitch.SendCommandReplyError("FAILED");
                        commandRequestReceived = true;
                    });

                    await Wait.Until(() => commandRequestReceived);

                    Assert.True(commandRequestReceived);
                    Assert.NotNull(commandReply);
                    Assert.False(commandReply.Success);
                }
            }
        }
Exemplo n.º 20
0
        public void it_should_parse_Command_Reply_OK()
        {
            var parser   = new Parser();
            var rawInput = "Content-Type: command/reply\nReply-Text: +OK\n\n";

            foreach (char c in rawInput)
            {
                parser.Append(c);
            }

            Assert.True(parser.Completed);

            var reply = new CommandReply(parser.ExtractMessage());

            Assert.NotNull(reply);
            Assert.True(reply.Success);

            Console.WriteLine(reply);
        }
Exemplo n.º 21
0
        public async Task Ipv4()
        {
            var commandReply = new CommandReply(
                CommandReplyType.Succeeded,
                new IPEndPoint(IPAddress.Parse("1.2.3.4"), 65534));

            var stream = new MemoryWriteOnlyStream();
            await commandReply.WriteToAsync(stream, this._bufferPool).ConfigureAwait(true);

            stream.ToArray().Should().Equal(
                5,
                (byte)CommandReplyType.Succeeded,
                0,
                (byte)AddressType.Ipv4,
                1,
                2,
                3,
                4,
                255,
                254);
        }
Exemplo n.º 22
0
 private void ParseReplyParam(XmlTextReader replyReader, ref CommandReply result, Collection <string> Name)
 {
     while (replyReader.Read() &&
            !(replyReader.Name == "returnValue" && replyReader.NodeType == XmlNodeType.EndElement))
     {
         if (replyReader.NodeType == XmlNodeType.Element)
         {
             foreach (string paramName in Name)
             {
                 if (replyReader.Name == paramName)
                 {
                     if (replyReader.Read() &&
                         (XmlNodeType.Text == replyReader.NodeType || XmlNodeType.CDATA == replyReader.NodeType))
                     {
                         ParameterDesc param = new ParameterDesc(paramName, replyReader.Value);
                         result.Parameters.Add(param);
                     }
                 }
             }
         }
     }
 }
        public override void Action(CommandCaller caller, string input, string[] args)
        {
            string command = string.Join(" ", args);

            List <string> argList = new List <string>();

            while (command.Contains("\""))
            {
                int first = command.IndexOf("\"", StringComparison.Ordinal);
                int last  = command.IndexOf("\"", first + 1, StringComparison.Ordinal);

                string arg = command.Substring(first, last - first + 1);
                command = command.Replace(arg, "");

                argList.Add(arg.Trim(' ', '"'));
            }

            argList.AddRange(command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));

            if (argList.Count < MinimumArguments)
            {
                throw new UsageException();
            }

            CommandReply reply = Action(caller, argList.ToArray());

            if (!reply.IsEmpty)
            {
                if (Main.netMode == 0 || Type.HasFlag(CommandType.Chat))
                {
                    caller.Reply(reply.Text, reply.TextColor);
                }
                else
                {
                    NetMessage.BroadcastChatMessage(NetworkText.FromLiteral(reply.Text), reply.TextColor);
                }
            }
        }
Exemplo n.º 24
0
        public static void EventLoop()
        {
            while (true)
            {
                IntPtr    ptr = mpv_wait_event(Handle, -1);
                mpv_event evt = (mpv_event)Marshal.PtrToStructure(ptr, typeof(mpv_event));

                if (WindowHandle == IntPtr.Zero)
                {
                    WindowHandle = FindWindowEx(MainForm.Hwnd, IntPtr.Zero, "mpv", null);
                }

                // Debug.WriteLine(evt.event_id.ToString());

                try
                {
                    switch (evt.event_id)
                    {
                    case mpv_event_id.MPV_EVENT_SHUTDOWN:
                        if (App.DebugMode)
                        {
                            Trace.WriteLine("before Shutdown.Invoke");
                        }
                        Shutdown?.Invoke();
                        if (App.DebugMode)
                        {
                            Trace.WriteLine("after Shutdown.Invoke");
                        }
                        WriteHistory(null);
                        ShutdownAutoResetEvent.Set();
                        return;

                    case mpv_event_id.MPV_EVENT_LOG_MESSAGE:
                        LogMessage?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_GET_PROPERTY_REPLY:
                        GetPropertyReply?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_SET_PROPERTY_REPLY:
                        SetPropertyReply?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_COMMAND_REPLY:
                        CommandReply?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_START_FILE:
                        StartFile?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_END_FILE:
                        var end_fileData        = (mpv_event_end_file)Marshal.PtrToStructure(evt.data, typeof(mpv_event_end_file));
                        EndFileEventMode reason = (EndFileEventMode)end_fileData.reason;
                        EndFile?.Invoke(reason);
                        break;

                    case mpv_event_id.MPV_EVENT_FILE_LOADED:
                        HideLogo();
                        FileLoaded?.Invoke();
                        WriteHistory(get_property_string("path"));
                        break;

                    case mpv_event_id.MPV_EVENT_TRACKS_CHANGED:
                        TracksChanged?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_TRACK_SWITCHED:
                        TrackSwitched?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_IDLE:
                        Idle?.Invoke();
                        if (get_property_int("playlist-count") == 0)
                        {
                            ShowLogo();
                        }
                        break;

                    case mpv_event_id.MPV_EVENT_PAUSE:
                        Pause?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_UNPAUSE:
                        Unpause?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_TICK:
                        Tick?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_SCRIPT_INPUT_DISPATCH:
                        ScriptInputDispatch?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_CLIENT_MESSAGE:
                        var      client_messageData = (mpv_event_client_message)Marshal.PtrToStructure(evt.data, typeof(mpv_event_client_message));
                        string[] args = NativeUtf8StrArray2ManagedStrArray(client_messageData.args, client_messageData.num_args);
                        if (args.Length > 1 && args[0] == "mpv.net")
                        {
                            Command.Execute(args[1], args.Skip(2).ToArray());
                        }
                        else if (args.Length > 0)
                        {
                            ClientMessage?.Invoke(args);
                        }
                        break;

                    case mpv_event_id.MPV_EVENT_VIDEO_RECONFIG:
                        VideoReconfig?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_AUDIO_RECONFIG:
                        AudioReconfig?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_METADATA_UPDATE:
                        MetadataUpdate?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_SEEK:
                        Seek?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_PROPERTY_CHANGE:
                        var propData = (mpv_event_property)Marshal.PtrToStructure(evt.data, typeof(mpv_event_property));

                        if (propData.format == mpv_format.MPV_FORMAT_FLAG)
                        {
                            foreach (var i in BoolPropChangeActions)
                            {
                                if (i.Key == propData.name)
                                {
                                    i.Value.Invoke(Marshal.PtrToStructure <int>(propData.data) == 1);
                                }
                            }
                        }

                        if (propData.format == mpv_format.MPV_FORMAT_STRING)
                        {
                            foreach (var i in StringPropChangeActions)
                            {
                                if (i.Key == propData.name)
                                {
                                    i.Value.Invoke(StringFromNativeUtf8(Marshal.PtrToStructure <IntPtr>(propData.data)));
                                }
                            }
                        }

                        if (propData.format == mpv_format.MPV_FORMAT_INT64)
                        {
                            foreach (var i in IntPropChangeActions)
                            {
                                if (i.Key == propData.name)
                                {
                                    i.Value.Invoke(Marshal.PtrToStructure <int>(propData.data));
                                }
                            }
                        }
                        break;

                    case mpv_event_id.MPV_EVENT_PLAYBACK_RESTART:
                        PlaybackRestart?.Invoke();
                        string path = get_property_string("path");
                        if (LastPlaybackRestartFile != path)
                        {
                            Size vidSize = new Size(get_property_int("dwidth"), get_property_int("dheight"));
                            if (vidSize.Width == 0 || vidSize.Height == 0)
                            {
                                vidSize = new Size(1, 1);
                            }
                            if (VideoSize != vidSize)
                            {
                                VideoSize = vidSize;
                                VideoSizeChanged?.Invoke();
                            }
                            VideoSizeAutoResetEvent.Set();
                            Task.Run(new Action(() => ReadMetaData()));
                            LastPlaybackRestartFile = path;
                        }
                        break;

                    case mpv_event_id.MPV_EVENT_CHAPTER_CHANGE:
                        ChapterChange?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_QUEUE_OVERFLOW:
                        QueueOverflow?.Invoke();
                        break;

                    case mpv_event_id.MPV_EVENT_HOOK:
                        Hook?.Invoke();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Msg.ShowException(ex);
                }
            }
        }
Exemplo n.º 25
0
        internal CommandReply ParseReply(string replyMsg)
        {
            Collection <string> paramName = new Collection <string>();

            CommandReply result = new CommandReply();

            StringReader strReader = new StringReader(replyMsg);

            XmlTextReader replyReader = new XmlTextReader(strReader);

            while ("" != replyMsg && replyReader.Read())
            {
                switch (replyReader.NodeType)
                {
                case XmlNodeType.Element:
                    if (replyReader.Name == "returnValue")
                    {
                        switch (result.CommandName)
                        {
                        case "readTagIDs":
                        case "readTagMemory":
                        case "writeTagMemory":
                        case "readTagField":
                        case "writeTagField":
                        case "killTag":
                        case "lockTagBank":
                        case "nXP_SetReadProtect":
                        case "nXP_ResetReadProtect":
                        case "nXP_Calibrate":
                            ParseForTagData(replyReader, ref result);
                            break;

                        case "hostGreetings":
                            paramName.Add("version");
                            paramName.Add("configType");
                            paramName.Add("configID");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "setConfiguration":
                            paramName.Add("configID");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getConfigVersion":
                            paramName.Add("configID");
                            paramName.Add("configType");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getConfiguration":
                            paramName.Add("configID");
                            paramName.Add("configData");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getAllSources":
                            paramName.Add("sourceName");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getTime":
                            paramName.Add("utcTime");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getIO":
                            paramName.Add("inValue");
                            paramName.Add("outValue");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getReaderStatus":
                            paramName.Add("readerType");
                            paramName.Add("mLFB");
                            paramName.Add("hWVersion");
                            paramName.Add("fWVersion");
                            paramName.Add("readerMode");
                            paramName.Add("version");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getProtocolConfig":
                            paramName.Add("initialQ");
                            paramName.Add("profile");
                            paramName.Add("channels");
                            paramName.Add("session");
                            paramName.Add("rSSIThreshold");
                            paramName.Add("retry");
                            paramName.Add("idLength");
                            paramName.Add("writeMode");
                            paramName.Add("writeBoost");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;

                        case "getAntennaConfig":
                            ParseAntennaReplyParam(replyReader, ref result);
                            break;

                        case "sendCommand":
                            paramName.Add("byteReply");
                            ParseReplyParam(replyReader, ref result, paramName);
                            break;


                        // This is an unknown result so we just ignore it
                        default:
                            break;
                        }

                        // Here we are: Now the interesting part begins which is the real
                        // return value.
                        while (replyReader.Read() &&
                               !(replyReader.Name == "returnValue" && replyReader.NodeType == XmlNodeType.EndElement))
                        {
                            if (replyReader.Name == "value")
                            {
                                if (replyReader.Read())
                                {
                                    if (XmlNodeType.Text == replyReader.NodeType)
                                    {
                                        ParameterDesc param = new ParameterDesc("value", replyReader.Value);
                                        result.Parameters.Add(param);
                                    }
                                }
                            }
                        }
                    }
                    else if (replyReader.Name == "error")
                    {
                        // Read in extended error information
                        while (replyReader.Read() &&
                               !(replyReader.Name == "error" && replyReader.NodeType == XmlNodeType.EndElement))
                        {
                            if (replyReader.Name == "name" && replyReader.NodeType == XmlNodeType.Element)
                            {
                                if (replyReader.Read() && XmlNodeType.Text == replyReader.NodeType)
                                {
                                    result.Error = replyReader.Value.ToString();
                                }
                            }
                            else if (replyReader.Name == "cause" && replyReader.NodeType == XmlNodeType.Element)
                            {
                                if (replyReader.Read() && XmlNodeType.Text == replyReader.NodeType)
                                {
                                    result.Cause = replyReader.Value.ToString();
                                }
                            }
                        }
                    }
                    else if (this.m_IsHeaderRead)
                    {
                        result.CommandName = replyReader.Name;
                    }
                    else if (this.m_IsValidReply)
                    {
                        switch (replyReader.Name)
                        {
                        case "id":
                            if (replyReader.Read())
                            {
                                if (XmlNodeType.Text == replyReader.NodeType)
                                {
                                    result.CommandID = replyReader.Value.ToString();
                                }
                            }
                            break;

                        case "resultCode":
                            if (replyReader.Read())
                            {
                                if (XmlNodeType.Text == replyReader.NodeType)
                                {
                                    result.ResultCode = Int32.Parse(replyReader.Value);
                                }
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    else if (replyReader.Name == "reply")
                    {
                        this.m_IsValidReply = true;
                    }
                    break;

                case XmlNodeType.EndElement:
                    switch (replyReader.Name)
                    {
                    case "resultCode":
                        this.m_IsHeaderRead = true;
                        break;

                    default:
                        break;
                    }
                    break;

                default:
                    break;
                }
            }

            return(result);
        }
Exemplo n.º 26
0
 private void ParseForTagData(XmlTextReader replyReader, ref CommandReply result)
 {
     result.TagData = ParseReportForTags(replyReader, "returnValue");
 }
Exemplo n.º 27
0
        private async void OnMessageReceived(ITcpChannel channel, object message)
        {
            // Here we validate the channel.
            if (!channel.ChannelId.Equals(_channel.ChannelId))
            {
                return;
            }
            var decodedMessage = message as EslDecodedMessage;

            // Handle decoded message.
            if (decodedMessage?.Headers == null ||
                !decodedMessage.Headers.HasKeys())
            {
                return;
            }

            var    headers = decodedMessage.Headers;
            object response;
            var    contentType = headers["Content-Type"];

            if (string.IsNullOrEmpty(contentType))
            {
                return;
            }
            contentType = contentType.ToLowerInvariant();
            switch (contentType)
            {
            case "command/reply":
                var reply = new CommandReply(headers, decodedMessage.OriginalMessage);
                response = reply;
                break;

            case "api/response":
                var apiResponse = new ApiResponse(decodedMessage.BodyText);
                response = apiResponse;
                break;

            case "text/event-plain":
                var parameters = decodedMessage.BodyLines.AllKeys.ToDictionary(key => key,
                                                                               key => decodedMessage.BodyLines[key]);
                var @event = new EslEvent(parameters);
                response = @event;
                break;

            case "log/data":
                var logdata = new LogData(headers, decodedMessage.BodyText);
                response = logdata;
                break;

            case "text/disconnect-notice":
                var notice = new DisconnectNotice(decodedMessage.BodyText);
                response = notice;
                break;

            case "text/rude-rejection":
                await _channel.CloseAsync();

                var reject = new RudeRejection(decodedMessage.BodyText);
                response = reject;
                break;

            default:
                // Here we are handling an unknown message
                var msg = new EslMessage(decodedMessage.Headers, decodedMessage.OriginalMessage);
                response = msg;
                break;
            }

            await HandleResponse(response);
        }
Exemplo n.º 28
0
Arquivo: mp.cs Projeto: amnek0/mpv.net
        public static void EventLoop()
        {
            while (true)
            {
                IntPtr    ptr = mpv_wait_event(MpvHandle, -1);
                mpv_event evt = (mpv_event)Marshal.PtrToStructure(ptr, typeof(mpv_event));

                if (MpvWindowHandle == IntPtr.Zero)
                {
                    MpvWindowHandle = FindWindowEx(MainForm.Hwnd, IntPtr.Zero, "mpv", null);
                }

                //Debug.WriteLine(evt.event_id.ToString());

                switch (evt.event_id)
                {
                case mpv_event_id.MPV_EVENT_SHUTDOWN:
                    Shutdown?.Invoke();
                    AutoResetEvent.Set();
                    return;

                case mpv_event_id.MPV_EVENT_LOG_MESSAGE:
                    LogMessage?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_GET_PROPERTY_REPLY:
                    GetPropertyReply?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_SET_PROPERTY_REPLY:
                    SetPropertyReply?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_COMMAND_REPLY:
                    CommandReply?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_START_FILE:
                    StartFile?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_END_FILE:
                    var end_fileData = (mpv_event_end_file)Marshal.PtrToStructure(evt.data, typeof(mpv_event_end_file));
                    EndFile?.Invoke((EndFileEventMode)end_fileData.reason);
                    break;

                case mpv_event_id.MPV_EVENT_FILE_LOADED:
                    FileLoaded?.Invoke();
                    LoadFolder();
                    break;

                case mpv_event_id.MPV_EVENT_TRACKS_CHANGED:
                    TracksChanged?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_TRACK_SWITCHED:
                    TrackSwitched?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_IDLE:
                    Idle?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_PAUSE:
                    Pause?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_UNPAUSE:
                    Unpause?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_TICK:
                    Tick?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_SCRIPT_INPUT_DISPATCH:
                    ScriptInputDispatch?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_CLIENT_MESSAGE:
                    if (ClientMessage != null)
                    {
                        try
                        {
                            var      client_messageData = (mpv_event_client_message)Marshal.PtrToStructure(evt.data, typeof(mpv_event_client_message));
                            string[] args = NativeUtf8StrArray2ManagedStrArray(client_messageData.args, client_messageData.num_args);

                            if (args != null && args.Length > 1 && args[0] == "mpv.net")
                            {
                                bool found = false;

                                foreach (var i in mpvnet.Command.Commands)
                                {
                                    if (args[1] == i.Name)
                                    {
                                        found = true;
                                        i.Action.Invoke(args.Skip(2).ToArray());
                                    }
                                }
                                if (!found)
                                {
                                    List <string> names = mpvnet.Command.Commands.Select((item) => item.Name).ToList();
                                    names.Sort();
                                    MainForm.Instance.ShowMsgBox($"No command '{args[1]}' found. Available commands are:\n\n{string.Join("\n", names)}\n\nHow to bind these commands can be seen in the default input bindings and menu definition located at:\n\nhttps://github.com/stax76/mpv.net/blob/master/mpv.net/Resources/input.conf.txt", MessageBoxIcon.Error);
                                }
                            }
                            ClientMessage?.Invoke(args);
                        }
                        catch (Exception ex)
                        {
                            MainForm.Instance.ShowMsgBox(ex.GetType().Name + "\n\n" + ex.ToString(), MessageBoxIcon.Error);
                        }
                    }
                    break;

                case mpv_event_id.MPV_EVENT_VIDEO_RECONFIG:
                    VideoReconfig?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_AUDIO_RECONFIG:
                    AudioReconfig?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_METADATA_UPDATE:
                    MetadataUpdate?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_SEEK:
                    Seek?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_PROPERTY_CHANGE:
                    var event_propertyData = (mpv_event_property)Marshal.PtrToStructure(evt.data, typeof(mpv_event_property));

                    if (event_propertyData.format == mpv_format.MPV_FORMAT_FLAG)
                    {
                        foreach (var i in BoolPropChangeActions)
                        {
                            if (i.Key == event_propertyData.name)
                            {
                                i.Value.Invoke(Marshal.PtrToStructure <int>(event_propertyData.data) == 1);
                            }
                        }
                    }
                    break;

                case mpv_event_id.MPV_EVENT_PLAYBACK_RESTART:
                    PlaybackRestart?.Invoke();
                    Size s = new Size(get_property_int("dwidth"), get_property_int("dheight"));

                    if (VideoSize != s && s != Size.Empty)
                    {
                        VideoSize = s;
                        VideoSizeChanged?.Invoke();
                    }
                    break;

                case mpv_event_id.MPV_EVENT_CHAPTER_CHANGE:
                    ChapterChange?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_QUEUE_OVERFLOW:
                    QueueOverflow?.Invoke();
                    break;

                case mpv_event_id.MPV_EVENT_HOOK:
                    Hook?.Invoke();
                    break;
                }
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="iPAddress">IP Address of listener, to which channel send data</param>
        ///  <param name="port">Port of listener, to which channel send data</param>
        /// <param name="bufferTag">If true: buffers data during offline. Listener must acknowledge data</param>
        /// <returns></returns>
        public void Subscribe(string typeOfChannel, IPAddress iPAddress, int port, bool bufferTag)

        {
            // Validate current state of Reader API
            if (!RfReaderApi.IsValid)
            {
                throw new RfReaderApiInvalidModeException();
            }

            // Tssting only: Setup listener, but do not send commands to reader
            if (RfReaderApi.testFlag_ListenOnly)
            {
                SubscribeChannelListener(typeOfChannel, iPAddress, port, bufferTag);
            }
            else
            {
                PerfTiming perfTimer1 = new PerfTiming();
                perfTimer1.Start();


                // Security check for preconditions: Are we connected at all?
                if (!this.CommandChannel.IsConnected())
                {
                    throw new RfReaderApiException(RfReaderApiException.ResultCode_System, RfReaderApiException.Error_NoConnection);
                }

                // setup channel Listener for alarms
                if (RfReaderApi.TER == typeOfChannel || RfReaderApi.ALARM == typeOfChannel || RfReaderApi.ALL == typeOfChannel)
                {
                    // Tssting only: send subscribe command, but don't listen
                    if (false == RfReaderApi.testFlag_SubscribeOnly)
                    {
                        if (IPAddress.None != iPAddress)
                        {
                            SubscribeChannelListener(typeOfChannel, iPAddress, port, bufferTag);
                        }
                        else
                        {
                            UnSubscribeChannelListener(typeOfChannel);
                        }
                    }
                }
                else
                {
                    throw new RfReaderApiException(RfReaderApiException.ResultCode_System, RfReaderApiException.Error_InvalidParameter);
                }

                List <ParameterDesc> subscribeParams = new List <ParameterDesc>();
                subscribeParams.Add(new ParameterDesc("type", typeOfChannel));
                if (IPAddress.None != iPAddress)
                {
                    subscribeParams.Add(new ParameterDesc("iPAddress", iPAddress.ToString()));
                    subscribeParams.Add(new ParameterDesc("port", port.ToString()));
                }
                subscribeParams.Add(new ParameterDesc("bufferTag", bufferTag.ToString()));

                Command      rpCommand = new Command("subscribe", subscribeParams);
                string       commandID = "";
                string       replyMsg  = this.CommandChannel.execute(rpCommand.getXmlCommand(ref commandID), commandID);
                CommandReply rpReply   = CommandReply.DecodeXmlCommand(replyMsg);
                if (rpReply == null)
                {
                    // There is no reply from our connected reader
                    throw new RfReaderApiException(RfReaderApiException.ResultCode_System,
                                                   RfReaderApiException.Error_NoReply);
                }
                if (rpReply.ResultCode != 0)
                {
                    // forward errors as exceptions
                    throw new RfReaderApiException(rpReply.ResultCode, rpReply.Error,
                                                   rpReply.Cause);
                }

                if (RfReaderApi.showPerformanceInfo)
                {
                    ProvideInformation(this, "Subscribe took " + perfTimer1.End().ToString("##.###") + "s");
                }
            }
        }
Exemplo n.º 30
0
 private void OnAuthed(CmdBase command, CommandReply reply)
 {
     LogWriter(LogPrio.Trace, "We have not authenticated.");
     _authed = true;
     RequestEvents();
 }