Beispiel #1
0
        public byte[] Send(IDeviceMessage message)
        {
            Connect();

            var str_message = message.ToString();

            message_queue = new List <byte>();
            try {
                byte[] buffer = message.GetSendBuffer();
                OnMessageSent?.Invoke(message.ToString().Substring(2));

                if (_stream != null)
                {
                    _stream.Write(buffer, 0, buffer.Length);
                    _stream.Flush();

                    var task = BeginReceiveTask();
                    if (!task.Wait(_settings.Timeout))
                    {
                        throw new MessageException("Device did not respond within the timeout.");
                    }

                    return(message_queue.ToArray());
                }
                else
                {
                    throw new MessageException("Device not connected.");
                }
            }
            finally {
                Disconnect();
            }
        }
Beispiel #2
0
        /// <summary>
        /// Sends chat message via bot
        /// </summary>
        /// <param name="msg">String message to send</param>
        public void SendChatMessage(string msg, bool isCommand)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return;
            }

            // :[email protected] PRIVMSG #channel :message
            if (!IsConnectionAlive)
            {
                _logger.LogWarning("Cannot send chat message, connection is NOT alive! Message '{msg}' was not send.", msg);
                return;
            }

            if (!throttler.AllowToSendMessage(msg))
            {
                return;
            }

            writer.WriteLine(String.Format("{0}{1}{2}", chatMessagePrefix, _botDataManager.UseColoredMessages && !isCommand ? "/me " : "", msg));
            writer.Flush();
            ConsoleAppendText(chatMessagePrefix + msg);
            OnMessageSent?.Invoke(this, new OnMessageArgs {
                Message = msg
            });
        }
        public byte[] Send(IDeviceMessage message)
        {
            try {
                if (_serialPort != null)
                {
                    _transComplete = false;
                    _exit          = false;

                    string bufferSend = Encoding.ASCII.GetString(message.GetSendBuffer());
                    OnMessageSent?.Invoke(bufferSend.Substring(1, bufferSend.Length - 3));

                    Task <bool> task = WriteMessage(message);
                    lock (_lock) {
                        while (!_transComplete)
                        {
                            if (!Monitor.Wait(_lock, _settings.Timeout))
                            {
                                _exit          = true;
                                _transComplete = true;
                                throw new ApiException("Terminal did not respond within timeout.");
                            }
                        }
                    }

                    return(_messageResponse.ToArray());
                }
                else
                {
                    throw new ConfigurationException("Terminal not connected.");
                }
            } catch (ApiException e) {
                throw new ApiException(e.Message);
            }
        }
Beispiel #4
0
        public byte[] Send(IDeviceMessage message)
        {
            OnMessageSent?.Invoke(message.ToString());

            try {
                string payload = Convert.ToBase64String(message.GetSendBuffer());

                return(Task.Run(async() => {
                    _client = HttpWebRequest.Create(string.Format("http://{0}:{1}?{2}", _settings.IpAddress, _settings.Port, payload));

                    var response = await _client.GetResponseAsync();

                    var buffer = new List <byte>();
                    using (var sr = new StreamReader(response.GetResponseStream())) {
                        var rec_buffer = await sr.ReadToEndAsync();
                        foreach (char c in rec_buffer)
                        {
                            buffer.Add((byte)c);
                        }
                    }
                    return buffer.ToArray();
                }).Result);
            }
            catch (Exception exc) {
                throw new MessageException("Failed to send message. Check inner exception for more details.", exc);
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="hubConnectionBuilder">Hub连接建造者</param>
        /// <param name="message">消息</param>
        public static async Task SendAsync <T>(HubConnectionBuilder hubConnectionBuilder, T message) where T : IMessage
        {
            #region # 验证

            if (!hubConnectionBuilder.HubConnectionBuilt)
            {
                throw new InvalidOperationException("Hub连接未构建,不可发送消息!");
            }

            #endregion

            string hubName = MessageExtension.GetHubName <T>();

            #region # 验证

            if (!hubConnectionBuilder.SenderProxies.ContainsKey(hubName))
            {
                throw new InvalidOperationException($"要发送的消息类型\"{typeof(T).Name}\"未注册!");
            }

            #endregion

            IHubProxy proxy = hubConnectionBuilder.SenderProxies[hubName];
            await proxy.Invoke(CommonConstants.ExchangeMethodName, message);

            //消息已发送事件
            OnMessageSent?.Invoke(message);
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="hubConnection">Hub连接</param>
        /// <param name="message">消息</param>
        public static void Send <T>(HubConnection hubConnection, T message) where T : IMessage
        {
            hubConnection.InvokeAsync(nameof(IMessageHub <T> .Exchange), message).Wait();

            //消息已发送事件
            OnMessageSent?.Invoke(message);
        }
Beispiel #7
0
        public byte[] Send(IDeviceMessage message)
        {
            byte[] buffer = message.GetSendBuffer();

            Connect();
            try {
                for (int i = 0; i < 3; i++)
                {
                    _stream.WriteAsync(buffer, 0, buffer.Length).Wait();

                    var rvalue = _stream.GetTerminalResponseAsync();
                    if (rvalue != null)
                    {
                        byte lrc = rvalue[rvalue.Length - 1]; // Should be the LRC
                        if (lrc != TerminalUtilities.CalculateLRC(rvalue))
                        {
                            SendControlCode(ControlCodes.NAK);
                        }
                        else
                        {
                            SendControlCode(ControlCodes.ACK);
                            return(rvalue);
                        }
                    }
                }
                throw new MessageException("Terminal did not respond in the given timeout.");
            }
            catch (Exception exc) {
                throw new MessageException(exc.Message, exc);
            }
            finally {
                OnMessageSent?.Invoke(message.ToString());
                Disconnect();
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="hubConnection">Hub连接</param>
        /// <param name="message">消息</param>
        public static async Task SendAsync <T>(HubConnection hubConnection, T message) where T : IMessage
        {
            await hubConnection.InvokeAsync(nameof(IMessageHub <T> .Exchange), message);

            //消息已发送事件
            OnMessageSent?.Invoke(message);
        }
 internal HeartSipInterface(HeartSipController controller)
 {
     _controller = controller;
     _controller.OnMessageSent += (message) => {
         OnMessageSent?.Invoke(message);
     };
 }
 internal PaxInterface(PaxController controller)
 {
     this.controller           = controller;
     controller.OnMessageSent += (message) => {
         OnMessageSent?.Invoke(message);
     };
 }
Beispiel #11
0
        private void HandleBotResponse(object sender, BotResponseEventArgs e)
        {
            Debug.Log($"Response from Bot of type: {e.EventType}");

            switch (e.EventType)
            {
            case EventTypes.None:
                break;

            case EventTypes.ConversationStarted:
                OnConversationStarted?.Invoke(this, e.ConversationId);
                break;

            case EventTypes.MessageSent:
                OnMessageSent?.Invoke(this, e.SentMessageId);
                break;

            case EventTypes.MessageReceived:
                OnMessagesReceived?.Invoke(this, e.Messages);
                break;

            case EventTypes.Error:
                break;
            }
        }
Beispiel #12
0
        /// <summary>
        /// Starts a message loop that allows events to be subsribed to.
        /// </summary>
        /// <param name="waitAfterPoll">Wait before each poll.</param>
        private void MessageLoop(TimeSpan waitAfterPoll, int secTimeOut = 0)
        {
            _searching = true;
            while (_searching)
            {
                Thread.Sleep(waitAfterPoll);
                PollResponse response = _chatHandler.Poll(secTimeOut);
                PollReceived?.Invoke(this, new PollArgs(response));

                if (response.Messages == null)
                {
                    continue;
                }
                foreach (Message message in response.Messages)
                {
                    MessageReceived?.Invoke(this, new MessageArgs(message));
                    switch (message.Type.ToLower())
                    {
                    case "saytext":
                        ChatMessageReceived?.Invoke(this, new ChatMessageArgs(message));
                        break;

                    case "typing":
                        OnUserTyping?.Invoke(this, new TypingArgs(message));
                        break;

                    case "my_saytext":
                        OnMessageSent?.Invoke(this, new ChatMessageArgs(message));
                        break;
                    }
                }
            }
        }
Beispiel #13
0
 internal HpaInterface(HpaController controller)
 {
     _controller = controller;
     _controller.OnMessageSent += (message) => {
         OnMessageSent?.Invoke(message);
     };
     _requestIdProvider = _controller.RequestIdProvider;
 }
Beispiel #14
0
 internal DeviceController(ITerminalConfiguration settings)
 {
     _settings  = settings;
     _connector = ConfigureConnector();
     _connector.OnMessageSent += (message) => {
         OnMessageSent?.Invoke(message);
     };
 }
Beispiel #15
0
 internal PaxInterface(PaxController controller)
 {
     this.controller           = controller;
     controller.OnMessageSent += (message) => {
         OnMessageSent?.Invoke(message);
     };
     requestIdProvider = controller.RequestIdProvider;
 }
        private WinEventProc WinEventProc(string windowName)
        {
            return((IntPtr hWinEventHook, WindowsEventHookType eventType, IntPtr hWnd, int idObject, int idChild, int dwEventThread, uint dwmsEventTime) =>
            {
                GetWindowThreadProcessId(hWnd, out var targetProcessId);
                var isTarget = targetProcessId == _targetProcessId;
                switch (eventType)
                {
                case WindowsEventHookType.EVENT_SYSTEM_FOREGROUND:
                    OnForeground?.Invoke(this, isTarget);
                    break;

                case WindowsEventHookType.EVENT_SYSTEM_MINIMIZESTART:
                    if (!isTarget)
                    {
                        return;
                    }
                    OnMinimized?.Invoke(this, true);
                    return;

                case WindowsEventHookType.EVENT_SYSTEM_MINIMIZEEND:
                    if (!isTarget)
                    {
                        return;
                    }
                    OnMinimized?.Invoke(this, false);
                    break;

                case WindowsEventHookType.EVENT_SYSTEM_MOVESIZEEND:
                case WindowsEventHookType.EVENT_OBJECT_LOCATIONCHANGE:
                    if (!isTarget)
                    {
                        return;
                    }
                    OnMoveOrSizeChanged?.Invoke(this, null);
                    break;

                case WindowsEventHookType.EVENT_OBJECT_REORDER:
                    if (!isTarget)
                    {
                        return;
                    }
                    if (idObject != 0 /* WindowObjId*/)
                    {
                        return;
                    }
                    OnBorderChanged?.Invoke(this, null);
                    break;

                default:
                    if (isTarget)
                    {
                        OnMessageSent?.Invoke(this, null);
                    }
                    return;
                }
            });
        }
Beispiel #17
0
 public void SendMessage(ChatMessage msg)
 {
     if (msg.Recipient[1] == "admin")
     {
         return;
     }
     _clientConnection.SendPackage(msg);
     OnMessageSent?.Invoke(null, msg);
 }
Beispiel #18
0
    private void Awake()
    {
        client = new Twitch.Client();

        // Transfert events
        client.OnDisconnected       += (s, e) => OnDisconnected?.Invoke(this, e);
        client.OnConnectionError    += (s, e) => OnConnectionError?.Invoke(this, e);
        client.OnChatCleared        += (s, e) => OnChatCleared?.Invoke(this, e);
        client.OnUserTimedout       += (s, e) => OnUserTimedout?.Invoke(this, e);
        client.OnLeftChannel        += (s, e) => OnLeftChannel?.Invoke(this, e);
        client.OnUserBanned         += (s, e) => OnUserBanned?.Invoke(this, e);
        client.OnModeratorsReceived += (s, e) => OnModeratorsReceived?.Invoke(this, e);
        client.OnChatColorChanged   += (s, e) => OnChatColorChanged?.Invoke(this, e);
        client.OnSendReceiveData    += (s, e) => OnSendReceiveData?.Invoke(this, e);
        client.OnNowHosting         += (s, e) => OnNowHosting?.Invoke(this, e);
        //client.OnBeingHosted                        += (s, e) => OnBeingHosted                      ?.Invoke(this, e);
        client.OnRaidNotification              += (s, e) => OnRaidNotification?.Invoke(this, e);
        client.OnGiftedSubscription            += (s, e) => OnGiftedSubscription?.Invoke(this, e);
        client.OnSelfRaidError                 += (s, e) => OnSelfRaidError?.Invoke(this, e);
        client.OnNoPermissionError             += (s, e) => OnNoPermissionError?.Invoke(this, e);
        client.OnRaidedChannelIsMatureAudience += (s, e) => OnRaidedChannelIsMatureAudience?.Invoke(this, e);
        client.OnRitualNewChatter              += (s, e) => OnRitualNewChatter?.Invoke(this, e);
        client.OnHostingStopped                += (s, e) => OnHostingStopped?.Invoke(this, e);
        client.OnHostingStarted                += (s, e) => OnHostingStarted?.Invoke(this, e);
        client.OnUserLeft += (s, e) => OnUserLeft?.Invoke(this, e);
        client.OnExistingUsersDetected += (s, e) => OnExistingUsersDetected?.Invoke(this, e);
        client.OnLog                 += (s, e) => OnLog?.Invoke(this, e);
        client.OnConnected           += (s, e) => OnConnected?.Invoke(this, e);
        client.OnJoinedChannel       += (s, e) => OnJoinedChannel?.Invoke(this, e);
        client.OnIncorrectLogin      += (s, e) => OnIncorrectLogin?.Invoke(this, e);
        client.OnChannelStateChanged += (s, e) => OnChannelStateChanged?.Invoke(this, e);
        client.OnUserStateChanged    += (s, e) => OnUserStateChanged?.Invoke(this, e);
        client.OnMessageReceived     += (s, e) => OnMessageReceived?.Invoke(this, e);
        client.OnWhisperReceived     += (s, e) => OnWhisperReceived?.Invoke(this, e);
        client.OnFailureToReceiveJoinConfirmation += (s, e) => OnFailureToReceiveJoinConfirmation?.Invoke(this, e);
        client.OnMessageSent            += (s, e) => OnMessageSent?.Invoke(this, e);
        client.OnChatCommandReceived    += (s, e) => OnChatCommandReceived?.Invoke(this, e);
        client.OnWhisperCommandReceived += (s, e) => OnWhisperCommandReceived?.Invoke(this, e);
        client.OnUserJoined             += (s, e) => OnUserJoined?.Invoke(this, e);
        client.OnModeratorJoined        += (s, e) => OnModeratorJoined?.Invoke(this, e);
        client.OnModeratorLeft          += (s, e) => OnModeratorLeft?.Invoke(this, e);
        client.OnNewSubscriber          += (s, e) => OnNewSubscriber?.Invoke(this, e);
        client.OnReSubscriber           += (s, e) => OnReSubscriber?.Invoke(this, e);
        client.OnHostLeft       += (s, e) => OnHostLeft?.Invoke(this, e);
        client.OnWhisperSent    += (s, e) => OnWhisperSent?.Invoke(this, e);
        client.OnUnaccountedFor += (s, e) => OnUnaccountedFor?.Invoke(this, e);

        // Log client activity
        client.OnLog           += (s, e) => Debug.Log(e.Data);
        client.OnConnected     += (s, e) => NotificationManager.Instance.PushNotification("Connected to Twitch servers", Color.white, Color.green);
        client.OnJoinedChannel += (s, e) => NotificationManager.Instance.PushNotification($"Joined {e.Channel} channel", Color.white, Color.cyan);
        client.OnLeftChannel   += (s, e) => NotificationManager.Instance.PushNotification($"Left {e.Channel} channel", Color.white, Color.yellow);
        client.OnDisconnected  += (s, e) => NotificationManager.Instance.PushNotification("Disconnected from Twitch servers", Color.white, Color.red);
        client.OnFailureToReceiveJoinConfirmation += (s, e) => NotificationManager.Instance.PushNotification("Failed to join channel", Color.white, Color.magenta);
    }
Beispiel #19
0
 /// <summary>
 /// Sends a formatted Twitch channel chat message.
 /// </summary>
 /// <param name="message">The message to be sent.</param>
 /// <param name="dryRun">If set to true, the message will not actually be sent for testing purposes.</param>
 public void SendMessage(string message, bool dryRun = false)
 {
     if (dryRun)
     {
         return;
     }
     _client.WriteLine(string.Format(":{0}!{0}@{0}.tmi.twitch.tv PRIVMSG #{1} :{2}", _credentials.TwitchUsername,
                                     _channel, message));
     OnMessageSent?.Invoke(null,
                           new OnMessageSentArgs {
         Username = _credentials.TwitchUsername, Channel = _channel, Message = message
     });
 }
 private void SendManageFriendButton_Click(object sender, EventArgs e)
 {
     if (messageBodyManageFriendEditText.Text != "")
     {
         OnMessageSent?.Invoke(this, new MessageArgs
         {
             BMessage = new BaseMessage {
                 MessageBody = messageBodyManageFriendEditText.Text
             },
             UserArgs = user
         });
     }
 }
Beispiel #21
0
        public override void Stop()
        {
            base.Stop();
            // 处理队列中剩余的消息
            Package package;

            while (_sendingQueue.TryTake(out package))
            {
                if (package != null)
                {
                    OnMessageSending?.Invoke(this, package);
                    OnInnerSending(package);
                    OnMessageSent?.Invoke(this, package);
                }
            }
        }
        internal DeviceController(ITerminalConfiguration settings)
        {
            _settings  = settings;
            _connector = ConfigureConnector();
            _connector.OnMessageSent += (message) => {
                OnMessageSent?.Invoke(message);
            };

            _connector.OnBroadcastMessage += (code, message) => {
                OnBroadcastMessage?.Invoke(code, message);
            };

            _connector.OnPayAtTableRequest += (request) => {
                OnPayAtTableRequest?.Invoke(request);
            };
        }
        /// <summary>
        /// Sends a formatted Twitch channel chat message.
        /// </summary>
        /// <param name="message">The message to be sent.</param>
        /// <param name="dryRun">If set to true, the message will not actually be sent for testing purposes.</param>
        public void SendMessage(string message, bool dryRun = false)
        {
            if (dryRun)
            {
                return;
            }
            string twitchMessage = $":{_credentials.TwitchUsername}!{_credentials.TwitchUsername}@{_credentials.TwitchUsername}" +
                                   $".tmi.twitch.tv PRIVMSG #{_channel} :{message}";

            // This is a makeshift hack to encode it with accomodations for at least cyrillic characters, and possibly others
            _client.WriteLine(Encoding.Default.GetString(Encoding.UTF8.GetBytes(twitchMessage)));
            OnMessageSent?.Invoke(null,
                                  new OnMessageSentArgs {
                Username = _credentials.TwitchUsername, Channel = _channel, Message = message
            });
        }
Beispiel #24
0
        internal HeartSipController(ITerminalConfiguration settings) : base(settings)
        {
            switch (_settings.ConnectionMode)
            {
            case ConnectionModes.TCP_IP:
                _interface = new HeartSipTcpInterface(settings);
                break;

            default:
                throw new NotImplementedException("Connection Method not available for HeartSIP devices");
            }

            //_interface.Connect();
            _interface.OnMessageSent += (message) => {
                OnMessageSent?.Invoke(message);
            };
        }
        internal void MessageStateChangeHandler(MessagingEventParams eventParams, MessagingEventParams.StateParams stateParams)
        {
            Message message = new Message()
            {
                Body      = stateParams.Body,
                Context   = stateParams.Context,
                Direction = stateParams.Direction,
                From      = stateParams.FromNumber,
                ID        = stateParams.MessageID,
                Media     = stateParams.Media,
                Reason    = stateParams.Reason,
                Segments  = stateParams.Segments,
                State     = stateParams.MessageState,
                Tags      = stateParams.Tags,
                To        = stateParams.ToNumber,
            };

            OnMessageStateChange?.Invoke(this, message, eventParams, stateParams);

            switch (stateParams.MessageState)
            {
            case MessageState.queued:
                OnMessageQueued?.Invoke(this, message, eventParams, stateParams);
                break;

            case MessageState.initiated:
                OnInitiated?.Invoke(this, message, eventParams, stateParams);
                break;

            case MessageState.sent:
                OnMessageSent?.Invoke(this, message, eventParams, stateParams);
                break;

            case MessageState.delivered:
                OnMessageDelivered?.Invoke(this, message, eventParams, stateParams);
                break;

            case MessageState.undelivered:
                OnMessageUndelivered?.Invoke(this, message, eventParams, stateParams);
                break;

            case MessageState.failed:
                OnMessageFailed?.Invoke(this, message, eventParams, stateParams);
                break;
            }
        }
Beispiel #26
0
 private void SendMessage()
 {
     try
     {
         if (StringFromRichTextBox(chatTextbox) != string.Empty)
         {
             OnMessageSent?.Invoke(new RawMessageEventArgs
             {
                 Message = StringFromRichTextBox(chatTextbox)
             });
             chatTextbox.Document.SetText(Windows.UI.Text.TextSetOptions.None, string.Empty);
         }
     }
     catch (Exception exception)
     {
         App.LogUnhandledError(exception);
     }
 }
Beispiel #27
0
        internal DeviceInterface(T controller)
        {
            _controller = controller;
            _controller.OnMessageSent += (message) => {
                OnMessageSent?.Invoke(message);
            };

            _controller.OnBroadcastMessage += (code, message) => {
                OnBroadcastMessage?.Invoke(code, message);
            };

            _controller.OnPayAtTableRequest += (request) => {
                OnPayAtTableRequest?.Invoke(request);
            };


            _requestIdProvider = _controller.RequestIdProvider;
        }
Beispiel #28
0
        private void PorcessMessageQueue()
        {
            while (true)
            {
                if (_shutdownEvent.Wait(0)) // 仅检查标志,立即返回
                {
                    // 关闭事件触发,退出loop
                    return;
                }

                var package = _sendingQueue.Take();
                if (package != null)
                {
                    OnMessageSending?.Invoke(this, package);
                    OnInnerSending(package);
                    OnMessageSent?.Invoke(this, package);
                }
            }
        }
Beispiel #29
0
 /// <summary>
 /// Sends a message to the server.
 /// </summary>
 /// <param name="content">The message to send.</param>
 /// <returns>Returns whether the message was successfuly sent or not.</returns>
 public bool SendMessage(string content)
 {
     if (ClientSocket.State != WebSocketState.Open)
     {
         return(false);
     }
     try
     {
         OnMessageSent?.Invoke(this, new SocketMessageEventArgs(content));
         ClientSocket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes(content)),
                                WebSocketMessageType.Text, true, CancellationToken.None);
     }
     catch (Exception e)
     {
         Console.ForegroundColor = ConsoleColor.Red;
         Console.WriteLine($"{e.Message}\n\n{e.StackTrace}");
         return(false);
     }
     return(true);
 }
Beispiel #30
0
        internal PaxController(ITerminalConfiguration settings) : base(settings)
        {
            switch (_settings.ConnectionMode)
            {
            case ConnectionModes.TCP_IP:
                _interface = new PaxTcpInterface(settings);
                break;

            case ConnectionModes.HTTP:
                _interface = new PaxHttpInterface(settings);
                break;

            case ConnectionModes.SERIAL:
            case ConnectionModes.SSL_TCP:
                throw new NotImplementedException();
            }

            //_interface.Connect();
            _interface.OnMessageSent += (message) => {
                OnMessageSent?.Invoke(message);
            };
        }