Example #1
0
        object ReceiveBufferProcess(object obj)
        {
            var bytes     = new Byte[1000];
            var byteIndex = 0;

            while (true)
            {
                try
                {
                    var b = _rxQueue.Dequeue();

                    if (_programStopping)
                    {
                        return(null);
                    }

                    if (b == 'x')
                    {
                        var copiedBytes = new byte[byteIndex];
                        Array.Copy(bytes, copiedBytes, byteIndex);
#if DEBUG
                        //CrestronConsole.Print("LG Rx: ");
                        //Tools.PrintBytes(copiedBytes, 0, copiedBytes.Length, true);
#endif
                        if (ReceivedData != null)
                        {
                            try
                            {
                                ReceivedData(copiedBytes);
                            }
                            catch (Exception e)
                            {
                                CloudLog.Exception(e);
                            }
                        }

                        byteIndex = 0;
                    }
                    else
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
#if DEBUG
                        //CrestronConsole.Print("Error in Lg Rx Handler: ");
                        //Tools.PrintBytes(bytes, 0, byteIndex);
#endif
                        CloudLog.Exception(string.Format("{0} - Exception in rx thread", GetType().Name), e);
                    }
                }

                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(0);
            }
        }
Example #2
0
        private object SendBufferProcess(object o)
        {
            while (true)
            {
                try
                {
                    var bytes = _txQueue.Dequeue();
                    if (bytes == null)
                    {
                        CloudLog.Notice("Exiting {0}", Thread.CurrentThread.Name);
                        return(null);
                    }
#if DEBUG
                    Debug.WriteInfo("Samsung Tx",
                                    Debug.AnsiPurple + Tools.GetBytesAsReadableString(bytes, 0, bytes.Length, false) +
                                    Debug.AnsiReset);
#endif
                    _comPort.Send(bytes, bytes.Length);
                    CrestronEnvironment.AllowOtherAppsToRun();
                    Thread.Sleep(10);
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        CloudLog.Exception(string.Format("{0} - Exception in tx buffer thread", GetType().Name), e);
                    }
                }
            }
        }
Example #3
0
        object SendThreadProcess(object o)
        {
#if DEBUG
            CrestronConsole.PrintLine("{0}.SendThreadProcess() Start", this.GetType().Name);
#endif
            while (!_sendQueue.IsEmpty)
            {
                byte[]           data = _sendQueue.Dequeue();
                SocketErrorCodes err  = SendPacket(_client, data);

#if DEBUG
                CrestronConsole.PrintLine("{0} Send process result - {1}", this.GetType().Name, err);
#endif

                if (err != SocketErrorCodes.SOCKET_OK)
                {
                    ErrorLog.Error("{0}.Send process - Error sending data to socket, {1}", this.GetType().Name, err);
                }

                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(0);
            }

#if DEBUG
            CrestronConsole.PrintLine("{0}.SendThreadProcess() End", this.GetType().Name);
#endif

            return(null);
        }
Example #4
0
        private static object FileWriteProcess(object userSpecific)
        {
            Notice("CloudLog FileWriteProcess Started");

            while (true)
            {
                CrestronEnvironment.AllowOtherAppsToRun();

                var log = FileWriteQueue.Dequeue();

                using (var writer = CurrentLogFile.AppendText())
                {
                    writer.WriteLine(log);
                    while (!FileWriteQueue.IsEmpty)
                    {
                        writer.WriteLine(FileWriteQueue.Dequeue());
                    }
                }

                if (_programEnding && FileWriteQueue.IsEmpty)
                {
                    return(null);
                }
            }
        }
Example #5
0
        object SendBufferProcess(object o)
        {
            while (!TxQueue.IsEmpty)
            {
                try
                {
                    Byte[] packet = TxQueue.Dequeue();
#if DEBUG
                    //CrestronConsole.Print("Samsung Tx: ");
                    //Tools.PrintBytes(packet, packet.Length);
#endif
                    if (programStopping)
                    {
                        TxQueue.Clear();
                        return(null);
                    }
                    else
                    {
                        this.ComPort.Send(packet, packet.Length);
                        CrestronEnvironment.AllowOtherAppsToRun();
                        Thread.Sleep(10);
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        ErrorLog.Exception(string.Format("{0} - Exception in tx buffer thread", GetType().Name), e);
                    }
                }
            }

            return(null);
        }
Example #6
0
        internal void QueueRequest(ServerRequest request)
        {
            RequestQueue.Enqueue(request);

            if (_dispatchThread != null && _dispatchThread.ThreadState == Thread.eThreadStates.ThreadRunning)
            {
                return;
            }

            _dispatchThread = new Thread(specific =>
            {
#if true
                Debug.WriteSuccess("AvediaServer", "Launching {0}.DispacthThread, Request Count = {1}", GetType().Name,
                                   RequestQueue.Count);
                Debug.WriteInfo("AvediaServer", "HttpClient Timeout = {0}, TimeoutEnabled = {1}", HttpClient.Timeout,
                                HttpClient.TimeoutEnabled);
#endif

                while (true)
                {
                    var r = RequestQueue.Dequeue();
                    if (request == null)
                    {
                        CloudLog.Info("Exiting {0}", Thread.CurrentThread.Name);
                        return(null);
                    }
#if true
                    CrestronConsole.PrintLine("{0} {1}", r.RequestType.ToString(), r.Url);
                    if (r.RequestType == RequestType.Post)
                    {
                        CrestronConsole.PrintLine(r.ContentString);
                    }
#endif
                    try
                    {
                        var response = HttpClient.Dispatch(r);

                        try
                        {
                            r.Callback(response, HTTP_CALLBACK_ERROR.COMPLETED);
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e);
                        }
                    }
                    catch
                    {
                        r.Callback(null, HTTP_CALLBACK_ERROR.UNKNOWN_ERROR);
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                }
            }, null)
            {
                Name = "Avedia HTTP dispatch process"
            };
        }
        object ReceiveBufferProcess(object obj)
        {
            Byte[] bytes     = new Byte[1000];
            int    byteIndex = 0;

            while (true)
            {
                try
                {
                    byte b = RxQueue.Dequeue();

                    if (programStopping)
                    {
                        return(null);
                    }

                    if (b == 10)
                    {
                        // skip line feed
                    }

                    // If find byte = CR
                    else if (b == 13)
                    {
                        // Copy bytes to new array with length of packet and ignoring the CR.
                        Byte[] copiedBytes = new Byte[byteIndex];
                        Array.Copy(bytes, copiedBytes, byteIndex);

                        byteIndex = 0;
#if DEBUG
                        CrestronConsole.Print("Revolabs Rx: ");
                        Tools.PrintBytes(copiedBytes, copiedBytes.Length, true);
#endif
                        if (ReceivedData != null)
                        {
                            ReceivedData(this, Encoding.ASCII.GetString(copiedBytes, 0, copiedBytes.Length));
                        }
                        CrestronEnvironment.AllowOtherAppsToRun();
                    }
                    else
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
#if DEBUG
                        CrestronConsole.Print("Error in Revolabs Rx: ");
                        Tools.PrintBytes(bytes, byteIndex);
#endif
                        ErrorLog.Exception(string.Format("{0} - Exception in rx thread", GetType().Name), e);
                    }
                }
            }
        }
Example #8
0
        private object SendProcess(object userSpecific)
        {
            while (_sendQueue.Count > 0)
            {
                var message = _sendQueue.Dequeue();
#if DEBUG
                CrestronConsole.PrintLine(Debug.AnsiGreen + "Yamaha Tx: {0}" + Debug.AnsiReset, message);
#endif
                base.Send(message + "\x0d");

                CrestronEnvironment.AllowOtherAppsToRun();
            }

            return(null);
        }
        private object RxThread(object userSpecific)
        {
            Byte[] bytes     = new Byte[1000];
            int    byteIndex = 0;

            while (!_programStopping)
            {
                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(0);

                try
                {
                    byte b = _rxQueue.Dequeue();

                    if (byteIndex == 7 && b == 0x08)
                    {
                        bytes[byteIndex] = b;
                        var copiedBytes = new Byte[byteIndex + 1];
                        Array.Copy(bytes, copiedBytes, byteIndex + 1);

                        byteIndex = 0;
#if DEBUG
                        CrestronConsole.PrintLine("VT Board Rx: ");
                        Tools.PrintBytes(copiedBytes, copiedBytes.Length, true);
#endif
                        OnReceivedData(copiedBytes);
                    }
                    else if (byteIndex == 7 && b != 0x08)
                    {
                        byteIndex = 0;
                    }
                    else
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        ErrorLog.Error("{0} - Error in thread: {1}, byteIndex = {2}", GetType().ToString(), e.Message, byteIndex);
                    }
                }
            }

            return(null);
        }
        private object CodecPollingProcess(object userSpecific)
        {
            while (!_programStopping)
            {
                foreach (var valuePair in _codecAddresses)
                {
                    var roomId  = valuePair.Key;
                    var address = valuePair.Value;

                    try
                    {
                        var uri = new UriBuilder("https", address, 443, "status.xml").Uri;
                        Debug.WriteInfo("Polling Codec", "Room {0}: {1}", roomId, uri.ToString());
                        var request = new HttpsClientRequest {
                            Url = new UrlParser(uri.ToString())
                        };
                        var username = ConfigManager.Config.CodecUsername;
                        var password = ConfigManager.Config.CodecPassword;
                        var auth     = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));
                        request.Header.AddHeader(new HttpsHeader("Authorization", "Basic " + auth));
                        var response = Client.Dispatch(request);
                        var reader   = new XmlReader(response.ContentString);
                        var doc      = XDocument.Load(reader);
                        var status   = doc.Element("Status");
                        Debug.WriteSuccess("Codec Online", status.Element("UserInterface").Element("ContactInfo").Element("Name").Value);
                        Debug.WriteSuccess("Mute", status.Element("Audio").Element("Microphones").Element("Mute").Value);
                        Debug.WriteSuccess("In Call", status.Elements("Call").Any().ToString());
                        Debug.WriteSuccess("Uptime", TimeSpan.FromSeconds(int.Parse(status.Element("SystemUnit").Element("Uptime").Value)).ToPrettyFormat());
                        Debug.WriteSuccess("Standby", "Status = {0}", status.Element("Standby").Element("State").Value != "Standby");
                        CrestronConsole.PrintLine("");
                    }
                    catch (Exception e)
                    {
                        CloudLog.Error("Error polling codec at {0}, {1}", address, e.Message);
                    }
                }

                Thread.Sleep(30000);
                CrestronEnvironment.AllowOtherAppsToRun();
            }

            CloudLog.Notice("Leaving thread: {0}", Thread.CurrentThread.Name);

            return(null);
        }
        /// <summary>
        /// Writes a list of SignedAnalogPropertyInterlocks to the XML Document in memory.
        /// </summary>
        /// <param name="items">The list of SignedAnalogPropertyInterlock items to write.</param>
        /// <returns>True if successful, false if any item fails.</returns>
        public bool WriteSignedAnalogPropertyInterlocks(List <SignedAnalogPropertyInterlock> items)
        {
            var status     = true;
            var markerTime = CrestronEnvironment.GetLocalTime().AddSeconds(20);

            for (var i = 0; i < items.Count; i++)
            {
                if (CrestronEnvironment.GetLocalTime() > markerTime)
                {
                    CrestronEnvironment.AllowOtherAppsToRun();
                    markerTime = CrestronEnvironment.GetLocalTime().AddSeconds(20);
                }
                if (WriteElement(items[i].Element) == false)
                {
                    status = false;
                }
            }
            return(status);
        }
        /// <summary>
        /// Writes all the SerialElements from a list of SerialProcessors to the XML Document in memory.
        /// </summary>
        /// <param name="items">A list of SerialProcessors.</param>
        /// <returns>True if successful, false if it fails.</returns>
        public bool WriteSerials(List <SerialProcessor> items)
        {
            var status     = true;
            var markerTime = CrestronEnvironment.GetLocalTime().AddSeconds(20);

            for (var i = 0; i < items.Count; i++)
            {
                if (CrestronEnvironment.GetLocalTime() > markerTime)
                {
                    CrestronEnvironment.AllowOtherAppsToRun();
                    markerTime = CrestronEnvironment.GetLocalTime().AddSeconds(20);
                }
                if (WriteSerials(items[i]) == false)
                {
                    status = false;
                }
            }
            return(status);
        }
Example #13
0
        object RxHandler(object o)
        {
            while (true)
            {
                try
                {
                    var bytes = _rxQueue.Dequeue();

                    if (bytes == null)
                    {
                        CloudLog.Notice("Bytes returned null. Program stopping? Exiting {0}", Thread.CurrentThread.Name);
                        return(null);
                    }

                    for (var i = 0; i < bytes.Length; i++)
                    {
                        switch (bytes[i])
                        {
                        case 10:
                            break;

                        case 13:
                            OnDataReceived(Encoding.ASCII.GetString(_bytes, 0, _byteIndex));
                            _byteIndex = 0;
                            break;

                        default:
                            _bytes[_byteIndex] = bytes[i];
                            _byteIndex++;
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ErrorLog.Exception("Exception in Codec Rx thread:", ex);
                }

                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(0);
            }
        }
Example #14
0
        object ReceiveBufferProcess(object obj)
        {
            var bytes     = new Byte[BufferLen];
            var byteIndex = 0;

            while (true)
            {
                try
                {
                    var b = _rxQueue.Dequeue();

                    if (_programStopping)
                    {
                        CloudLog.Notice("Exiting {0}", Thread.CurrentThread.Name);
                        return(null);
                    }

                    if (b == 0x0d)
                    {
                        OnReceivedString(Encoding.ASCII.GetString(bytes, 0, byteIndex));

                        byteIndex = 0;
                    }
                    else if (b != 0x0a)
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        CloudLog.Exception(string.Format("{0} - Exception in rx thread", GetType().Name), e);
                    }
                }

                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(0);
            }
        }
Example #15
0
        internal static void GetRequest(ServerRequest request)
        {
            RequestQueue.Enqueue(request);

            if (_dispatchThread == null || _dispatchThread.ThreadState != Thread.eThreadStates.ThreadRunning)
            {
                _dispatchThread = new Thread(specific =>
                {
#if true
                    CrestronConsole.PrintLine("Launching TripleCare.DispacthThread, Request Count = {0}", RequestQueue.Count);
#endif

                    while (RequestQueue.Count > 0)
                    {
                        if (!HttpClient.ProcessBusy)
                        {
#if true
                            CrestronConsole.PrintLine("TripleCare.HttpClient available, dispatching ...");
#endif
                            var r = RequestQueue.Dequeue();
#if true
                            CrestronConsole.PrintLine("{0} {1}", r.RequestType.ToString(), r.Url);
                            if (r.RequestType == RequestType.Post)
                            {
                                CrestronConsole.PrintLine(r.ContentString);
                            }
#endif
                            var response = HttpClient.Dispatch(r);
                            r.Callback(r.Id, response);
                        }

                        CrestronEnvironment.AllowOtherAppsToRun();
                    }

                    return(null);
                }, null);
            }
        }
Example #16
0
        internal void GetRequest(ServerRequest request)
        {
            _requestQueue.Enqueue(request);

            if (_dispatchThread == null || _dispatchThread.ThreadState != Thread.eThreadStates.ThreadRunning)
            {
                _dispatchThread = new Thread(specific =>
                {
#if DEBUG
                    CrestronConsole.PrintLine("Launching {0}.DispacthThread, Request Count = {1}", GetType().Name,
                                              _requestQueue.Count);
#endif

                    while (_requestQueue.Count > 0)
                    {
                        if (!HttpClient.ProcessBusy)
                        {
#if DEBUG
                            CrestronConsole.PrintLine("{0}.HttpClient available, dispatching ...", GetType().Name);
#endif
                            var r = _requestQueue.Dequeue();
#if DEBUG
                            CrestronConsole.PrintLine("{0} {1}", r.RequestType.ToString(), r.Url);
                            if (r.RequestType == RequestType.Post)
                            {
                                CrestronConsole.PrintLine(r.ContentString);
                            }
#endif
                            HttpClient.DispatchAsync(r, r.Callback);
                        }

                        CrestronEnvironment.AllowOtherAppsToRun();
                    }

                    return(null);
                }, null);
            }
        }
Example #17
0
 private void InternalClockInitialize()
 {
     _clockInitThread = new Thread(specific =>
     {
         CloudLog.Debug("InternalClockInitialize(), Waiting for seconds to be 0", GetType().Name);
         while (DateTime.Now.Second != 0)
         {
             Thread.Sleep(50);
             CrestronEnvironment.AllowOtherAppsToRun();
         }
         CloudLog.Notice("InternalClockInitialize(), Seconds should now be zero, time is now {1}, creating CTimer to track time",
                         GetType().Name,
                         DateTime.Now.ToString("T"));
         _clockTimer = new CTimer(s => OnTimeChange(), null, 60000, 60000);
         OnTimeChange();
         CloudLog.Info("InternalClockInitialize(), OnTimeChange() will be called every time time is 0 seconds", GetType().Name);
         return(null);
     }, null, Thread.eThreadStartOptions.CreateSuspended)
     {
         Name     = "Clock Init Thread",
         Priority = Thread.eThreadPriority.HighPriority
     };
     _clockInitThread.Start();
 }
Example #18
0
        protected object ConnectionThreadProcess(object o)
        {
            var memoryStream     = new MemoryStream();
            var reader           = new StreamReader(memoryStream);
            var receivedAnything = false;

            while (true)
            {
                var connectCount = 0;
                while (_remainConnected && !Connected)
                {
                    connectCount++;
                    _client.AddressClientConnectedTo = _currentAddress;
                    Debug.WriteInfo(GetType().Name, "Address to connect to set to {0}", _currentAddress);
                    var result = _client.ConnectToServer();
                    if (result == SocketErrorCodes.SOCKET_OK)
                    {
                        CloudLog.Notice("{0} connected to {1}", GetType().Name, _client.AddressClientConnectedTo);
                        receivedAnything = false;
                        break;
                    }

                    TryAnotherAddress();

                    if (connectCount <= 4 || connectCount > 10)
                    {
                        continue;
                    }

                    if (connectCount == 10)
                    {
                        CloudLog.Error("{0} failed to connect to any address, will keep trying in background",
                                       GetType().Name);
                    }
                    else
                    {
                        CloudLog.Warn("{0} cannot connect to address: {1}", GetType().Name, _currentAddress);
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                }

                _pollTimer = new CTimer(specific => DoNothing(), null, 30000, 30000);

                _adapterType = _client.EthernetAdapter;

                while (true)
                {
                    var dataCount = _client.ReceiveData();

                    if (dataCount <= 0)
                    {
                        Debug.WriteWarn(GetType().Name, "Disconnected!");
                        _pollTimer.Stop();
                        _pollTimer.Dispose();
                        _pollTimer = null;

                        if (_remainConnected)
                        {
                            if (!receivedAnything)
                            {
                                CloudLog.Warn(
                                    "{0} connected but didn't receive anything." +
                                    "Will wait for 1 minute before reconnection attempt. Upgrade may be in progress.",
                                    GetType().Name);
                                Thread.Sleep(60000);
                            }
                            break;
                        }

                        Debug.WriteWarn("Exiting Thread", Thread.CurrentThread.Name);
                        return(null);
                    }

                    receivedAnything = true;
#if DEBUG
                    Debug.WriteInfo(GetType().Name, "{0} bytes in buffer", dataCount);
#endif
                    for (var i = 0; i < dataCount; i++)
                    {
                        var b = _client.IncomingDataBuffer[i];
                        if (b != 0)
                        {
                            memoryStream.WriteByte(b);
                            continue;
                        }

                        memoryStream.Position = 0;
                        try
                        {
                            var data = JToken.Parse(reader.ReadToEnd());
                            memoryStream.SetLength(0);
#if DEBUG
                            Debug.WriteInfo(_name + " Rx",
                                            Debug.AnsiBlue + data.ToString(Formatting.None) + Debug.AnsiReset);
#endif
                            if (data["method"] != null)
                            {
                                OnRequestReceived(this, new QsysRequest(data));
                            }
                            else if (data["id"] != null)
                            {
                                var id = data["id"].Value <int>();
                                if (_requests.ContainsKey(id))
                                {
                                    var request = _requests[id];
                                    _requests.Remove(id);
                                    OnResponseReceived(this, new QsysResponse(data, request));
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception("Error occured processing a complete data parcel from Core", e);
                        }
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                    Thread.Sleep(0);
                }
            }
        }
Example #19
0
        object CiscoCodecRegisterProcess(object threadObject)
        {
            while (!programStopping)
            {
                try
                {
                    if (this.HttpClient.StartSession().Length > 0)
                    {
                        ErrorLog.Notice("Codec has connected and received a session id");
                    }
                    else
                    {
                        ErrorLog.Warn("Codec has connected but did not receive session id");
                    }

                    break;
                }
                catch (Exception e)
                {
                    ErrorLog.Warn("Could not start session with Cisco codec, {0}", e.Message);
                }

                CrestronConsole.PrintLine("Waiting for codec connection... will retry in 30 seconds");
                ErrorLog.Warn("Waiting for codec connection... will retry in 30 seconds");

                CrestronEnvironment.AllowOtherAppsToRun();
                Thread.Sleep(30000);
            }

            try
            {
                CrestronConsole.PrintLine("Connecting ControlSystem to codec and registering...");

                CommandArgs args = new CommandArgs();
                args.Add("HardwareInfo", ControlSystem.ControllerPrompt);
                args.Add("ID",
                         CrestronEthernetHelper.GetEthernetParameter(
                             CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
                             CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                                 FeedbackServer.AdapterForIPAddress)));
                args.Add("Name", "Crestron Control System");
                args.Add("NetworkAddress",
                         CrestronEthernetHelper.GetEthernetParameter(
                             CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                             CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                                 FeedbackServer.AdapterForIPAddress)));
                args.Add("SerialNumber", "Unknown");
                args.Add("Type", "ControlSystem");
                var assembly = Assembly.GetExecutingAssembly().GetName();
                args.Add("SoftwareInfo", assembly.Name + " " + assembly.Version);
                XDocument response = SendCommand("Peripherals/Connect", args);

                CrestronConsole.PrintLine("Codec registration {0}",
                                          response.Element("Command").Element("PeripheralsConnectResult").Attribute("status").Value == "OK");
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Error trying to register control system with Cisco Codec", e);
            }

            try
            {
                CrestronConsole.PrintLine("Registering for HttpFeedback...");
                this.Registerfeedback();
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Error trying to register feedback notifications with Cisco Codec", e);
            }

            try
            {
                CrestronConsole.PrintLine("Getting call status...");
                this.Calls.Update();
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Error trying to update calls status with Cisco Codec", e);
            }

            try
            {
                if (this.HasConnected != null)
                {
                    this.HasConnected(this);
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Error calling CiscoCodec.HasConnected thread", e);
            }

            try
            {
                CrestronConsole.PrintLine("Creating timer to periodically check the codec connection every 60 seconds");
                _CheckStatusTimer = new CTimer(CheckStatus, null, 60000, 60000);
            }
            catch (Exception e)
            {
                CrestronConsole.PrintLine("Error crating CiscoCodec CheckStatus Timer", e.Message);
                ErrorLog.Error("Error creating CiscoCodec CheckStatus Timer", e.Message);
            }

            this.DeviceCommunicating = true;

            return(null);
        }
Example #20
0
        public void ConnectionStart()
        {
            if (_connectionId > 0 || (_connectionThread != null && _connectionThread.ThreadState == Thread.eThreadStates.ThreadRunning))
            {
                return;
            }
            _connectionActive = true;
            _connectionWait.Reset();
            CloudLog.Notice("{0} Initialize() called", GetType().Name);
            _connectionThread = new Thread(specific =>
            {
                while (_connectionActive && !_programStopping)
                {
                    var suppressErrors = false;

                    UriBuilder uri;
                    Task <HttpResponseMessage> task;
                    HttpResponseMessage response;
                    Task <string> readTask;
                    string content;
                    JToken json;

                    while (_connectionId == 0)
                    {
                        try
                        {
                            uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                            {
                                Query = "action=connect"
                            };

                            Debug.WriteInfo("Trying to connect to " + uri.Uri);

                            task     = _client.GetAsync(uri.Uri);
                            response = task.Await();

                            response.EnsureSuccessStatusCode();

                            readTask = response.Content.ReadAsStringAsync();
                            content  = readTask.Await();
#if DEBUG
                            Debug.WriteInfo("Response content:\r\n" + content);
#endif
                            json = JToken.Parse(content);

                            _connectionId = int.Parse(json["connectionid"].Value <string>());
                            CloudLog.Debug("{0} connected and received conenction id of \"{1}\"", GetType().Name,
                                           _connectionId);

                            try
                            {
                                var eventInfo   = json["configevents"].First;
                                _currentClip    = eventInfo["eParamID_CurrentClip"].Value <string>();
                                _transportState =
                                    (ETransportState)int.Parse(eventInfo["eParamID_TransportState"].Value <string>());
                                OnTransportModeChanged(this);
                            }
                            catch (Exception e)
                            {
                                Debug.WriteWarn("Could not parse configevents on connect, {0}", e.Message);
                            }
                        }
                        catch (Exception e)
                        {
                            if (!suppressErrors)
                            {
                                suppressErrors = true;
                                CloudLog.Error("Error trying to connect to {0}, {1}", GetType().Name, e.Message);
                                CloudLog.Warn("{0} will try again in 5 seconds", GetType().Name);
                            }

                            _connectionWait.Wait(5000);

                            DeviceCommunicating = false;
                        }
                    }

                    DeviceCommunicating = true;

                    uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                    {
                        Query = "action=get&paramid=eParamID_TransportState"
                    };

                    Debug.WriteInfo("Trying to connect to " + uri.Uri);

                    task     = _client.GetAsync(uri.Uri);
                    response = task.Await();

                    response.EnsureSuccessStatusCode();
                    readTask = response.Content.ReadAsStringAsync();
                    content  = readTask.Await();
#if DEBUG
                    Debug.WriteWarn("Response content:\r\n" + content);
#endif
                    json = JToken.Parse(content);

                    TransportState = (ETransportState)int.Parse(json["value"].Value <string>());

                    while (_connectionActive)
                    {
                        var timeStamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

                        uri = new UriBuilder("http", _ipAddress, 80, string.Format("config"))
                        {
                            Query =
                                string.Format("action=wait_for_config_events&connectionid={0}&_={1}", _connectionId,
                                              timeStamp)
                        };

                        Debug.WriteInfo("Trying to connect to " + uri.Uri);

                        task     = _client.GetAsync(uri.Uri);
                        response = task.Await();

                        if (response.StatusCode == HttpStatusCode.Gone)
                        {
                            _connectionId = 0;
                            break;
                        }

                        response.EnsureSuccessStatusCode();
                        readTask = response.Content.ReadAsStringAsync();
                        content  = readTask.Await();
#if DEBUG
                        Debug.WriteWarn("Response content:\r\n" + content);
#endif
                        json = JToken.Parse(content);

                        foreach (var item in json)
                        {
                            var paramId = item["param_id"].Value <string>();
                            switch (paramId)
                            {
                            case "eParamID_DisplayTimecode":
                                _timeCode = item["str_value"].Value <string>();
                                break;

                            case "eParamID_CurrentClip":
                                _currentClip = item["str_value"].Value <string>();
                                break;

                            case "eParamID_TransportState":
                                _transportState = (ETransportState)item["int_value"].Value <int>();
                                break;
                            }
                        }

                        OnTransportModeChanged(this);

                        CrestronEnvironment.AllowOtherAppsToRun();

                        _connectionWait.Wait(100);
                    }
                }

                _connectionId = 0;

                return(null);
            }, null);
        }
Example #21
0
        private object CheckStatusThread(object userSpecific)
        {
            CloudLog.Info("{0} Started status checking thread", GetType().Name);

            while (!_programStopping)
            {
                try
                {
                    if (_inputStatusNotChecked)
                    {
                        _checkWait.Wait(5000);
                    }
                    else
                    {
                        _checkWait.Wait(60000);
                    }

                    _threadRunning = true;

                    CrestronEnvironment.AllowOtherAppsToRun();
                    Thread.Sleep(0);

                    if (_programStopping)
                    {
                        return(null);
                    }

                    #region Get System Info

                    var response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/system", "getSystemInformation", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        if (response.ConnectionFailed)
                        {
                            DeviceCommunicating = false;
                            _connectionOk       = false;
                        }
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JObject;
                        _serialNumber = info["serial"].Value <string>();
                        _model        = info["model"].Value <string>();
                        _macAddress   = info["macAddr"].Value <string>();
                        _versionInfo  = info["generation"].Value <string>();
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                    }

                    #endregion

                    #region Get Power Status

                    var previousPowerWasNotOn = PowerStatus != DevicePowerStatus.PowerOn;

                    response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/system", "getPowerStatus", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        if (response.ConnectionFailed)
                        {
                            DeviceCommunicating = false;
                            _connectionOk       = false;
                        }
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JObject;

                        switch (info["status"].Value <string>())
                        {
                        case "standby":
                            SetPowerFeedback(DevicePowerStatus.PowerOff);
                            break;

                        case "active":
                            SetPowerFeedback(DevicePowerStatus.PowerOn);
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                        continue;
                    }

                    #endregion

                    DeviceCommunicating = true;

                    if (PowerStatus == DevicePowerStatus.PowerOn)
                    {
                        #region Get Input Status

                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent",
                                                         "getPlayingContentInfo", "1.0").Await();
                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("Error trying to get input status from Sony Display, will try again in 5 seconds");
                            _inputStatusNotChecked = true;
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JObject;

                            var uri = info["uri"].Value <string>();

                            if (_availableSources != null && _availableSources.Any(s => s != null && s.Uri == uri))
                            {
                                _currentInput = _availableSources.First(s => s.Uri == uri).InputType;

                                if (_requestedInput != DisplayDeviceInput.Unknown && _currentInput != _requestedInput)
                                {
                                    SetInput(_requestedInput,
                                             previousPowerWasNotOn ? TimeSpan.FromSeconds(2) : TimeSpan.Zero);
                                }
                                else if (_requestedInput == _currentInput)
                                {
                                    _requestedInput = DisplayDeviceInput.Unknown;
                                }
                            }
                            else
                            {
                                _currentInput = DisplayDeviceInput.Unknown;
                            }

                            _inputStatusNotChecked = false;
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }

                        #endregion

                        #region Get Volume Level

                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/audio", "getVolumeInformation",
                                                         "1.0").Await();
                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            continue;
                        }

                        try
                        {
                            foreach (var token in response.Data.First())
                            {
                                var info = token as JObject;

                                var type =
                                    (TargetVolumeDeviceType)
                                    Enum.Parse(typeof(TargetVolumeDeviceType), info["target"].Value <string>(), true);

                                var currentLevel = info["volume"].Value <int>();
                                var minLevel     = info["minVolume"].Value <int>();
                                var maxLevel     = info["maxVolume"].Value <int>();
                                var mute         = info["mute"].Value <bool>();

                                var control =
                                    _volumeControls.Cast <SonyBraviaVolumeControl>()
                                    .FirstOrDefault(c => c.TargetType == type);

                                if (control == null)
                                {
                                    continue;
                                }

                                control.VolumeMin     = minLevel;
                                control.VolumeMax     = maxLevel;
                                control.InternalLevel = currentLevel;
                                control.InternalMute  = mute;
                            }
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }

                        #endregion
                    }

                    if (_connectionOk)
                    {
                        continue;
                    }

                    CloudLog.Info("{0} at {1} will now get status. Either failed previously or first connect",
                                  GetType().Name, DeviceAddressString);

                    #region Get Input and Source Schemes

                    var schemes = new List <string>();

                    response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getSchemeList", "1.0")
                        .Await();
                    if (response.Type != SonyBraviaResponseType.Success)
                    {
                        CloudLog.Error("{0} could not get SchemeList, {1}", GetType().Name, response.Type);
                        continue;
                    }

                    try
                    {
                        var info = response.Data.First() as JArray;

                        schemes.AddRange(info.Select(token => token as JObject).Select(o => o["scheme"].Value <string>()));

                        if (schemes.Count == 0)
                        {
                            CloudLog.Warn("Received empty array for {0} getSchemeList, moving to generate defaults",
                                          GetType().Name);
                            goto ErrorGettingInputs;
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                           response.RequestMethod);
                        continue;
                    }

                    var sources = new Dictionary <string, List <string> >();

                    foreach (var scheme in schemes)
                    {
                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getSourceList", "1.0",
                                                         new JObject
                        {
                            { "scheme", scheme }
                        }).Await();

                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("{0} could not get SourceList for scheme \"{1}\", {2}",
                                          GetType().Name, scheme, response.Type);
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JArray;

                            var list = new List <string>();
                            sources[scheme] = list;
                            list.AddRange(info.Select(token => token as JObject)
                                          .Select(o => o["source"].Value <string>()));
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }
                    }

                    var newContentList = new List <SonyContentSource>();

                    foreach (
                        var source in
                        sources.Where(k => k.Key != "fav").Select(k => k.Value).SelectMany(scheme => scheme))
                    {
                        response =
                            SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/avContent", "getContentList",
                                                         "1.0", new JObject
                        {
                            { "source", source }
                        }).Await();

                        if (response.Type != SonyBraviaResponseType.Success)
                        {
                            CloudLog.Warn("{0} could not get ConntentList for source \"{1}\", {2}",
                                          GetType().Name, source, response.Type);
                            continue;
                        }

                        try
                        {
                            var info = response.Data.First() as JArray;

                            foreach (var token in info)
                            {
                                try
                                {
                                    var input = new SonyContentSource(token as JObject);
                                    newContentList.Add(input);
                                    Debug.WriteInfo("Sony content source", input.ToString());
                                }
                                catch (Exception e)
                                {
                                    CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                                       response.RequestMethod);
                                }
                            }

                            goto FoundInputs;
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error in request: \"{0}\", {1}", response.RequestUri,
                                               response.RequestMethod);
                        }
                    }

ErrorGettingInputs:
                    CloudLog.Warn("Error getting input schemes for {0}, Generating default HDMI inputs", GetType().Name);
                    _availableSources = new List <SonyContentSource>()
                    {
                        new SonyContentSource("extInput:hdmi?port=1", "HDMI 1", 0),
                        new SonyContentSource("extInput:hdmi?port=2", "HDMI 2", 1),
                        new SonyContentSource("extInput:hdmi?port=3", "HDMI 3", 2),
                        new SonyContentSource("extInput:hdmi?port=4", "HDMI 4", 3)
                    };
                    goto InputsDone;

FoundInputs:
                    _availableSources = newContentList;

InputsDone:
                    Debug.WriteSuccess("Available inputs");
                    foreach (var source in _availableSources)
                    {
                        Debug.WriteNormal(source.ToString());
                    }

                    #endregion

                    _connectionOk = true;
                }
                catch (Exception e)
                {
                    CloudLog.Error("Error in {0}, message = {1}", Thread.CurrentThread.Name, e.Message);
                }
            }

            return(null);
        }
Example #22
0
        private object SystemThreadProcess(object userSpecific)
        {
            try
            {
                while (true)
                {
                    if (_userPrompts.Count == 0)
                    {
                        _systemWait.Wait(2000);
                    }

                    if (_programStopping)
                    {
                        return(null);
                    }

                    if (_userPrompts.Count == 0)
                    {
                        goto CheckTimers;
                    }

                    try
                    {
                        var prompts = _userPrompts.ToArray();

                        // We have queued prompts that aren't showing as current system prompts
                        if (prompts.Any(p => p.State == PromptState.Queued) &&
                            !prompts.Any(p => p.State == PromptState.Shown && p.Room == null))
                        {
                            //Debug.WriteInfo("Prompts queued! System {0}, Room {1}",
                            //    _userPrompts.Count(p => p.State == PromptState.Queued && p.Room == null),
                            //    _userPrompts.Count(p => p.State == PromptState.Queued && p.Room != null));

                            // Look for any system prompts (not specific to a room)
                            var prompt = prompts.FirstOrDefault(p => p.State == PromptState.Queued && p.Room == null);

                            if (prompt != null)
                            {
                                var roomPrompts = prompts.Where(p => p.State == PromptState.Shown && p.Room != null);

                                // Close any active room prompts and reset to queue as system will override

                                var pArray = roomPrompts as UserPrompt[] ?? roomPrompts.ToArray();
                                foreach (var roomPrompt in pArray)
                                {
                                    roomPrompt.State = PromptState.Queued;
                                }

                                if (pArray.Any())
                                {
                                    Thread.Sleep(200);
                                }

                                prompt.State = PromptState.Shown;

                                //Debug.WriteInfo("Showing system prompt on all UIs!");

                                foreach (var uiController in UIControllers)
                                {
                                    uiController.ShowPrompt(prompt);
                                }
                            }

                            else
                            {
                                // No system prompts to show so we can show any room prompts

                                foreach (var room in Rooms)
                                {
                                    var room1 = room;

                                    // Already showing a prompt in this room ... skip the room
                                    if (_userPrompts.Any(p => p.State == PromptState.Shown && p.Room == room1))
                                    {
                                        continue;
                                    }

                                    prompt = prompts.FirstOrDefault(
                                        p => p.State == PromptState.Queued && p.Room == room1);

                                    if (prompt != null && prompt.State != PromptState.Cancelled)
                                    {
                                        prompt.State = PromptState.Shown;

                                        foreach (var uiController in UIControllers.ForRoom(room1))
                                        {
                                            uiController.ShowPrompt(prompt);
                                        }
                                    }
                                }
                            }
                        }

                        //if (prompts.Length > 0)
                        //    Debug.WriteInfo("Removing {0} expired prompts", prompts.Length);

                        foreach (var userPrompt in
                                 prompts.Where(p => p.State != PromptState.Queued && p.State != PromptState.Shown))
                        {
                            _userPromptsLock.Enter();
                            _userPrompts.Remove(userPrompt);
                            _userPromptsLock.Leave();
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e);
                        Thread.Sleep(1000);
                    }

CheckTimers:

                    if (!Booted)
                    {
                        continue;
                    }

                    if (SecondsSinceLastSystemTimerCallback > 10 && !_timersBrokenFlag)
                    {
                        _timersBrokenFlag = true;
                        CloudLog.Error(
                            "System Timer last checked in {0} seconds ago. Will reboot processor in 10 minutes if not fixed!!",
                            SecondsSinceLastSystemTimerCallback);
                    }
                    else if (SecondsSinceLastSystemTimerCallback > 600 && _timersBrokenFlag)
                    {
                        CloudLog.Error("Automatic reboot now!");
                        var response = string.Empty;
                        CrestronConsole.SendControlSystemCommand("REBOOT", ref response);
                    }
                    else if (_timersBrokenFlag && SecondsSinceLastSystemTimerCallback < 10)
                    {
                        _timersBrokenFlag = false;
                        CloudLog.Warn("System Timer checked in {0} seconds ago after a delay", SecondsSinceLastSystemTimerCallback);
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Unhandled Exception in SystemThreadProcess()!");
                return(null);
            }
        }
Example #23
0
        /// <summary>
        /// This thread callback will look through the received bytes and look for a delimeter.
        /// The default delimiter is byte value 13 (0x0d - CR). Override this function if you need a different delimiter.
        /// </summary>
        /// <remarks>
        /// This by default will also skip bytes with value 10 (0x0a - LF)
        /// </remarks>
        protected virtual object ReceiveBufferProcess(object obj)
        {
            Byte[] bytes     = new Byte[this.BufferSize];
            int    byteIndex = 0;

            while (true)
            {
                try
                {
                    byte b = rxQueue.Dequeue();

                    if (((TCPClient)obj).ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
                    {
#if DEBUG
                        CrestronConsole.PrintLine("{0}.ReceiveBufferProcess exiting thread, Socket.ClientStatus = {1}",
                                                  this.GetType().Name, ((TCPClient)obj).ClientStatus);
#endif
                        return(null);
                    }

                    // skip any LF chars
                    if (b == 10)
                    {
                    }
                    // If find byte = CR
                    else if (b == 13)
                    {
                        // Copy bytes to new array with length of packet and ignoring the CR.
                        Byte[] copiedBytes = new Byte[byteIndex];
                        Array.Copy(bytes, copiedBytes, byteIndex);

                        byteIndex = 0;

                        OnReceivedPacket(copiedBytes);

                        CrestronEnvironment.AllowOtherAppsToRun();
                        Thread.Sleep(10);
                        if (rxQueue.IsEmpty)
                        {
                            return(null);
                        }
                    }
                    else
                    {
                        if (byteIndex < this.BufferSize)
                        {
                            bytes[byteIndex] = b;
                            byteIndex++;
                        }
                        else
                        {
                            ErrorLog.Error("{0} - Buffer overflow error", GetType().ToString());

                            string lastBytes = string.Empty;
                            for (int bt = this.BufferSize - 51; bt < this.BufferSize - 1; bt++)
                            {
                                byte btVal = bytes[bt];
                                if (btVal > 32 && btVal <= 127)
                                {
                                    lastBytes = lastBytes + (char)btVal;
                                }
                                else
                                {
                                    lastBytes = lastBytes + @"\x" + btVal.ToString("X2");
                                }
                            }

                            ErrorLog.Notice("Last 50 bytes of buffer: \"{0}\"", lastBytes);
                            ErrorLog.Warn("The buffer was cleared as a result");
                            byteIndex = 0;
                        }
                    }
                }
                catch (Exception e)
                {
#if DEBUG
                    CrestronConsole.PrintLine("{0}.ReceiveBufferProcess {1}", this.GetType().Name, e.Message);
#endif
                    if (e.Message != "ThreadAbortException")
                    {
                        ErrorLog.Error("{0} - Error in thread: {1}, byteIndex = {2}", GetType().ToString(), e.Message, byteIndex);
                    }
                }
            }
        }
Example #24
0
        protected object ReceiveBufferProcess(object obj)
        {
            Byte[] bytes     = new Byte[1000];
            int    byteIndex = 0;

            while (true)
            {
                try
                {
                    byte b = RxQueue.Dequeue();

                    // If find byte = CR
                    if (b == 13)
                    {
                        // Copy bytes to new array with length of packet and ignoring the CR.
                        Byte[] copiedBytes = new Byte[byteIndex];
                        Array.Copy(bytes, copiedBytes, byteIndex);

                        byteIndex = 0;

                        int chk = 0;

                        for (int i = 1; i < (copiedBytes.Length - 1); i++)
                        {
                            chk = chk ^ copiedBytes[i];
                        }

                        if (chk == copiedBytes.Last())
                        {
#if DEBUG
                            //CrestronConsole.Print("NEC Rx: ");
                            //Tools.PrintBytes(copiedBytes, copiedBytes.Length);
#endif
                            if (ReceivedPacket != null)
                            {
                                ReceivedPacket(this, copiedBytes);
                            }
                            CrestronEnvironment.AllowOtherAppsToRun();
                        }
                        else
                        {
#if DEBUG
                            CrestronConsole.PrintLine("NEC Display Rx - Checksum Error");
#endif
                            ErrorLog.Error("NEC Display Rx - Checksum Error");
                        }
                    }
                    else
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        ErrorLog.Exception("Error in NEC Rx Thread Handler", e);
                    }
                }
            }
        }
Example #25
0
        private object ConnectionThreadProcess(object o)
        {
            try
            {
                while (true)
                {
                    var connectCount = 0;
                    while (_remainConnected && !Connected)
                    {
                        if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST)
                        {
                            Thread.Sleep(5000);
                            continue;
                        }

                        connectCount++;

                        var result = _client.ConnectToServer();
                        if (result == SocketErrorCodes.SOCKET_OK)
                        {
                            CrestronConsole.PrintLine("{0} connected to {1}", GetType().Name,
                                                      _client.AddressClientConnectedTo);

                            try
                            {
                                OnConnect();
                                OnStatusChanged(SocketStatusEventType.Connected);
                            }
                            catch (Exception e)
                            {
                                CloudLog.Exception(e);
                            }
                            break;
                        }

                        if (connectCount <= 2 || connectCount > 5)
                        {
                            continue;
                        }
                        if (connectCount == 5)
                        {
                            CloudLog.Error("{0} failed to connect to address: {1}, will keep trying in background",
                                           GetType().Name, _client.AddressClientConnectedTo);
                        }
                        CrestronEnvironment.AllowOtherAppsToRun();
                    }

                    _adapterType = _client.EthernetAdapter;

                    while (true)
                    {
                        var dataCount = _client.ReceiveData();

                        if (dataCount <= 0)
                        {
                            CrestronConsole.PrintLine("{0} Disconnected!", GetType().Name);

                            try
                            {
                                OnStatusChanged(SocketStatusEventType.Disconnected);
                                OnDisconnect();
                            }
                            catch (Exception e)
                            {
                                CloudLog.Exception(e);
                            }

                            if (_remainConnected)
                            {
                                Thread.Sleep(2000);

                                if (_client.ClientStatus == SocketStatus.SOCKET_STATUS_LINK_LOST)
                                {
                                    CloudLog.Warn("{0} Ethernet Link Lost! - sleeping thread until back up", GetType().Name);
                                }
                                break;
                            }

                            CrestronConsole.PrintLine("Exiting {0}", Thread.CurrentThread.Name);
                            return(null);
                        }

                        //CrestronConsole.PrintLine("{0} {1} bytes in buffer", GetType().Name, dataCount);

                        try
                        {
                            OnReceive(_client.IncomingDataBuffer, dataCount);
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e);
                        }

                        CrestronEnvironment.AllowOtherAppsToRun();
                        Thread.Sleep(0);
                    }
                }
            }
            catch (Exception e)
            {
                if (_remainConnected)
                {
                    CloudLog.Exception("Error in handler thread while connected / connecting", e);
                }
                return(null);
            }
        }
Example #26
0
        private object ReceiveBufferProcess(object obj)
        {
            var bytes      = new Byte[1000];
            var byteIndex  = 0;
            var dataLength = 0;

            CloudLog.Info("Started {0}", Thread.CurrentThread.Name);

            while (true)
            {
                try
                {
                    var b = _rxQueue.Dequeue();

                    if (_programStopping)
                    {
                        return(null);
                    }

                    if (b == 0xAA)
                    {
                        byteIndex  = 0;
                        dataLength = 0;
                    }
                    else
                    {
                        byteIndex++;
                    }

                    bytes[byteIndex] = b;
                    if (byteIndex == 3)
                    {
                        dataLength = bytes[byteIndex];
                    }

                    if (byteIndex == (dataLength + 4))
                    {
                        int chk = bytes[byteIndex];

                        var test = 0;
                        for (var i = 1; i < byteIndex; i++)
                        {
                            test = test + bytes[i];
                        }

                        if (chk == (byte)test)
                        {
                            var copiedBytes = new byte[byteIndex];
                            Array.Copy(bytes, copiedBytes, byteIndex);
                            if (ReceivedPacket != null)
                            {
                                ReceivedPacket(this, copiedBytes);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
#if DEBUG
                        CrestronConsole.Print("Error in Samsung Rx: {0}",
                                              Tools.GetBytesAsReadableString(bytes, 0, byteIndex, false));
#endif
                        CloudLog.Error("Error in {0} TX Thread", GetType().Name);
                    }
                }

                CrestronEnvironment.AllowOtherAppsToRun();
            }
        }
Example #27
0
        private static object UploadProcess(object userSpecific)
        {
            Notice("CloudLog UploadProcess Started");

            while (true)
            {
                CrestronEnvironment.AllowOtherAppsToRun();

                if (_linkDown && !_programEnding)
                {
                    Thread.Sleep(60000);
                }
                else if (!_linkDown)
                {
                    try
                    {
                        var entries = PendingLogs.Take(50);

                        try
                        {
#if DEBUG
                            //CrestronConsole.PrintLine("Updating autodiscovery query...");
#endif
                            var query = EthernetAutodiscovery.Query();

#if DEBUG
                            //CrestronConsole.PrintLine("Autodiscovery {0}", query);
#endif
                            if (query ==
                                EthernetAutodiscovery.eAutoDiscoveryErrors.AutoDiscoveryOperationSuccess)
                            {
                                var adresults = EthernetAutodiscovery.DiscoveredElementsList;
#if DEBUG
                                //CrestronConsole.PrintLine("Found {0} devivces:", adresults.Count);
#endif
                                foreach (var adresult in adresults)
                                {
                                    //CrestronConsole.PrintLine("{0}, {1}, {2}", adresult.IPAddress,
                                    //adresult.HostName, adresult.DeviceIdString);
                                }
                            }
#if DEBUG
                            //CrestronConsole.PrintLine("CloudLog uploading to cloud...");
#endif

                            var contents = Post("submit_logs", entries);
                            var data     = JObject.Parse(contents);
#if DEBUG
                            //CrestronConsole.PrintLine("CloudLog client response: {0}", data["status"].Value<string>());
#endif
                            var results = data["results"];
                            foreach (var id in results.Select(result => result["id"].Value <string>()))
                            {
                                InternalDictionary[id].CloudId = id;
                            }
                        }
                        catch (Exception e)
                        {
                            Error("Error with CloudLog upload process, {0}", e.Message);
                            if (_programEnding)
                            {
                                return(null);
                            }
                            CrestronConsole.PrintLine("CloudLog could not upload to cloud service. {0} items pending",
                                                      PendingLogs.Count);
                            Thread.Sleep(60000);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorLog.Error("Error in CloudLog.PostToCloudProcess, {1}", e.Message);
                    }
                }

                if (_programEnding)
                {
                    return(null);
                }

                if (PendingLogs.Count == 0)
                {
                    UploadEvent.Wait(60000);
                }
            }
        }
Example #28
0
        protected override object ReceiveThreadProcess(object o)
        {
            Byte[] bytes     = new Byte[this.BufferSize];
            int    byteIndex = 0;

            while (this.ProgramRunning && this.Status == SocketStatus.SOCKET_STATUS_CONNECTED)
            {
                try
                {
                    byte b = ReceiveQueue.Dequeue();

                    // If find byte = CR
                    if (b == 13)
                    {
                        // check the next byte may also be 13 in which this one maybe the checksum
                        if (ReceiveQueue.Peek() == 13)
                        {
                            b = ReceiveQueue.Dequeue();
                            bytes[byteIndex] = b;
                            byteIndex++;
                        }

                        // Copy bytes to new array with length of packet and ignoring the CR.
                        Byte[] copiedBytes = new Byte[byteIndex];
                        Array.Copy(bytes, copiedBytes, byteIndex);

                        byteIndex = 0;

                        int chk = 0;

                        for (int i = 1; i < (copiedBytes.Length - 1); i++)
                        {
                            chk = chk ^ copiedBytes[i];
                        }
#if DEBUG
                        CrestronConsole.Print("NEC Rx: ");
                        Tools.PrintBytes(copiedBytes, copiedBytes.Length, false);
#endif
                        if (copiedBytes.Length > 0 && chk == (int)copiedBytes.Last())
                        {
                            if (this.ReceivedData != null)
                            {
                                this.ReceivedData(this, copiedBytes);
                            }
                        }
                        else if (copiedBytes.Length > 0)
                        {
                            ErrorLog.Warn("NEC Display Rx: \"{0}\"", Tools.GetBytesAsReadableString(copiedBytes, copiedBytes.Length, true));
                            ErrorLog.Warn("NEC Display Rx - Checksum Error, chk = 0x{0}, byteIndex = {1}, copiedBytes.Length = {2}",
                                          chk.ToString("X2"), byteIndex, copiedBytes.Length);
#if DEBUG
                            CrestronConsole.PrintLine("NEC Display Rx - Checksum Error, chk = 0x{0}, byteIndex = {1}, copiedBytes.Length = {2}",
                                                      chk.ToString("X2"), byteIndex, copiedBytes.Length);

                            CrestronConsole.PrintLine("rxQueue.Peek() = {0}", ReceiveQueue.Peek());
#endif
                        }

                        if (ReceiveQueue.IsEmpty)
                        {
                            break;
                        }
                    }
                    else
                    {
                        bytes[byteIndex] = b;
                        byteIndex++;
                    }

                    CrestronEnvironment.AllowOtherAppsToRun();
                    Thread.Sleep(0);
                }
                catch (Exception e)
                {
                    ErrorLog.Error("{0} - Error in ReceiveThreadProcess, {1}", this.GetType().Name, e.Message);
                    break;
                }
            }

            return(null);
        }
Example #29
0
        protected override object ReceiveBufferProcess(object obj)
        {
            Byte[] bytes     = new Byte[50];
            int    byteIndex = 0;

            while (true)
            {
                try
                {
                    Byte b = rxQueue.Dequeue();

                    if (((TCPClient)obj).ClientStatus != SocketStatus.SOCKET_STATUS_CONNECTED)
                    {
#if DEBUG
                        CrestronConsole.PrintLine("{0}.ReceiveBufferProcess exiting thread, Socket.ClientStatus = {1}",
                                                  this.GetType().Name, ((TCPClient)obj).ClientStatus);
#endif
                        return(null);
                    }

                    if (b == 2)
                    {
                        byteIndex        = 0;
                        bytes[byteIndex] = b;
                    }
                    else if (b == 3)
                    {
                        byteIndex++;
                        bytes[byteIndex] = b;

                        Byte[] processedBytes = new Byte[50];
                        int    newIndex       = 0;
                        for (int i = 0; i <= byteIndex; i++)
                        {
                            if (bytes[i] == 27)
                            {
                                i++;
                                int value = bytes[i];
                                value = value - 128;
                                processedBytes[newIndex] = (byte)value;
                            }
                            else
                            {
                                processedBytes[newIndex] = bytes[i];
                            }
                            newIndex++;
                        }

                        Byte[] copiedBytes = new Byte[newIndex];
                        Array.Copy(processedBytes, copiedBytes, newIndex);

                        byteIndex = 0;
                        OnReceivedPacket(copiedBytes);

                        CrestronEnvironment.AllowOtherAppsToRun();
                    }
                    else
                    {
                        byteIndex++;
                        bytes[byteIndex] = b;
                    }
                }
                catch (Exception e)
                {
                    if (e.Message != "ThreadAbortException")
                    {
                        ErrorLog.Error("{0} - Error in thread: {1}, byteIndex = {2}", GetType().ToString(), e.Message, byteIndex);
                    }
                }
            }
        }
Example #30
0
        private object DispatchThreadProcess(object userSpecific)
        {
            while (!RequestQueue.IsEmpty)
            {
                var request  = RequestQueue.Dequeue();
                var callback = Callbacks[request];

                Lock.Enter();
                Callbacks.Remove(request);
                Lock.Leave();
#if DEBUG
                var ready = true;
#endif
                while (_client.ProcessBusy)
                {
#if DEBUG
                    if (ready)
                    {
                        //CrestronConsole.PrintLine("Waiting for Client...");
                        ready = false;
                    }
#endif
                    CrestronEnvironment.AllowOtherAppsToRun();
                }
#if DEBUG
                if (!ready)
                {
                    ready = true;
                    //CrestronConsole.PrintLine("Client Ready...");
                }
                CrestronConsole.PrintLine("Dispatching request...");
#endif
                try
                {
                    var r = _client.Dispatch(request.Request);
#if DEBUG
                    CrestronConsole.PrintLine("Received response, {0}, {1} bytes", r.Code, r.ContentLength);
#endif
                    var response = new CodecResponse(request, r);

                    if (response.Code == 401)
                    {
                        StartSession();
                    }

                    try
                    {
                        callback(response);
                    }
                    catch (Exception e)
                    {
                        CloudLog.Exception(e);
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e);
                }
            }

            return(null);
        }