private static void SocketOnOnConnectionEstablished(object sender, EventArgs e)
        {
            DeviceStatus_Tick(null); // Send device to populate rig stats
            LoadSMA();               //for first run
            string ghv = GetVersion("");

            Helpers.ConsolePrint("GITHUB", ghv);
            SetVersion(ghv);
            OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
        }
Esempio n. 2
0
        /// <summary>
        /// Achtung: Nicht Teil von ICommunication
        /// </summary>
        public void Open()
        {
            lock (_SerialPortLock) {
                if (!_port.IsOpen)
                {
                    _port.Open();
                }
            }

            OnConnectionEstablished?.Invoke(this);
            StartRead();
        }
        private void Login(object sender, EventArgs e)
        {
            try
            {
                var loginJson = JsonConvert.SerializeObject(_login);
                SendData(loginJson);

                OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
            } catch (Exception er)
            {
                NHM.Common.Logger.Info("SOCKET", er.Message);
            }
        }
        // loops receiving any messages
        private async Task ReceiveLoop(string address, int port, CancellationToken cancellationToken)
        {
            // connect
            await _tcpClient.ConnectAsync(address, port);

            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (!_tcpClient.Connected)
            {
                OnClientDisconnected?.Invoke(new MessageEventArgs("Failed to connect"));
                return;
            }
            _controlStream = _tcpClient.GetStream();
            _controlWriter = new StreamWriter(_controlStream, Encoding.Default);
            OnConnectionEstablished?.Invoke(new MessageEventArgs("Connected"));

            // loop receiving data
            while (!cancellationToken.IsCancellationRequested)
            {
                if (!_tcpClient.Connected)
                {
                    OnClientDisconnected?.Invoke(new MessageEventArgs("Failed to connect"));
                    return;
                }

                int length;
                try {
                    length = await _controlStream.ReadAsync(_dataBuffer, 0, _dataBuffer.Length, cancellationToken);
                } catch (OperationCanceledException) {
                    return;
                }

                string message = Encoding.Default.GetString(_dataBuffer, 0, length);
                if (!string.IsNullOrEmpty(message) || _tcpClient.IsSocketConnected())
                {
                    await Store.TcpReceive.SendAsync(message);
                }
                else
                {
                    _tcpClient.Client.Disconnect(true);
                    OnClientDisconnected?.Invoke(new MessageEventArgs("Disconnected."));
                }
            }
        }
        private void ConnectCallback(object sender, EventArgs e)
        {
            try
            {
                //send login
                var version = "NHML/" + Application.ProductVersion;
                var login   = new NicehashLogin
                {
                    version = version
                };
                var loginJson = JsonConvert.SerializeObject(login);
                SendData(loginJson);

                OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
            } catch (Exception er)
            {
                Helpers.ConsolePrint("SOCKET", er.ToString());
            }
        }
Esempio n. 6
0
        public void Connect()
        {
            try
            {
                _log.Info($"Connecting to {_gateway}:{_port}...");
                _tcpClient = new TcpClient(_gateway, _port)
                {
                    NoDelay = true
                };
            }
            catch (Exception ex)
            {
                _log.Error($"Connecting to {_gateway}:{_port} :: {ex}");
                throw;
            }

            _sslStream = new SslStream(_tcpClient.GetStream(), false, ValidateServerCertificate, null);
            try
            {
                _sslStream.AuthenticateAsClient(_gateway);
            }
            catch (Exception ex)
            {
                _log.Error($"_sslStream.AuthenticateAsClient({_gateway}) :: {ex}");
                _tcpClient.Dispose();
                throw;
            }

            if (!_sslStream.IsAuthenticated)
            {
                _log.Error($"Cannot establish secure connection to {_gateway}:{_port}");
                return;
            }

            Start_Listening_Thread();
            Start_Sender_Thread();
            Start_KeepAlive_Thread();

            _log.Info($"Connection established to {_gateway}:{_port}");

            OnConnectionEstablished?.Invoke(this, null);
        }
Esempio n. 7
0
        private async Task InitConnection()
        {
            OnConnectionEstablished?.Invoke(this, System.EventArgs.Empty);

            var publicKey = await webApi.GetRequest <GetPublicKeyResponse>("jdev/sys/getPublicKey");;

            _pubKey = Convert.FromBase64String(publicKey.Data.PublicKey.Replace("-----END CERTIFICATE-----", "").Replace("-----BEGIN CERTIFICATE-----", ""));
            string stringDataToEncrypt;

            SecureRandom random = new SecureRandom();

            _aesKey = GenerateAesKey(LoxoneUuid);

            _aesIv = new byte[128 / 8];
            random.NextBytes(_aesIv);

            stringDataToEncrypt = $"{_aesKey.ToHex(false)}:{_aesIv.ToHex(false)}";

            Asn1Object  obj = Asn1Object.FromByteArray(_pubKey);
            DerSequence publicKeySequence = (DerSequence)obj;

            DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
            DerSequence  publicKeyDer     = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());

            DerInteger modulus  = (DerInteger)publicKeyDer[0];
            DerInteger exponent = (DerInteger)publicKeyDer[1];

            RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
            var encryptEngine = new Pkcs1Encoding(new RsaEngine());

            encryptEngine.Init(true, keyParameters);

            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(stringDataToEncrypt);
            byte[] encryptedData = encryptEngine.ProcessBlock(dataToEncrypt, 0, dataToEncrypt.Length);

            var publicKeySelf = Convert.ToBase64String(encryptedData);

            _connectionState = ConnectionState.ExchangeKeys;

            _webSocket.Send($"jdev/sys/keyexchange/{publicKeySelf}");
        }
Esempio n. 8
0
        public NetServer(IPEndPoint endpoint, int maxConnections)
        {
            this.Endpoint = endpoint;

            this.server = new NetManager(listener, maxConnections, "Phinix")
            {
                PingInterval      = 5000,
                DisconnectTimeout = 30000
            };
            this.connectedPeers = new Dictionary <string, NetPeer>();

            // Subscribe to events
            listener.PeerConnectedEvent += (peer) =>
            {
                // Add or update the peer's connection
                string connectionId = peer.ConnectId.ToString("X");
                if (connectedPeers.ContainsKey(connectionId))
                {
                    connectedPeers[connectionId] = peer;
                }
                else
                {
                    connectedPeers.Add(connectionId, peer);
                }

                // Raise the connection established event for this peer
                OnConnectionEstablished?.Invoke(this, new ConnectionEventArgs(connectionId));
            };
            listener.PeerDisconnectedEvent += (peer, info) =>
            {
                // Remove the peer's connection
                string connectionId = peer.ConnectId.ToString("X");
                connectedPeers.Remove(connectionId);

                // Raise the connection established event for this peer
                OnConnectionClosed?.Invoke(this, new ConnectionEventArgs(connectionId));
            };
        }
        private static void SocketOnOnConnectionEstablished(object sender, EventArgs e)
        {
            DeviceStatus_Tick(null); // Send device to populate rig stats

            OnConnectionEstablished?.Invoke(null, EventArgs.Empty);
        }
Esempio n. 10
0
        /// <summary>
        /// Dequeues all the messages from Discord and invokes appropriate methods. This will process the message and update the internal state before invoking the events. Returns the messages that were invoked and in the order they were invoked.
        /// </summary>
        /// <returns>Returns the messages that were invoked and in the order they were invoked.</returns>
        public IMessage[] Invoke()
        {
            //Dequeue all the messages and process them
            IMessage[] messages = connection.DequeueMessages();
            for (int i = 0; i < messages.Length; i++)
            {
                //Do a bit of pre-processing
                IMessage message = messages[i];
                HandleMessage(message);

                //Invoke the appropriate methods
                switch (message.Type)
                {
                case MessageType.Ready:
                    if (OnReady != null)
                    {
                        OnReady.Invoke(this, message as ReadyMessage);
                    }
                    break;

                case MessageType.Close:
                    if (OnClose != null)
                    {
                        OnClose.Invoke(this, message as CloseMessage);
                    }
                    break;

                case MessageType.Error:
                    if (OnError != null)
                    {
                        OnError.Invoke(this, message as ErrorMessage);
                    }
                    break;

                case MessageType.PresenceUpdate:
                    if (OnPresenceUpdate != null)
                    {
                        OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                    }
                    break;

                case MessageType.ConnectionEstablished:
                    if (OnConnectionEstablished != null)
                    {
                        OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                    }
                    break;

                case MessageType.ConnectionFailed:
                    if (OnConnectionFailed != null)
                    {
                        OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                    }
                    break;

                default:
                    //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                    Console.WriteLine($"Message was queued with no appropriate handle! {message.Type}");
                    break;
                }
            }

            //Finally, return the messages
            return(messages);
        }
Esempio n. 11
0
        /// <summary>
        /// Processes the message, updating our internal state and then invokes the events.
        /// </summary>
        /// <param name="message"></param>
        private void ProcessMessage(IMessage message)
        {
            if (message == null)
            {
                return;
            }
            switch (message.Type)
            {
            //We got a update, so we will update our current presence
            case MessageType.PresenceUpdate:
                lock (_sync)
                {
                    PresenceMessage pm = message as PresenceMessage;
                    if (pm != null)
                    {
                        //We need to merge these presences together
                        if (CurrentPresence == null)
                        {
                            CurrentPresence = pm.Presence;
                        }
                        else if (pm.Presence == null)
                        {
                            CurrentPresence = null;
                        }
                        else
                        {
                            CurrentPresence.Merge(pm.Presence);
                        }

                        //Update the message
                        pm.Presence = CurrentPresence;
                    }
                }

                break;

            //Update our configuration
            case MessageType.Ready:
                ReadyMessage rm = message as ReadyMessage;
                if (rm != null)
                {
                    lock (_sync)
                    {
                        Configuration = rm.Configuration;
                        CurrentUser   = rm.User;
                    }

                    //Resend our presence and subscription
                    SynchronizeState();
                }
                break;

            //Update the request's CDN for the avatar helpers
            case MessageType.JoinRequest:
                if (Configuration != null)
                {
                    //Update the User object within the join request if the current Cdn
                    JoinRequestMessage jrm = message as JoinRequestMessage;
                    if (jrm != null)
                    {
                        jrm.User.SetConfiguration(Configuration);
                    }
                }
                break;

            case MessageType.Subscribe:
                lock (_sync)
                {
                    SubscribeMessage sub = message as SubscribeMessage;
                    Subscription |= sub.Event;
                }
                break;

            case MessageType.Unsubscribe:
                lock (_sync)
                {
                    UnsubscribeMessage unsub = message as UnsubscribeMessage;
                    Subscription &= ~unsub.Event;
                }
                break;

            //We got a message we dont know what to do with.
            default:
                break;
            }

            //Invoke the appropriate methods
            switch (message.Type)
            {
            case MessageType.Ready:
                if (OnReady != null)
                {
                    OnReady.Invoke(this, message as ReadyMessage);
                }
                break;

            case MessageType.Close:
                if (OnClose != null)
                {
                    OnClose.Invoke(this, message as CloseMessage);
                }
                break;

            case MessageType.Error:
                if (OnError != null)
                {
                    OnError.Invoke(this, message as ErrorMessage);
                }
                break;

            case MessageType.PresenceUpdate:
                if (OnPresenceUpdate != null)
                {
                    OnPresenceUpdate.Invoke(this, message as PresenceMessage);
                }
                break;

            case MessageType.Subscribe:
                if (OnSubscribe != null)
                {
                    OnSubscribe.Invoke(this, message as SubscribeMessage);
                }
                break;

            case MessageType.Unsubscribe:
                if (OnUnsubscribe != null)
                {
                    OnUnsubscribe.Invoke(this, message as UnsubscribeMessage);
                }
                break;

            case MessageType.Join:
                if (OnJoin != null)
                {
                    OnJoin.Invoke(this, message as JoinMessage);
                }
                break;

            case MessageType.Spectate:
                if (OnSpectate != null)
                {
                    OnSpectate.Invoke(this, message as SpectateMessage);
                }
                break;

            case MessageType.JoinRequest:
                if (OnJoinRequested != null)
                {
                    OnJoinRequested.Invoke(this, message as JoinRequestMessage);
                }
                break;

            case MessageType.ConnectionEstablished:
                if (OnConnectionEstablished != null)
                {
                    OnConnectionEstablished.Invoke(this, message as ConnectionEstablishedMessage);
                }
                break;

            case MessageType.ConnectionFailed:
                if (OnConnectionFailed != null)
                {
                    OnConnectionFailed.Invoke(this, message as ConnectionFailedMessage);
                }
                break;

            default:
                //This in theory can never happen, but its a good idea as a reminder to update this part of the library if any new messages are implemented.
                Logger.Error("Message was queued with no appropriate handle! {0}", message.Type);
                break;
            }
        }
 private void Subsribe()
 {
     _manager.RdpViewer.OnApplicationClose          += delegate(object application) { OnApplicationClose?.Invoke(application); };
     _manager.RdpViewer.OnApplicationOpen           += delegate(object application) { OnApplicationOpen?.Invoke(application); };
     _manager.RdpViewer.OnApplicationUpdate         += delegate(object application) { OnApplicationUpdate?.Invoke(application); };
     _manager.RdpViewer.OnAttendeeConnected         += delegate(object attendee) { OnAttendeeConnected?.Invoke(attendee); };
     _manager.RdpViewer.OnAttendeeDisconnected      += delegate(object info) { OnAttendeeDisconnected?.Invoke(info); };
     _manager.RdpViewer.OnAttendeeUpdate            += delegate(object attendee) { OnAttendeeUpdate?.Invoke(attendee); };
     _manager.RdpViewer.OnChannelDataReceived       += delegate(object channel, int id, string data) { OnChannelDataReceived?.Invoke(channel, id, data); };
     _manager.RdpViewer.OnChannelDataSent           += delegate(object channel, int id, int sent) { OnChannelDataSent?.Invoke(channel, id, sent); };
     _manager.RdpViewer.OnConnectionAuthenticated   += delegate(object sender, EventArgs args) { OnConnectionAuthenticated?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionEstablished     += delegate(object sender, EventArgs args) { OnConnectionEstablished?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionFailed          += delegate(object sender, EventArgs args) { OnConnectionFailed?.Invoke(sender, args); };
     _manager.RdpViewer.OnConnectionTerminated      += delegate(int reason, int info) { OnConnectionTerminated?.Invoke(reason, info); };
     _manager.RdpViewer.OnControlLevelChangeRequest += delegate(object attendee, CTRL_LEVEL level) { OnControlLevelChangeRequest?.Invoke(attendee, level); };
     _manager.RdpViewer.OnError                        += delegate(object info) { OnError?.Invoke(info); };
     _manager.RdpViewer.OnFocusReleased                += delegate(int direction) { OnFocusReleased?.Invoke(direction); };
     _manager.RdpViewer.OnGraphicsStreamPaused         += delegate(object sender, EventArgs args) { OnGraphicsStreamPaused?.Invoke(sender, args); };
     _manager.RdpViewer.OnGraphicsStreamResumed        += delegate(object sender, EventArgs args) { OnGraphicsStreamResumed?.Invoke(sender, args); };
     _manager.RdpViewer.OnSharedDesktopSettingsChanged += delegate(int width, int height, int colordepth) { OnSharedDesktopSettingsChanged?.Invoke(width, height, colordepth); };
     _manager.RdpViewer.OnSharedRectChanged            += delegate(int left, int top, int right, int bottom) { OnSharedRectChanged?.Invoke(left, top, right, bottom); };
     _manager.RdpViewer.OnWindowClose                  += delegate(object window) { OnWindowClose?.Invoke(window); };
     _manager.RdpViewer.OnWindowOpen                   += delegate(object window) { OnWindowOpen?.Invoke(window); };
     _manager.RdpViewer.OnWindowUpdate                 += delegate(object window) { OnWindowUpdate?.Invoke(window); };
 }