Example #1
0
        /// <summary>
        /// Send a message to the server.
        /// </summary>
        /// <param name="message">Message to send.</param>
        /// <returns><c>true</c> if successful, otherwise <c>false</c>.</returns>
        public bool Send(IrssMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (_serverSocket == null)
            {
                return(false);
            }

            byte[] data = message.ToBytes();

            byte[] frame = new byte[sizeof(int) + data.Length];
            Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(data.Length)), 0, frame, 0, sizeof(int));
            Buffer.BlockCopy(data, 0, frame, sizeof(int), data.Length);

            try
            {
                // Send framed message
                _serverSocket.Send(frame);

                return(true);
            }
            catch (SocketException)
            {
                return(false);
            }
        }
Example #2
0
        internal void Send(IrssMessage message)
        {
            byte[] data = message.ToBytes();

            byte[] frame = new byte[sizeof(int) + data.Length];
            Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(data.Length)), 0, frame, 0, sizeof(int));
            Buffer.BlockCopy(data, 0, frame, sizeof(int), data.Length);

            // Send framed message
            _connection.Send(frame);
        }
Example #3
0
        private void ReceiveThread()
        {
            try
            {
                byte[] buffer = new byte[4];

                while (_processReceiveThread)
                {
                    if (!Receive(buffer))
                    {
                        break;
                    }

                    byte[] packet = new byte[IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0))];

                    if (!Receive(packet))
                    {
                        break;
                    }

                    IrssMessage         message = IrssMessage.FromBytes(packet);
                    MessageManagerCombo combo   = new MessageManagerCombo(message, this);

                    if (_messageSink != null)
                    {
                        _messageSink(combo);
                    }
                }
            }
#if TRACE
            catch (SocketException socketException)
            {
                Trace.WriteLine(socketException.ToString());
            }
#else
            catch (SocketException)
            {
            }
#endif
            finally
            {
                if (_connection != null)
                {
                    _connection.Close(100);
                    _connection = null;
                }

                _disconnectCallback(this);
            }
        }
 private void ReceivedMessage(IrssMessage received)
 {
   if (_learnIR != null && received.Type == MessageType.LearnIR)
   {
     if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
     {
       _learnIR.LearnStatus("Learned IR successfully", true);
     }
     else if ((received.Flags & MessageFlags.Timeout) == MessageFlags.Timeout)
     {
       _learnIR.LearnStatus("Learn IR timed out", false);
     }
     else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
     {
       _learnIR.LearnStatus("Learn IR failed", false);
     }
   }
 }
    private void MessageReceiver(IrssMessage received)
    {
      if (received.Type == MessageType.RemoteEvent)
      {
        string deviceName = received.MessageData[IrssMessage.DEVICE_NAME] as string;
        string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;

        _deviceName = deviceName;

        // TODO: When Abstract Remote Model becomes on by default
        //if (deviceName.Equals("Abstract", StringComparison.OrdinalIgnoreCase)
        _keyCode = keyCode;
        //else
        //  _keyCode = String.Format("{0} ({1})", deviceName, keyCode);

        Invoke(_keyCodeSet);
      }
    }
Example #6
0
        /// <summary>
        /// Send a message to a particular client.
        /// </summary>
        /// <param name="sendTo">Client to send to.</param>
        /// <param name="message">Message to send.</param>
        /// <returns><c>true</c> if successful, otherwise <c>false</c>.</returns>
        public bool Send(ClientManager sendTo, IrssMessage message)
        {
            if (_clientManagers == null)
            {
                return(false);
            }
            if (!_clientManagers.Contains(sendTo))
            {
                return(false);
            }

            try
            {
                sendTo.Send(message);
                return(true);
            }
            catch (SocketException)
            {
                ClientDisconnect(sendTo);
                return(false);
            }
        }
Example #7
0
    private void SendToRepeaters(IrssMessage message)
    {
      IrssLog.Debug("SendToRepeaters({0}, {1})", message.Type, message.Flags);

      List<ClientManager> unregister = new List<ClientManager>();

      lock (_registeredRepeaters)
      {
        foreach (ClientManager client in _registeredRepeaters)
        {
          if (!_server.Send(client, message))
          {
            IrssLog.Warn("Failed to send message to a repeater, unregistering repeater");

            // If a message doesn't get through then unregister that repeater
            unregister.Add(client);
          }
        }

        // Unregistering repeaters must be done as a two part process because otherwise the
        // foreach statement above would fail if you modified the _registeredRepeaters list
        // while enumerating it.
        foreach (ClientManager repeater in unregister)
        {
          UnregisterRepeater(repeater);
        }
      }
    }
Example #8
0
 private void QueueMessageSink(IrssMessage message)
 {
     _messageSink(message);
 }
Example #9
0
    private static void SendMessage(IrssMessage message)
    {
      if (message == null)
        throw new ArgumentNullException("message");

      if (_client != null)
        _client.Send(message);
    }
Example #10
0
    private void SendTo(ClientManager receiver, IrssMessage message)
    {
      IrssLog.Debug("SendTo({0}, {1})", message.Type, message.Flags);

      if (!_server.Send(receiver, message))
      {
        IrssLog.Warn("Failed to send message to a client, unregistering client");

        // If a message doesn't get through then unregister that client
        UnregisterClient(receiver);
      }
    }
    /// <summary>
    /// Learn an IR command.
    /// </summary>
    /// <param name="fileName">File to place learned IR command in (absolute path).</param>
    /// <returns><c>true</c> if successful, otherwise <c>false</c>.</returns>
    internal static bool LearnIR(string fileName)
    {
      try
      {
        if (String.IsNullOrEmpty(fileName))
        {
          Log.Error("TV2BlasterPlugin: Null or Empty file name for LearnIR()");
          return false;
        }

        if (!_registered)
        {
          Log.Warn("TV2BlasterPlugin: Not registered to an active IR Server");
          return false;
        }

        if (_learnIRFilename != null)
        {
          Log.Warn("TV2BlasterPlugin: Already trying to learn an IR command");
          return false;
        }

        _learnIRFilename = fileName;

        IrssMessage message = new IrssMessage(MessageType.LearnIR, MessageFlags.Request);
        _client.Send(message);
      }
      catch (Exception ex)
      {
        _learnIRFilename = null;
        Log.Error(ex);
        return false;
      }

      return true;
    }
Example #12
0
    internal static void ButtonPress(string keyCode)
    {
#if TRACE
      Trace.WriteLine("ButtonPress: " + keyCode);
#endif
      if (!_registered)
        return;

      byte[] bytes = IrssMessage.EncodeRemoteEventData(_device, keyCode);

      IrssMessage message = new IrssMessage(MessageType.ForwardRemoteEvent, MessageFlags.Notify, bytes);
      SendMessage(message);
    }
Example #13
0
    private void ReceivedMessage(IrssMessage received)
    {
      IrssLog.Debug("Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.RemoteEvent:
            if (listViewButtons.SelectedItems.Count == 1)
            {
              string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;

              listViewButtons.SelectedItems[0].SubItems[1].Text = keyCode;
            }
            return;

          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _registered = true;
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              MessageBox.Show(this, "Failed to register with server", "Virtual Remote Skin Editor Error",
                              MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return;

          case MessageType.ServerShutdown:
            MessageBox.Show(this, "Server has been shut down", "Virtual Remote Skin Editor Error", MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
            return;

          case MessageType.Error:
            MessageBox.Show(this, received.GetDataAsString(), "Virtual Remote Skin Editor Error from Server",
                            MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }
      }
      catch (Exception ex)
      {
        IrssLog.Error(ex);
        MessageBox.Show(this, ex.Message, "Virtual Remote Skin Editor Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
Example #14
0
    private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
    {
      if (_registered)
      {
        IrssMessage message = new IrssMessage(MessageType.UnregisterClient, MessageFlags.Request);
        _client.Send(message);

        _registered = false;
      }

      StopClient();
    }
Example #15
0
    private static void ReceivedMessage(IrssMessage received)
    {
      IrssLog.Debug("Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.BlastIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
              Info("Blast Success");
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
              Warn("Blast Failed!");
            break;

          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              Info("Registered to IR Server");
              _registered = true;
              //_irServerInfo = TransceiverInfo.FromString(received.Data);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              Warn("IR Server refused to register");
            }
            break;

          case MessageType.ServerShutdown:
            _registered = false;
            Warn("IR Server Shutdown - Blasting disabled until IR Server returns");
            break;

          case MessageType.Error:
            Warn(received.GetDataAsString());
            break;
        }
      }
      catch (Exception ex)
      {
        Error(ex);
      }
    }
Example #16
0
    void Connected(object obj)
    {
      ServiceRegistration.Get<ILogger>().Info("IrInputPlugin: Connected to server");

      IrssMessage message = new IrssMessage(MessageType.RegisterClient, MessageFlags.Request);
      _client.Send(message);
    }
Example #17
0
    private static void Connected(object obj)
    {
      _connectionFailures = 0;
      IrssLog.Info("Connected to server");
      _connected = true;
      IrssMessage message = new IrssMessage(MessageType.RegisterClient, MessageFlags.Request);
      _client.Send(message);

      _notifyIcon.Icon = Resources.Icon16;
      _notifyIcon.Text = "Translator";

      if (_firstConnection)
      {
        _firstConnection = false;
        MapEvent(MappingEvent.Translator_Start, true);
      }
    }
 /// <summary>
 /// Create a new MessageManagerCombo structure instance.
 /// </summary>
 /// <param name="message">The IrssMessage to encapsulate.</param>
 /// <param name="manager">The ClientManager to encapsulate.</param>
 public MessageManagerCombo(IrssMessage message, ClientManager manager)
 {
     _message = message;
     _manager = manager;
 }
Example #19
0
    private static void ReceivedMessage(IrssMessage received)
    {
      IrssLog.Debug("Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _irServerInfo = IRServerInfo.FromBytes(received.GetDataAsBytes());
              _registered = true;

              IrssLog.Info("Registered to IR Server");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              IrssLog.Warn("IR Server refused to register");
            }
            break;

          case MessageType.RemoteEvent:
            string deviceName = received.MessageData[IrssMessage.DEVICE_NAME] as string;
            string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;

            RemoteHandlerCallback(deviceName, keyCode);
            break;

          case MessageType.BlastIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              IrssLog.Debug("Blast successful");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              IrssLog.Error("Failed to blast IR command");
            }
            break;

          case MessageType.LearnIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              IrssLog.Debug("Learnt IR Successfully");

              byte[] dataBytes = received.GetDataAsBytes();

              using (FileStream file = File.Create(_learnIRFilename))
                file.Write(dataBytes, 0, dataBytes.Length);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              IrssLog.Error("Failed to learn IR command");
            }
            else if ((received.Flags & MessageFlags.Timeout) == MessageFlags.Timeout)
            {
              IrssLog.Error("Learn IR command timed-out");
            }

            _learnIRFilename = null;
            break;

          case MessageType.ServerShutdown:
            IrssLog.Warn("IR Server Shutdown - Media Center Blaster disabled until IR Server returns");
            _registered = false;
            break;

          case MessageType.Error:
            IrssLog.Error("Received error: {0}", received.GetDataAsString());
            break;
        }

        if (_handleMessage != null)
          _handleMessage(received);
      }
      catch (Exception ex)
      {
        IrssLog.Error("ReceivedMessage(): {0}", ex.ToString());
      }
    }
Example #20
0
    private static void Connected(object obj)
    {
      IrssLog.Info("Connected to server");

      UpdateTrayIcon("Media Center Blaster", Resources.Icon16);

      IrssMessage message = new IrssMessage(MessageType.RegisterClient, MessageFlags.Request);
      _client.Send(message);
    }
Example #21
0
    private void Stop()
    {
      _notifyIcon.Visible = false;

      try
      {
        if (_registered)
        {
          _registered = false;

          IrssMessage message = new IrssMessage(MessageType.UnregisterClient, MessageFlags.Request);
          _client.Send(message);
        }
      }
      catch
      {
      }

      StopClient();

      if (_mediaState != null)
      {
        _mediaState.Dispose();
        _mediaState = null;
      }
    }
Example #22
0
    private static void ReceivedMessage(IrssMessage received)
    {
      IrssLog.Debug("Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.RemoteEvent:
            {
              string deviceName = received.MessageData[IrssMessage.DEVICE_NAME] as string;
              string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;

              RemoteHandlerCallback(deviceName, keyCode);
            }
            break;

          case MessageType.KeyboardEvent:
            {
              int vKey = (int)received.MessageData[IrssMessage.V_KEY];
              bool keyUp = (bool)received.MessageData[IrssMessage.KEY_UP];

              KeyboardHandlerCallback("TODO", vKey, keyUp);
              break;
            }

          case MessageType.MouseEvent:
            {
              int deltaX = (int)received.MessageData[IrssMessage.DELTA_X];
              int deltaY = (int)received.MessageData[IrssMessage.DELTA_Y];
              int buttons = (int)received.MessageData[IrssMessage.BUTTONS];

              MouseHandlerCallback("TODO", deltaX, deltaY, buttons);
              break;
            }

          case MessageType.BlastIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
              IrssLog.Info("Blast successful");
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
              IrssLog.Error("Failed to blast IR command");
            break;

          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _irServerInfo = IRServerInfo.FromBytes(received.GetDataAsBytes());
              _registered = true;

              IrssLog.Info("Registered to IR Server");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              IrssLog.Warn("IR Server refused to register");
            }
            break;

          case MessageType.LearnIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              IrssLog.Info("Learned IR Successfully");

              byte[] dataBytes = received.GetDataAsBytes();

              using (FileStream file = File.Create(_learnIRFilename))
                file.Write(dataBytes, 0, dataBytes.Length);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              IrssLog.Error("Failed to learn IR command");
            }
            else if ((received.Flags & MessageFlags.Timeout) == MessageFlags.Timeout)
            {
              IrssLog.Warn("Learn IR command timed-out");
            }

            _learnIRFilename = null;
            break;

          case MessageType.ServerShutdown:
            IrssLog.Warn("IR Server Shutdown - Translator disabled until IR Server returns");
            _registered = false;

            _notifyIcon.Icon = Resources.Icon16Connecting;
            _notifyIcon.Text = "Translator - Connecting ...";

            break;

          case MessageType.Error:
            _learnIRFilename = null;
            IrssLog.Error("Received error: {0}", received.GetDataAsString());
            break;
        }

        if (_handleMessage != null)
          _handleMessage(received);
      }
      catch (Exception ex)
      {
        _learnIRFilename = null;
        IrssLog.Error(ex);
      }
    }
Example #23
0
        private void ConnectionThread()
        {
            // Outer loop is for reconnection attempts ...
            while (_processConnectionThread)
            {
                _connected = false;

                _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                #region Attempt to connect

                while (_processConnectionThread)
                {
                    try
                    {
                        _serverSocket.Connect(_serverEndpoint);
                        break;
                    }
                    catch (SocketException socketException)
                    {
                        if (!_processConnectionThread)
                        {
                            return;
                        }

                        if (socketException.SocketErrorCode == SocketError.ConnectionRefused)
                        {
                            Thread.Sleep(1000);
                            continue;
                        }

                        if (_commsFailureCallback != null)
                        {
                            _commsFailureCallback(socketException);
                        }
                        else
                        {
                            throw;
                        }
                    }
                    catch (Exception ex)
                    {
                        if (!_processConnectionThread)
                        {
                            return;
                        }

                        if (_commsFailureCallback != null)
                        {
                            _commsFailureCallback(ex);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                #endregion Attempt to connect

                if (!_processConnectionThread)
                {
                    return;
                }

                _connected = true;

                if (_connectCallback != null)
                {
                    _connectCallback(null);
                }

                #region Read from socket

                try
                {
                    byte[] buffer = new byte[4];

                    // Read data from socket ...
                    while (_processConnectionThread)
                    {
                        if (!Receive(buffer))
                        {
                            break;
                        }

                        byte[] packet = new byte[IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0))];

                        if (!Receive(packet))
                        {
                            break;
                        }

                        IrssMessage message = IrssMessage.FromBytes(packet);
                        _messageQueue.Enqueue(message);
                    }

                    if (!_processConnectionThread)
                    {
                        return;
                    }

                    if (_disconnectCallback != null)
                    {
                        _disconnectCallback(null);
                    }
                }
                catch (SocketException socketException)
                {
                    if (!_processConnectionThread)
                    {
                        return;
                    }

                    if (socketException.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        if (_disconnectCallback != null)
                        {
                            _disconnectCallback(null);
                        }
                    }
                    else
                    {
                        if (_commsFailureCallback != null)
                        {
                            _commsFailureCallback(socketException);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (!_processConnectionThread)
                    {
                        return;
                    }

                    if (_commsFailureCallback != null)
                    {
                        _commsFailureCallback(ex);
                    }
                    else
                    {
                        throw;
                    }
                }

                #endregion Read from socket
            }
        }
Example #24
0
    private static void BlastIR(string fileName, string port)
    {
      using (FileStream file = File.OpenRead(fileName))
      {
        if (file.Length == 0)
          throw new IOException(String.Format("Cannot Blast. IR file \"{0}\" has no data, possible IR learn failure",
                                              fileName));

        byte[] outData = new byte[4 + port.Length + file.Length];

        BitConverter.GetBytes(port.Length).CopyTo(outData, 0);
        Encoding.ASCII.GetBytes(port).CopyTo(outData, 4);

        file.Read(outData, 4 + port.Length, (int) file.Length);

        IrssMessage message = new IrssMessage(MessageType.BlastIR, MessageFlags.Request | MessageFlags.ForceNotRespond,
                                              outData);
        _client.Send(message);
      }
    }
    internal void Send(IrssMessage message)
    {
      byte[] data = message.ToBytes();

      byte[] frame = new byte[sizeof(int) + data.Length];
      Buffer.BlockCopy(BitConverter.GetBytes(IPAddress.HostToNetworkOrder(data.Length)), 0, frame, 0, sizeof(int));
      Buffer.BlockCopy(data, 0, frame, sizeof(int), data.Length);

      // Send framed message
      _connection.Send(frame);
    }
Example #26
0
    void ReceivedMessage(IrssMessage received)
    {
      ServiceRegistration.Get<ILogger>().Debug("IrInputPlugin: Received Message '{0}' {1}", received.Type, received.GetDataAsString());
      try
      {
        switch (received.Type)
        {
          case MessageType.RemoteEvent:
            string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;
            RemoteHandler(keyCode);
            break;

          // TODO: What to do with this code?
          /*
          case MessageType.BlastIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
              ServiceRegistration.Get<ILogger>().Info("IrInputPlugin: Blast successful");
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
              ServiceRegistration.Get<ILogger>().Warn("IrInputPlugin: Failed to blast IR command");
            break;
          */
          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _irServerInfo = IRServerInfo.FromBytes(received.GetDataAsBytes());

              ServiceRegistration.Get<ILogger>().Info("IrInputPlugin: Registered to Input Service '{0}'", _irServerInfo);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
              ServiceRegistration.Get<ILogger>().Warn("IrInputPlugin: Input Service refused to register plugin");
            break;

          // TODO: What to do with this code?
          /*
          case MessageType.LearnIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              ServiceRegistration.Get<ILogger>().Info("IrInputPlugin: Learned IR Successfully");

              byte[] dataBytes = received.GetDataAsBytes();

              using (FileStream file = File.Create(_learnIRFilename))
                file.Write(dataBytes, 0, dataBytes.Length);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
              ServiceRegistration.Get<ILogger>().Error("IrInputPlugin: Failed to learn IR command");
            else if ((received.Flags & MessageFlags.Timeout) == MessageFlags.Timeout)
              ServiceRegistration.Get<ILogger>().Error("IrInputPlugin: Learn IR command timed-out");
            break;
          */
          case MessageType.ServerShutdown:
            ServiceRegistration.Get<ILogger>().Warn("IrInputPlugin: Input Service shutdown - IrInputPlugin is disabled until Input Service returns");
            break;

          case MessageType.Error:
            ServiceRegistration.Get<ILogger>().Error("IrInputPlugin: Received error '{0}'", received.GetDataAsString());
            break;
        }
      }
      catch (Exception ex)
      {
        ServiceRegistration.Get<ILogger>().Error("Problem receiving IR message: {0}", ex);
      }
    }
Example #27
0
    private void ReceivedMessage(IrssMessage received)
    {
      Invoke(_addStatusLine,
          new Object[] { String.Format("Received Message: \"{0}, {1}\"", received.Flags , received.Type) });

      try
      {
        switch (received.Type)
        {
          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _registered = true;
              _irServerInfo = IRServerInfo.FromBytes(received.GetDataAsBytes());
              comboBoxPort.Items.Clear();
              comboBoxPort.Items.AddRange(_irServerInfo.Ports);
              comboBoxPort.SelectedIndex = 0;

              _client.Send(new IrssMessage(MessageType.ActiveReceivers, MessageFlags.Request));
              _client.Send(new IrssMessage(MessageType.ActiveBlasters, MessageFlags.Request));
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
            }
            return;

          case MessageType.ActiveBlasters:
            Invoke(_addStatusLine, new Object[] {received.GetDataAsString()});
            break;

          case MessageType.ActiveReceivers:
            Invoke(_addStatusLine, new Object[] {received.GetDataAsString()});
            break;

          case MessageType.RemoteEvent:
            string deviceName = received.MessageData[IrssMessage.DEVICE_NAME] as string;
            string keyCode = received.MessageData[IrssMessage.KEY_CODE] as string;

            Invoke(_addStatusLine, new Object[] {String.Format("{0} ({1})", deviceName, keyCode)});
            return;

          case MessageType.LearnIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              byte[] dataBytes = received.GetDataAsBytes();

              using (FileStream file = File.Create(_learnIRFilename))
                file.Write(dataBytes, 0, dataBytes.Length);
            }

            _learnIRFilename = null;
            break;

          case MessageType.ServerShutdown:
            _registered = false;
            return;

          case MessageType.Error:
            _learnIRFilename = null;
            Invoke(_addStatusLine, new Object[] {received.GetDataAsString()});
            return;
        }
      }
      catch (Exception ex)
      {
        Invoke(_addStatusLine, new Object[] {ex.Message});
      }
    }
Example #28
0
    private bool LearnIR(string fileName)
    {
      try
      {
        if (_learnIRFilename != null)
          return false;

        _learnIRFilename = fileName;

        IrssMessage message = new IrssMessage(MessageType.LearnIR, MessageFlags.Request);
        _client.Send(message);

        AddStatusLine("Learning");
      }
      catch (Exception ex)
      {
        _learnIRFilename = null;
        AddStatusLine(ex.Message);
        return false;
      }

      return true;
    }
Example #29
0
    private bool BlastIR(string fileName, string port)
    {
      try
      {
        using (FileStream file = File.OpenRead(fileName))
        {
          if (file.Length == 0)
            throw new IOException(String.Format("Cannot Blast. IR file \"{0}\" has no data, possible IR learn failure",
                                                fileName));

          byte[] outData = new byte[4 + port.Length + file.Length];

          BitConverter.GetBytes(port.Length).CopyTo(outData, 0);
          Encoding.ASCII.GetBytes(port).CopyTo(outData, 4);

          file.Read(outData, 4 + port.Length, (int) file.Length);

          IrssMessage message = new IrssMessage(MessageType.BlastIR, MessageFlags.Request, outData);
          _client.Send(message);
        }
      }
      catch (Exception ex)
      {
        AddStatusLine(ex.Message);
        return false;
      }

      return true;
    }
    private static void ReceivedMessage(IrssMessage received)
    {
      Log.Debug("TV2BlasterPlugin: Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.BlastIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              Log.Debug("TV2BlasterPlugin: Blast successful");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              Log.Error("TV2BlasterPlugin: Failed to blast IR command");
            }
            break;

          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              _irServerInfo = IRServerInfo.FromBytes(received.GetDataAsBytes());
              _registered = true;

              Log.Debug("TV2BlasterPlugin: Registered to IR Server");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              Log.Error("TV2BlasterPlugin: IR Server refused to register");
            }
            break;

          case MessageType.LearnIR:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              Log.Debug("TV2BlasterPlugin: Learned IR Successfully");

              byte[] dataBytes = received.GetDataAsBytes();

              using (FileStream file = File.Create(_learnIRFilename))
                file.Write(dataBytes, 0, dataBytes.Length);
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              Log.Error("TV2BlasterPlugin: Failed to learn IR command");
            }
            else if ((received.Flags & MessageFlags.Timeout) == MessageFlags.Timeout)
            {
              Log.Error("TV2BlasterPlugin: Learn IR command timed-out");
            }

            _learnIRFilename = null;
            break;

          case MessageType.ServerShutdown:
            Log.Info("TV2BlasterPlugin: IR Server Shutdown - Plugin disabled until IR Server returns");
            _registered = false;
            break;

          case MessageType.Error:
            _learnIRFilename = null;
            Log.Error("TV2BlasterPlugin: Received error: {0}", received.GetDataAsString());
            break;
        }

        if (_handleMessage != null)
          _handleMessage(received);
      }
      catch (Exception ex)
      {
        _learnIRFilename = null;
        Log.Error(ex);
      }
    }
Example #31
0
    private void buttonDisconnect_Click(object sender, EventArgs e)
    {
      AddStatusLine("Disconnect");

      try
      {
        if (_client == null)
        {
          AddStatusLine(" - Not connected");
          return;
        }

        if (_registered)
        {
          IrssMessage message = new IrssMessage(MessageType.UnregisterClient, MessageFlags.Request);
          _client.Send(message);
        }

        StopClient();
      }
      catch (Exception ex)
      {
        AddStatusLine(ex.Message);
      }
    }
    /// <summary>
    /// Blast an IR command.
    /// </summary>
    /// <param name="fileName">File to blast (absolute path).</param>
    /// <param name="port">Port to blast to.</param>
    internal static void BlastIR(string fileName, string port)
    {
      Log.Debug("TV2BlasterPlugin - BlastIR(): {0}, {1}", fileName, port);

      if (!_registered)
        throw new InvalidOperationException("Cannot Blast, not registered to an active IR Server");

      using (FileStream file = File.OpenRead(fileName))
      {
        if (file.Length == 0)
          throw new IOException(String.Format("Cannot Blast. IR file \"{0}\" has no data, possible IR learn failure",
                                              fileName));

        byte[] outData = new byte[4 + port.Length + file.Length];

        BitConverter.GetBytes(port.Length).CopyTo(outData, 0);
        Encoding.ASCII.GetBytes(port).CopyTo(outData, 4);

        file.Read(outData, 4 + port.Length, (int) file.Length);

        IrssMessage message = new IrssMessage(MessageType.BlastIR, MessageFlags.Request, outData);
        _client.Send(message);
      }
    }
Example #33
0
    private void buttonShutdownServer_Click(object sender, EventArgs e)
    {
      AddStatusLine("Shutdown");

      if (_client == null)
      {
        AddStatusLine(" - Not connected");
        return;
      }

      if (!_client.Connected)
      {
        AddStatusLine(" - Connecting...");
        return;
      }

      try
      {
        IrssMessage message = new IrssMessage(MessageType.ServerShutdown, MessageFlags.Request);
        _client.Send(message);
      }
      catch (Exception ex)
      {
        AddStatusLine(ex.Message);
      }
    }
Example #34
0
    private static void Connected(object obj)
    {
      IrssLog.Info("Connected to server");

      IrssMessage message = new IrssMessage(MessageType.RegisterClient, MessageFlags.Request);
      _client.Send(message);
    }
Example #35
0
    private void buttonSendRemoteButton_Click(object sender, EventArgs e)
    {
      AddStatusLine("Send Remote Button");

      try
      {
        if (_client == null)
        {
          AddStatusLine(" - Not connected");
          return;
        }

        if (!_client.Connected)
        {
          AddStatusLine(" - Connecting...");
          return;
        }

        byte[] bytes = IrssMessage.EncodeRemoteEventData(textBoxRemoteDevice.Text, textBoxRemoteCode.Text);
        
        IrssMessage message = new IrssMessage(MessageType.ForwardRemoteEvent, MessageFlags.Notify, bytes);
        _client.Send(message);
      }
      catch (Exception ex)
      {
        AddStatusLine(ex.Message);
      }
    }
Example #36
0
    private static void ReceivedMessage(IrssMessage received)
    {
      IrssLog.Debug("Received Message \"{0}\"", received.Type);

      try
      {
        switch (received.Type)
        {
          case MessageType.RegisterClient:
            if ((received.Flags & MessageFlags.Success) == MessageFlags.Success)
            {
              //_irServerInfo = IRServerInfo.FromBytes(received.DataAsBytes);
              _registered = true;

              IrssLog.Info("Registered to IR Server");
            }
            else if ((received.Flags & MessageFlags.Failure) == MessageFlags.Failure)
            {
              _registered = false;
              IrssLog.Warn("IR Server refused to register");
            }
            break;

          case MessageType.ServerShutdown:
            IrssLog.Warn("IR Server Shutdown - Web Remote disabled until IR Server returns");
            _registered = false;
            break;

          case MessageType.Error:
            IrssLog.Error(received.GetDataAsString());
            break;
        }
      }
      catch (Exception ex)
      {
        IrssLog.Error(ex);
      }
    }
Example #37
0
    private void SendToAllExcept(ClientManager exceptClient, IrssMessage message)
    {
      IrssLog.Debug("SendToAllExcept({0}, {1})", message.Type, message.Flags);

      List<ClientManager> unregister = new List<ClientManager>();

      lock (_registeredClients)
      {
        foreach (ClientManager client in _registeredClients)
        {
          if (client == exceptClient)
            continue;

          if (!_server.Send(client, message))
          {
            IrssLog.Warn("Failed to send message to a client, unregistering client");

            // If a message doesn't get through then unregister that client
            unregister.Add(client);
          }
        }

        // Unregistering clients must be done as a two part process because otherwise the
        // foreach statement above would fail if you modified the _registeredClients list
        // while enumerating it.
        foreach (ClientManager client in unregister)
        {
          UnregisterClient(client);
        }
      }
    }