Exemple #1
0
        internal void UpdateInfo(JToken data)
        {
#if DEBUG
            CrestronConsole.PrintLine("Updated data for IPTV Receiver...");
            CrestronConsole.PrintLine(data.ToString(Formatting.Indented));
#endif
            Name       = data["name"].Value <string>();
            Location   = data["location"].Value <string>();
            MacAddress = data["mac"].Value <string>();
            try
            {
                IpAddress = data["ip"].Value <string>();
            }
            catch (Exception e)
            {
                IpAddress = data["address"].Value <string>();
            }
            finally
            {
                if (string.IsNullOrEmpty(IpAddress))
                {
                    CloudLog.Error(
                        "Could not parse Device hostname / address from data in {0}.UpdateInfo(JToken data)",
                        GetType().Name);
                }
            }
        }
Exemple #2
0
        public void SetVolume(int volumeLevel)
        {
            var json = string.Format("{{ \"params\": {{ \"receivervolume\": {0} }} }}", volumeLevel);

            PostRequest("/cgi-bin/json_xfer", json, (userobj, error) =>
            {
                if (error != HTTP_CALLBACK_ERROR.COMPLETED || userobj == null)
                {
                    CheckComms(false);
                    return;
                }

                try
                {
                    var data = JToken.Parse(userobj.ContentString);
                    //#if DEBUG
                    CrestronConsole.PrintLine("{0} received response:", GetType().Name);
                    CrestronConsole.PrintLine(data.ToString(Formatting.Indented));
                    //#endif
                    CheckComms(true);
                }
                catch (Exception e)
                {
                    //#if DEBUG
                    CrestronConsole.PrintLine(userobj.ContentString);
                    //#endif
                    CloudLog.Error("Error in {0}.SetVolume(int volumeLevel), {1}", GetType().Name, e.Message);

                    CheckComms(false);
                }
            });
        }
Exemple #3
0
        public void SetCurrentMode(ReceiverMode mode)
        {
            var json = string.Format("{{ \"params\": {{ \"currentMode\": \"{0}\" }} }}", mode.ToString().ToLower());

            Mode = mode;

            PostRequest("/cgi-bin/json_xfer", json, (userobj, error) =>
            {
                if (error != HTTP_CALLBACK_ERROR.COMPLETED || userobj == null)
                {
                    CheckComms(false);
                    return;
                }

                try
                {
                    var data = JToken.Parse(userobj.ContentString);
#if DEBUG
                    CrestronConsole.PrintLine("{0} received response:", GetType().Name);
                    CrestronConsole.PrintLine(data.ToString(Formatting.Indented));
#endif
                    CheckComms(true);
                }
                catch (Exception e)
                {
#if DEBUG
                    CrestronConsole.PrintLine(userobj.ContentString);
#endif
                    CloudLog.Error("Error in {0}.SetCurrentMode(ReceiverMode mode), {1}", GetType().Name, e.Message);

                    CheckComms(false);
                }
            });
        }
Exemple #4
0
        public FireAlarmMonitorSystem(CrestronControlSystem controlSystem) : base(controlSystem)
        {
            try
            {
                if (controlSystem.NumberOfVersiPorts > 0)
                {
                    controlSystem.VersiPorts[1].Register();
                    _fireAlarmMonitor = new FireAlarmMonitor(9002, 20, controlSystem.VersiPorts[1]);
                    return;
                }

                if (controlSystem.NumberOfDigitalInputPorts > 0)
                {
                    controlSystem.DigitalInputPorts[1].Register();
                    _fireAlarmMonitor = new FireAlarmMonitor(9002, 20, controlSystem.DigitalInputPorts[1]);
                    return;
                }

                CloudLog.Error("Could not setup fire alarm interface! No io ports available");
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
Exemple #5
0
        public uint AddItem(object linkedObject, bool holdOffSettingListSize)
        {
            if (_count == MaxNumberOfItems)
            {
                CloudLog.Error("Cannot add item to {0}, No more items available!, count = {1}, max = {2}",
                               GetType().Name, _count, MaxNumberOfItems);
                return(0);
            }

            _count++;

            var item = this[_count];

            item.Show();
            item.Enable();
            item.Feedback     = false;
            item.LinkedObject = linkedObject;

            if (!holdOffSettingListSize)
            {
                SetNumberOfItems(_count);
            }

            return(_count);
        }
Exemple #6
0
        public override void SetInput(DisplayDeviceInput input)
        {
            if (_availableInputs.Contains(input))
            {
                switch (input)
                {
                case DisplayDeviceInput.HDMI1:
                    _requestedInputValue = "HDMI";
                    break;

                case DisplayDeviceInput.DVI:
                    _requestedInputValue = "D-RGB";
                    break;

                case DisplayDeviceInput.VGA:
                    _requestedInputValue = "A-RGB2";
                    break;

                case DisplayDeviceInput.HDBaseT:
                    _requestedInputValue = "HDBT";
                    break;
                }

                _socket.Send(string.Format("INPUT={0}", _requestedInputValue));
                _socket.Send("GET=INPUT");
            }
            else
            {
                CloudLog.Error("{0} does not have the option of input: {1}", this, input);
            }
        }
Exemple #7
0
        internal QsysResponse Request(string method, object args)
        {
            if (Thread.CurrentThread.ThreadType == Thread.eThreadType.SystemThread)
            {
                throw new Exception("Cannot call QsysCore.Request synchronously in system thread!");
            }
            var request = new QsysRequest(_socket, method, args);

            //CloudLog.Debug("{0}.Request(), ID = {1}", GetType().Name, request.Id);
            _awaitingEventsLocked.Enter();
            _awaitingEvents[request.Id] = new CEvent(true, false);
            _awaitingEventsLocked.Leave();
            _socket.SendRequest(request);
            var result = _awaitingEvents[request.Id].Wait(30000);

            _awaitingEvents[request.Id].Dispose();
            _awaitingEventsLocked.Enter();
            _awaitingEvents.Remove(request.Id);
            _awaitingEventsLocked.Leave();
            if (!result)
            {
                CloudLog.Error("{0} Request Time Out, Request: {1}, ID {2}", GetType().Name, request.Method, request.Id);
                throw new TimeoutException("Request did not process a response in suitable time");
            }
            var response = _awaitingResponses[request.Id];

            _awaitingResponsesLocked.Enter();
            _awaitingResponses.Remove(request.Id);
            _awaitingResponsesLocked.Leave();
            return(response);
        }
Exemple #8
0
        internal virtual void UpdateProperties(Dictionary <string, Dictionary <string, string> > properties)
        {
            try
            {
                foreach (var property in properties["gen"])
                {
                    switch (property.Key)
                    {
                    case "model":
                        Model = property.Value;
                        break;

                    case "state":
                        State = (DeviceState)Enum.Parse(typeof(DeviceState), property.Value, true);
                        break;

                    case "name":
                        Name = property.Value;
                        break;

                    case "uptime":
                        var timeMatch = Regex.Match(property.Value, @"(\d+)d:(\d+)h:(\d+)m:(\d+)s");
                        UpTime = TimeSpan.FromDays(int.Parse(timeMatch.Groups[1].Value))
                                 + TimeSpan.FromHours(int.Parse(timeMatch.Groups[2].Value))
                                 + TimeSpan.FromMinutes(int.Parse(timeMatch.Groups[3].Value))
                                 + TimeSpan.FromSeconds(int.Parse(timeMatch.Groups[4].Value));
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                CloudLog.Error("Error processing property values in {0}, {1}", GetType().Name, e.Message);
            }
        }
Exemple #9
0
        internal QsysRequest(JToken data)
        {
            try
            {
                if (data["method"] != null)
                {
                    Method = data["method"].Value <string>();

                    if (data["id"] != null)
                    {
                        Id = data["id"].Value <int>();
                    }

                    if (data["params"] != null)
                    {
                        Args = data["params"];
                    }

                    return;
                }

                CloudLog.Error("Error processing {0} from data string", GetType().Name);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
Exemple #10
0
        /// <summary>
        /// Create an instance of a QsysCore
        /// </summary>
        /// <param name="deviceAddresses">The hostnames or ip addresses of the core(s)</param>
        /// <param name="port">Override the default TCP port of 1710</param>
        /// <param name="name"></param>
        public QsysCore(IList <string> deviceAddresses, string name, int port)
        {
            _name = name;
            try
            {
                _socket = new QsysSocket(deviceAddresses, port, name);
                _socket.StatusChanged += (client, status) =>
                {
                    _initialized        = status != SocketStatus.SOCKET_STATUS_CONNECTED;
                    DeviceCommunicating = status == SocketStatus.SOCKET_STATUS_CONNECTED;
                };

                _socket.RequestReceived  += SocketOnRequestReceived;
                _socket.ResponseReceived += SocketOnResponseReceived;
                CloudLog.Debug("{0} instance created with address(es) \"{1}\" port {2}", GetType().Name,
                               String.Join(",", deviceAddresses.ToArray()), port);
                CrestronConsole.AddNewConsoleCommand(parameters => DefaultChangeGroup.Invalidate(), "QSysUpdateAll",
                                                     "Invalidate the default change group in the core",
                                                     ConsoleAccessLevelEnum.AccessOperator);
            }
            catch (Exception e)
            {
                CloudLog.Error("Error in {0}.ctor(), {1}", GetType().Name, e.Message);
            }
        }
Exemple #11
0
        internal override void UpdateProperties(Dictionary <string, Dictionary <string, string> > properties)
        {
            base.UpdateProperties(properties);

            try
            {
                if (properties.ContainsKey("hdmiInput"))
                {
                    HdmiInput.UpdateFromProperties(properties["hdmiInput"]);
                }
            }
            catch (Exception e)
            {
                CloudLog.Error("Error processing property values in {0}, {1}", GetType().Name, e.Message);
            }

#if DEBUG
            CrestronConsole.PrintLine("Updated {0}, \"{1}\": State: {2}", GetType().Name, Name, State);
            if (State != DeviceState.Up)
            {
                return;
            }
            CrestronConsole.PrintLine("   Uptime: {0}", UpTime.ToPrettyFormat());
            CrestronConsole.PrintLine("   HdmiInput: {0}{1}{2}",
                                      HdmiInput.Connected ? "Connected" : "Disconnected",
                                      HdmiInput.Connected ? " " + HdmiInput.Format : "",
                                      HdmiInput.Connected ? " HDCP: " + HdmiInput.Hdcp : "",
                                      HdmiInput.Connected ? " HDMI 2.0: " + HdmiInput.Hdmi2Point0 : "");
#endif
        }
Exemple #12
0
        private void SocketOnReceivedString(string receivedString)
        {
            DeviceCommunicating = true;
            var match = Regex.Match(receivedString, @"^([\w-]+) ([\w/]+)(?:(\.|:| )(.+))?$");

            if (!match.Success)
            {
                CloudLog.Error("Error processing line from lightware: \"{0}\"", receivedString);
                return;
            }
            var prefix  = match.Groups[1].Value;
            var path    = match.Groups[2].Value;
            var context = match.Groups[4].Value;

            Debug.WriteNormal(Debug.AnsiBlue + prefix + " " + Debug.AnsiPurple + path + Debug.AnsiCyan +
                              match.Groups[3].Value + Debug.AnsiGreen + context + Debug.AnsiReset);

            switch (prefix)
            {
            case "CHG":
                OnReceiveChange(path, context);
                break;

            case "pr":
                OnReceiveProperty(path, context, true);
                break;

            case "pw":
                OnReceiveProperty(path, context, false);
                break;
            }
        }
Exemple #13
0
        internal ChristieComPortHandler(IComPortDevice comPort)
        {
            _comPort = comPort;

            var port = _comPort as CrestronDevice;

            if (port != null && !port.Registered)
            {
                var result = port.Register();
                if (result != eDeviceRegistrationUnRegistrationResponse.Success)
                {
                    CloudLog.Error("Could not register {0}, {1}", port, result);
                }
            }

            _comPort.SetComPortSpec(new ComPort.ComPortSpec()
            {
                BaudRate          = ComPort.eComBaudRates.ComspecBaudRate115200,
                DataBits          = ComPort.eComDataBits.ComspecDataBits8,
                StopBits          = ComPort.eComStopBits.ComspecStopBits1,
                Parity            = ComPort.eComParityType.ComspecParityNone,
                Protocol          = ComPort.eComProtocolType.ComspecProtocolRS232,
                ReportCTSChanges  = false,
                HardwareHandShake = ComPort.eComHardwareHandshakeType.ComspecHardwareHandshakeNone,
                SoftwareHandshake = ComPort.eComSoftwareHandshakeType.ComspecSoftwareHandshakeNone,
            });

            _bytes     = new byte[1000];
            _byteIndex = 0;

            _comPort.SerialDataReceived += ComPortOnSerialDataReceived;
        }
Exemple #14
0
        public IEnumerable <Booking> GetBookings()
        {
            var cmd = new CodecCommand("Bookings", "List");

            cmd.Args.Add("Days", 1);
            cmd.Args.Add("DayOffset", 0);

            var bookings = new List <Booking>();

            var response = Codec.SendCommand(cmd);

            if (response.Code != 200)
            {
                CloudLog.Error("Error getting bookings search, Codec Responded with {0} code", response.Code);
                return(bookings);
            }

            var result = response.Xml.Element("Command").Element("BookingsListResult");

            Debug.WriteInfo("Bookings List");
            Debug.WriteNormal(Debug.AnsiPurple + result + Debug.AnsiReset);

            if (result.Attribute("status").Value == "Error")
            {
                var message = result.Element("Reason").Value;
                CloudLog.Error("Error getting bookings search: {0}", message);
                return(bookings);
            }

            bookings.AddRange(result.Elements("Booking").Select(data => new Booking(data)));

            return(bookings.ToArray());
        }
Exemple #15
0
        public override void SetInput(DisplayDeviceInput input)
        {
            if (_availableInputs.Contains(input))
            {
                _requestedInput = input;

                switch (input)
                {
                case DisplayDeviceInput.HDMI1:
                    Send('x', 'b', 0x90);
                    break;

                case DisplayDeviceInput.HDMI2:
                    Send('x', 'b', 0x91);
                    break;

                case DisplayDeviceInput.HDMI3:
                    Send('x', 'b', 0x92);
                    break;

                case DisplayDeviceInput.HDMI4:
                    Send('x', 'b', 0x93);
                    break;
                }
            }
            else
            {
                CloudLog.Error("{0} does not have the option of input: {1}", this, input);
            }
        }
Exemple #16
0
        public void Initialize()
        {
            if (_timer != null)
            {
                return;
            }

            _refreshCount = 60;

            CrestronEnvironment.ProgramStatusEventHandler += type =>
            {
                _programStopping = type == eProgramStatusEventType.Stopping;
                if (_programStopping)
                {
                    RequestQueue.Enqueue(null);
                }
            };

            _timer = new CTimer(specific =>
            {
                _refreshCount = _refreshCount - 1;

                try
                {
                    if (_refreshCount == 0 || !Receivers.Any())
                    {
                        Receivers.Discover();
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Error("Error getting receiver collection from AvediaServer, {0}", e.Message);
                }

                try
                {
                    if (_refreshCount == 0 || !Channels.Any())
                    {
                        Channels.UpdateChannels();
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Error("Error getting channel collection from AvediaServer, {0}", e.Message);
                }

                if (!_initialized)
                {
                    _initialized = true;
                    OnHasInitialized(this);
                }

                if (_refreshCount == 0)
                {
                    _refreshCount = 60;
                }
            }, null, 1000, (long)TimeSpan.FromMinutes(1).TotalMilliseconds);
        }
Exemple #17
0
        public void Initialize()
        {
            if (_initialized)
            {
                return;
            }

            var port = _comPort as PortDevice;

            if (port != null && !port.Registered)
            {
                var result = port.Register();
                if (result != eDeviceRegistrationUnRegistrationResponse.Success)
                {
                    CloudLog.Error("Could not register {0} with ID {1}, {2}", port.GetType().Name, port.ID, result);
                }
            }

            var spec = new ComPort.ComPortSpec()
            {
                BaudRate          = ComPort.eComBaudRates.ComspecBaudRate9600,
                DataBits          = ComPort.eComDataBits.ComspecDataBits8,
                Parity            = ComPort.eComParityType.ComspecParityNone,
                StopBits          = ComPort.eComStopBits.ComspecStopBits1,
                Protocol          = ComPort.eComProtocolType.ComspecProtocolRS232,
                HardwareHandShake = ComPort.eComHardwareHandshakeType.ComspecHardwareHandshakeNone,
                SoftwareHandshake = ComPort.eComSoftwareHandshakeType.ComspecSoftwareHandshakeNone,
                ReportCTSChanges  = false
            };

            _comPort.SetComPortSpec(spec);

            _comPort.SerialDataReceived += (device, args) =>
            {
                var bytes = args.SerialData.ToByteArray();
#if DEBUG
                Debug.WriteSuccess("Samsung Rx",
                                   Debug.AnsiBlue + Tools.GetBytesAsReadableString(bytes, 0, bytes.Length, false) +
                                   Debug.AnsiReset);
#endif
                foreach (var b in bytes)
                {
                    _rxQueue.Enqueue(b);
                }

                if (_rxThread != null && _rxThread.ThreadState == Thread.eThreadStates.ThreadRunning)
                {
                    return;
                }
                _rxThread = new Thread(ReceiveBufferProcess, null, Thread.eThreadStartOptions.CreateSuspended)
                {
                    Priority = Thread.eThreadPriority.UberPriority,
                    Name     = string.Format("Samsung Display ComPort - Rx Handler")
                };
                _rxThread.Start();
            };
            _initialized = true;
        }
        protected BaseUIController(SystemBase system, BasicTriListWithSmartObject device, RoomBase room)
            : base(system, device, room)
        {
            try
            {
                var assembly   = Assembly.GetExecutingAssembly();
                var streamName =
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(n => n.Contains(".sgd") && n.Contains(device.Name)) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(
                        n => n.Contains(".sgd") && n.Contains("XPanel") && device is XpanelForSmartGraphics) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(
                        n => n.Contains(".sgd") && n.Contains("CrestronApp") && device is CrestronApp) ??
                    assembly.GetManifestResourceNames()
                    .FirstOrDefault(n => n.Contains(".sgd"));
                CloudLog.Info("Loading Smartgraphics for {0} ID {1}, File: {2}", GetType().Name, Id, streamName);
                var stream = assembly.GetManifestResourceStream(streamName);
                LoadSmartObjects(stream);
            }
            catch
            {
                CloudLog.Error("Could not load SGD file for {0}", this);
            }

            _roomNameLabel          = new UILabel(this, Serials.RoomName);
            _roomContactNumberLabel = new UILabel(this, Serials.RoomContactNumber);

            _bootPage = new BootPageViewController(this, Digitals.PageBoot, null);

            var tswX60BaseClass = device as TswX60BaseClass;

            if (tswX60BaseClass != null)
            {
                tswX60BaseClass.ExtenderSystem2ReservedSigs.Use();
            }

            _restartingView = new ASubPage(this, Device.BooleanInput[Digitals.SubPageRestarting], string.Empty, TimeSpan.Zero);
            _restartingText = new UILabel(this, Serials.RestartingText)
            {
                Text = "System Restarting"
            };

            _homeButton = new UIButton(this, Digitals.HomeButton);
            _backButton = new UIButton(this, Digitals.BackButton)
            {
                VisibleJoin = Device.BooleanInput[Digitals.BackButtonVisible]
            };
            _backButton.Show();

            _homeButton.ButtonEvent += HomeButtonOnButtonEvent;

            _textEntryView = new TextFieldEntryViewController(this);

            _actionSheets[0] = new ActionSheetDefault(this);
        }
Exemple #19
0
        internal void FusionRegisterInternal()
        {
            var ipId = FusionShouldRegister();

            try
            {
                if (ipId > 0)
                {
                    IpIdFactory.Block(ipId, IpIdFactory.DeviceType.Fusion);
                    Fusion                         = new FusionRoom(ipId, System.ControlSystem, Name, Guid.NewGuid().ToString());
                    Fusion.Description             = "Fusion for " + Name;
                    Fusion.FusionStateChange      += OnFusionStateChange;
                    Fusion.OnlineStatusChange     += OnFusionOnlineStatusChange;
                    Fusion.FusionAssetStateChange += FusionOnFusionAssetStateChange;
                }
                else
                {
                    return;
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            try
            {
                FusionShouldRegisterUserSigs();
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            try
            {
                FusionShouldRegisterAssets();
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            try
            {
                var regResult = Fusion.Register();
                if (regResult != eDeviceRegistrationUnRegistrationResponse.Success)
                {
                    CloudLog.Error("Error registering fusion in room {0} with IpId 0x{1:X2}, result = {2}", Id, ipId,
                                   regResult);
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
Exemple #20
0
        private bool CheckIfNewVersion(Assembly appAssembly)
        {
            try
            {
                var runningVersion = appAssembly.GetName().Version;

                CloudLog.Info("Checking version of {0} to see if \"{1}\" is new", appAssembly.GetName().Name,
                              runningVersion);

                var filePath = string.Format("{0}\\{1}_version.info", AppStoragePath, appAssembly.GetName().Name);

                if (!File.Exists(filePath))
                {
                    using (var newFile = File.OpenWrite(filePath))
                    {
                        newFile.Write(runningVersion.ToString(), Encoding.UTF8);
                    }
                    CloudLog.Notice("Version file created at \"{0}\", app must be updated or new", filePath);
                    return(true);
                }

                bool appIsNewVersion;

                using (var file = new StreamReader(filePath, Encoding.UTF8))
                {
                    var contents = file.ReadToEnd().Trim();
                    var version  = new Version(contents);
                    appIsNewVersion = runningVersion.CompareTo(version) != 0;
                    if (appIsNewVersion)
                    {
                        CloudLog.Warn("APP UPDATED TO {0}", runningVersion.ToString());
                    }
                    else
                    {
                        CloudLog.Notice("App version remains as {0}", runningVersion.ToString());
                    }
                }

                if (appIsNewVersion)
                {
                    File.Delete(filePath);

                    using (var newFile = File.OpenWrite(filePath))
                    {
                        newFile.Write(runningVersion.ToString(), Encoding.UTF8);
                    }
                    CloudLog.Notice("Version file deleted and created at \"{0}\", with new version number", filePath);
                }

                return(appIsNewVersion);
            }
            catch (Exception e)
            {
                CloudLog.Error("Error checking if app is new version, returning true, {0}", e.Message);
                return(true);
            }
        }
Exemple #21
0
        public void GetStatus()
        {
            try
            {
                //CloudLog.Debug("{0}.GetStatus() for address {1}", GetType().Name, _address);
                if (string.IsNullOrEmpty(_address) && _firstAttempt)
                {
                    _firstAttempt = false;
                    CloudLog.Error("Error with Solstice Pod, no address set, please check config");
                    return;
                }
                var uri = string.Format("http://{0}/api/stats?password={1}", _address, _password);
#if DEBUG
                CloudLog.Debug("Gettiing .. " + uri);
#endif
                _client.GetAsync(uri, (response, error) =>
                {
                    try
                    {
                        if (error == HTTP_CALLBACK_ERROR.COMPLETED)
                        {
#if DEBUG
                            Debug.WriteNormal(Debug.AnsiPurple + response + Debug.AnsiReset);
#endif
                            var data            = JToken.Parse(response);
                            var info            = data["m_displayInformation"];
                            _displayName        = info["m_displayName"].Value <string>();
                            _productName        = info["m_productName"].Value <string>();
                            _productVarient     = info["m_productVariant"].Value <string>();
                            Name                = _productName + " " + _productVarient + " (" + _displayName + ")";
                            DeviceCommunicating = true;
                            return;
                        }
                    }
                    catch (Exception e)
                    {
                        CloudLog.Error("Error with response from Solstice Pod at \"{0}\", {1}", _address, e.Message);
                    }

                    if (DeviceCommunicating || _firstAttempt)
                    {
                        _firstAttempt = false;
                        CloudLog.Error("Error waiting for response from Solstice Pod at \"{0}\"", _address);
                        DeviceCommunicating = false;
                    }
                });
            }
            catch (Exception e)
            {
                if (DeviceCommunicating || _firstAttempt)
                {
                    _firstAttempt = false;
                    CloudLog.Error("Error calling request for Solstice Pod at \"{0}\", {1}", _address, e.Message);
                    DeviceCommunicating = false;
                }
            }
        }
Exemple #22
0
 private static void CallMethodForClient(string host, string method, uint clientId)
 {
     GetRequest((id, response) =>
     {
         if (response.Code != 200)
         {
             CloudLog.Error("Error trying method \"{0}\", Response code: {1}", method, response.Code);
         }
     }, host, method, clientId);
 }
Exemple #23
0
 public static void SetChannel(string host, uint clientId, uint channelNumber)
 {
     GetRequest((id, response) =>
     {
         if (response.Code != 200)
         {
             CloudLog.Error("Error trying to set channel, Response code: {0}", response.Code);
         }
     }, host, "SelectChannel", clientId, channelNumber);
 }
        private void Callback(HttpClientResponse response, HTTP_CALLBACK_ERROR error)
        {
            try
            {
                if (error != HTTP_CALLBACK_ERROR.COMPLETED)
                {
                    CloudLog.Warn("Cannot communicate with AvediaServer to discover receivers");
                    return;
                }

                if (response.Code != 200)
                {
                    CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code);
                    return;
                }

                var data = JArray.Parse(response.ContentString);
#if true
                Debug.WriteInfo(Debug.AnsiPurple + data.ToString(Formatting.Indented) + Debug.AnsiReset);
#endif
                foreach (
                    var device in
                    data.Where(
                        d => d["type"].Value <string>() == "Media Player" || d["type"].Value <string>() == "Receiver")
                    )
                {
                    if (this.Any(d => d.Id == device["id"].Value <string>()))
                    {
                        this[device["id"].Value <string>()].UpdateInfo(device);
                    }
                    else
                    {
                        Receiver receiver = null;
                        try
                        {
                            receiver = new Receiver(_server, device);
                        }
                        catch (Exception e)
                        {
                            CloudLog.Exception(e, "Error loading receiver object from data");
                        }
                        if (receiver == null)
                        {
                            continue;
                        }
                        _receivers.Add(receiver);
                        OnReceiverDiscovered(receiver, receiver.Id, receiver.Name);
                    }
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }
        }
Exemple #25
0
        private object SourceLoadProcess(object userSpecific)
        {
            var sources = userSpecific as SourceBase[];

            if (sources == null)
            {
                CloudLog.Error("Error in SourceLoadProcess(object userSpecific)");
                return(null);
            }

            _sourceChangeBusy = true;

            try
            {
                SourceLoadStarted(sources[1]);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            try
            {
                SourceLoadProcess(sources[0], sources[1]);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error loading source \"{0}\"", sources[1] != null ? sources[1].Name : "None");
            }

            try
            {
                if (Fusion != null)
                {
                    FusionShouldUpdateCoreParameters();
                }
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            _sourceChangeBusy = false;

            try
            {
                SourceLoadEnded();
            }
            catch (Exception e)
            {
                CloudLog.Exception(e);
            }

            return(null);
        }
Exemple #26
0
        public void StopRecording(int contentId, string name)
        {
            var requestData = new
            {
                name,
                schedule = new
                {
                    @stop = DateTime.Now,
                }
            };
            var json    = JToken.FromObject(requestData);
            var request = new ServerRequest(_server.HostNameOrIpAddress, "/api/content/recording/scheduled/" + contentId,
                                            json.ToString(), RequestType.Put,
                                            (response, error) =>
            {
                if (error != HTTP_CALLBACK_ERROR.COMPLETED)
                {
                    CloudLog.Warn("Cannot communicate with AvediaServer to get recordings");
                    OnRecordingsUpdated(new RecordingsUpdatedEventArgs
                    {
                        EventType     = RecordingUpdatedEventType.StopRecording,
                        RequestFailed = true,
                        FailReason    = "Could not get response from server"
                    });
                    return;
                }

                if (response.Code != 200)
                {
                    CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code);
                    OnRecordingsUpdated(new RecordingsUpdatedEventArgs
                    {
                        EventType     = RecordingUpdatedEventType.StopRecording,
                        RequestFailed = true,
                        FailReason    = "Server responded with " + response.Code + " error",
                    });
                    return;
                }

                var data = JToken.Parse(response.ContentString).First;

                var id = data["Id"].Value <int>();

                CloudLog.Error("{0} HttpResponse = {1}", GetType().Name, response.Code);
                OnRecordingsUpdated(new RecordingsUpdatedEventArgs
                {
                    EventType     = RecordingUpdatedEventType.StopRecording,
                    RequestFailed = false,
                    RecordingId   = id
                });
            });

            _server.QueueRequest(request);
        }
Exemple #27
0
        protected override void ActionPowerRequest(bool powerRequest)
        {
            if (_powerSetThread != null && _powerSetThread.ThreadState == Thread.eThreadStates.ThreadRunning)
            {
                if (powerRequest == RequestedPower)
                {
                    return;
                }
            }

            _powerSetThread = new Thread(specific =>
            {
                try
                {
                    var response =
                        SonyBraviaHttpClient.Request(_deviceAddress, _psk, "/sony/system", "setPowerStatus", "1.0",
                                                     new JObject
                    {
                        { "status", powerRequest }
                    }).Await();

                    if (response.Type == SonyBraviaResponseType.Success)
                    {
                        if (powerRequest && PowerStatus == DevicePowerStatus.PowerOff)
                        {
                            PowerStatus = DevicePowerStatus.PowerWarming;
                        }
                        else if (!powerRequest && PowerStatus == DevicePowerStatus.PowerOn)
                        {
                            PowerStatus = DevicePowerStatus.PowerCooling;
                        }
                    }
                    else if (response.Type == SonyBraviaResponseType.Failed)
                    {
                        CloudLog.Error("Could not set display power, Response = {0}, {1}", response.Type,
                                       response.Exception.Message);
                    }
                    else
                    {
                        CloudLog.Error("Could not set display power, Response = {0}", response.Type);
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error trying to set display power");
                    _connectionOk = false;
                }

                _checkWait.Set();

                return(null);
            }, null);
        }
        protected override void ReceivedResponse(TesiraResponse response)
        {
            if (response.CommandType != TesiraCommand.Get || response.OtherCommandElements.Any())
            {
                return;
            }

            var json = response.TryParseResponse();

            if (json == null)
            {
                CloudLog.Error("{0} could not parse {1} value from json message \"{2}\"", GetType().Name,
                               response.AttributeCode, response.Message);
                return;
            }

            try
            {
                switch (response.AttributeCode)
                {
                case TesiraAttributeCode.Label:
                    _label = response.TryParseResponse()["value"].Value <string>();
                    break;

                case TesiraAttributeCode.NumInputs:
                    _numberOfInputs = response.TryParseResponse()["value"].Value <uint>();
                    break;

                case TesiraAttributeCode.NumOutputs:
                    _numberOfOutputs = response.TryParseResponse()["value"].Value <uint>();
                    break;

                case TesiraAttributeCode.NumSources:
                    _numberOfSources = response.TryParseResponse()["value"].Value <uint>();
                    break;

                case TesiraAttributeCode.SourceSelection:
                    _sourceSelection = response.TryParseResponse()["value"].Value <uint>();
                    break;

                case TesiraAttributeCode.StereoEnable:
                    _stereroEnabled = response.TryParseResponse()["value"].Value <bool>();
                    OnInitialized();
                    break;
                }
            }
            catch (Exception e)
            {
                CloudLog.Error("{0} could not parse {1} value from json \"{2}\", {3}", GetType().Name,
                               response.AttributeCode, json.ToString(), e.Message);
            }
        }
Exemple #29
0
 /// <summary>
 /// Access to the controls registered to the component
 /// </summary>
 /// <param name="controlName">The name of the control</param>
 /// <returns>A QsysControl object</returns>
 public QsysControl this[string controlName]
 {
     get
     {
         if (Controls.ContainsKey(controlName))
         {
             return(Controls[controlName]);
         }
         CloudLog.Error("Qsys Component \"{0}\" does not contain control \"{1}\"",
                        Name, controlName);
         return(null);
     }
 }
Exemple #30
0
        /// <summary>
        /// Access a Named Component on the Core
        /// </summary>
        /// <param name="componentName"></param>
        /// <returns></returns>
        public ComponentBase this[string componentName]
        {
            get
            {
                if (_components.ContainsKey(componentName))
                {
                    return(_components[componentName]);
                }

                CloudLog.Error("QsysCore does not contain component \"{0}\"", componentName);
                return(null);
            }
        }