示例#1
0
        public static short GetAdapterIdForAddress(this IPAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }

            if (address.Equals(IPAddress.Broadcast) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.Loopback) || address.Equals(IPAddress.None) || address.IsIPv4Multicast())
            {
                return(-1);
            }

            var numAdapters = InitialParametersClass.NumberOfEthernetInterfaces;

            for (short ix = 0; ix < numAdapters; ++ix)
            {
                var addr   = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, ix);
                var mask   = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, ix);
                var ipAddr = IPAddress.Parse(addr);
                var ipMask = IPAddress.Parse(mask);

                if (address.IsInSameSubnet(ipAddr, ipMask))
                {
                    return(ix);
                }
            }

            return(CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter));
        }
        public FusionAssetBase Add(CrestronControlSystem controlSystem)
        {
            uint newId = 0;

            for (uint id = 1; id <= 249; id++)
            {
                if (!this.Fusion.Room.Fusion.FusionRoom.UserConfigurableAssetDetails.Contains(id))
                {
                    newId = id;
                    break;
                }
            }

            if (newId > 0)
            {
                this.Fusion.Room.Fusion.FusionRoom.AddAsset(eAssetType.StaticAsset, newId, controlSystem.ControllerPrompt,
                                                            "Control Processor", Guid.NewGuid().ToString());

                Assets[newId] = this.Fusion.Room.Fusion.FusionRoom.UserConfigurableAssetDetails[newId].Asset;

                ((FusionStaticAsset)Assets[newId]).AddSig(eSigType.String, 1, "IP Address", eSigIoMask.InputSigOnly);
                ((FusionStaticAsset)Assets[newId]).FusionGenericAssetSerialsAsset3.StringInput[1].StringValue
                    = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                                                                  CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter));

                return(Assets[newId]);
            }
            return(null);
        }
示例#3
0
        /// <summary>
        /// Create a CodecSshClient
        /// </summary>
        internal CiscoSshClient(string address, int port, string username, string password)
        {
            _address  = address;
            _port     = port;
            _username = username;
            _password = password;
            CrestronEnvironment.ProgramStatusEventHandler += type =>
            {
                _programRunning = type != eProgramStatusEventType.Stopping;
                if (_programRunning)
                {
                    return;
                }

                _threadWait.Set();
                _reconnect = false;

                if (!Connected)
                {
                    return;
                }

                CloudLog.Info("Program stopping, Sending bye to {0} at {1}", GetType().Name, _address);
                Send("bye");
            };
            _heartbeatId =
                CrestronEthernetHelper.GetEthernetParameter(
                    CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter));
        }
示例#4
0
文件: CloudLog.cs 项目: uxav/lib2
        private static string Post(string method, object args)
        {
            var system = new
            {
                mac_address = CrestronEthernetHelper.GetEthernetParameter(
                    CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)),
                ip_address = CrestronEthernetHelper.GetEthernetParameter(
                    CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)),
                host_name = CrestronEthernetHelper.GetEthernetParameter(
                    CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME,
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)),
                model    = InitialParametersClass.ControllerPromptName,
                version  = InitialParametersClass.FirmwareVersion,
                ram_free = SystemMonitor.RAMFree * 1000
            };

            var app = new
            {
                index                 = InitialParametersClass.ApplicationNumber,
                name                  = InitialParametersClass.ProgramIDTag,
                version               = _assembly.GetName().Version.ToString(),
                last_start_time       = _startupTime,
                build_date            = _programInfo["App Build Date"],
                programmer            = _programInfo["Programmer Name"],
                simpl_sharp_version   = _programInfo["SIMPLSharp Version"],
                include_4_dat_version = _programInfo["Include4.dat Version"]
            };

            var requestObject = new
            {
                method,
                @params     = args,
                project_key = _projectKey,
                system,
                app
            };

            var request = new HttpsClientRequest
            {
                RequestType   = RequestType.Post,
                ContentSource = ContentSource.ContentString,
                ContentString =
                    JsonConvert.SerializeObject(requestObject, Formatting.Indented, new IsoDateTimeConverter()),
                Header    = { ContentType = "application/json" },
                KeepAlive = false,
                Url       = new Crestron.SimplSharp.Net.Http.UrlParser(@"https://crestroncloudlogger.appspot.com/api")
            };

            using (var client = new HttpsClient {
                IncludeHeaders = false
            })
            {
                var response = client.Dispatch(request);
                CrestronConsole.PrintLine("Logger response: {0}", response.Code);
                CrestronConsole.PrintLine("Logger rx:\r\n{0}", response.ContentString);
                return(response.ContentString);
            }
        }
示例#5
0
        void CheckStatus(object o)
        {
            try
            {
                bool commsOk = false;
                try
                {
                    //#if DEBUG
                    CrestronConsole.PrintLine("CiscoCodec Sending Heatbeat...");
                    //#endif
                    CommandArgs args = new CommandArgs();
                    args.Add("ID", CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS,
                                                                               CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(this.FeedbackServer.AdapterForIPAddress)));
                    XDocument response = this.SendCommand("Peripherals/HeartBeat", args);
                    //#if DEBUG
                    try
                    {
                        if (response.Element("Command").Element("PeripheralsHeartBeatResult").Attribute("status").Value == "OK")
                        {
                            CrestronConsole.PrintLine("HeatBeat OK");
                        }
                        else
                        {
                            CrestronConsole.PrintLine("status = {0}", response.Element("Command").Element("PeripheralsHeartBeatResult").Attribute("status").Value);
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorLog.Exception("Error reading result from Heartbeat Send", e);
                    }
                    //#endif

                    this.DeviceCommunicating = true;
                    commsOk = true;
                }
                catch (Exception e)
                {
                    ErrorLog.Error("Error checking in with CiscoCodec, {0}", e.Message);
                    CrestronConsole.PrintLine("Error Sending CiscoCodec Heartbeat ...");
                    CrestronConsole.PrintLine(e.StackTrace);
                    CrestronConsole.PrintLine("Stopping CheckStatus Timer and calling CiscoCodec.Initialize()...");
                    this.DeviceCommunicating = false;
                    _CheckStatusTimer.Stop();
                    _CheckStatusTimer.Dispose();
                    this.Initialize();
                }

                if (commsOk && !this.FeedbackServer.Registered)
                {
                    ErrorLog.Warn("The CiscoCodec was not registered for feedback on CheckStatusThread. Codec could have unregistered itself due to Post errors or connectivity problems");
                    this.Registerfeedback();
                }
            }
            catch (Exception e)
            {
                ErrorLog.Exception("Error occured in CiscoCodec.CheckStatus() timer callback", e);
            }
        }
示例#6
0
        public TemplateEngine(Assembly assembly, string resourcePath, string title, bool loggedIn)
        {
            _templateContents = GetResourceContents(assembly, resourcePath);

            while (Regex.IsMatch(_templateContents, @"{% extends ([\.\w]+) %}"))
            {
                var contents = _templateContents;

                var block = GetResourceContents(assembly, Regex.Match(_templateContents, @"{% extends ([\.\w]+) %}").Groups[1].Value);

                _templateContents = Regex.Replace(block, @"{{ block_content }}",
                                                  match => Regex.Replace(contents, @"{% extends ([\.\w]+) %}", string.Empty));
            }

            _context = new Dictionary <string, object>
            {
                { "page_title", title },
                { "processor_prompt", InitialParametersClass.ControllerPromptName },
                {
                    "processor_ip_address",
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                        CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                            EthernetAdapterType.EthernetLANAdapter))
                },
                {
                    "processor_hostname",
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME,
                        CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                            EthernetAdapterType.EthernetLANAdapter)).ToUpper()
                },
                { "authentication_enabled", InitialParametersClass.IsAuthenticationEnabled },
                { "login_logout_button_name", loggedIn ? "Logout" : "Login" },
                { "login_logout_link", loggedIn ? "/logout" : "/login" }
            };

            var domain = CrestronEthernetHelper.GetEthernetParameter(
                CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME,
                CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                    EthernetAdapterType.EthernetLANAdapter));

            domain = domain.Length > 0 ? domain : "local";
            _context.Add("processor_domain", domain);
            _context.Add("processor_fqdn", _context["processor_hostname"] + "." + domain);
            _context.Add("system_name", _context["processor_hostname"]);
        }
示例#7
0
        public void Get()
        {
            try
            {
                var roomId = 1;

                var host =
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                        CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                            EthernetAdapterType.EthernetLANAdapter));

                try
                {
                    roomId = int.Parse(Request.QueryString["room"]);
                }
                catch
                {
                    HandleNotFound();
                    return;
                }

                uint ipId = 4;
                try
                {
                    var controllers =
                        System.UIControllers.Where(
                            ui => ui is RoomUIController && ui.DefaultRoom != null && ui.DefaultRoom.Id == roomId).ToArray();
                    if (controllers.Any())
                    {
                        ipId = controllers.First().Device.ID;
                    }

                    Redirect(string.Format("/static/xpanel/Core3XPanel.html?host={0}&ipid={1}", host,
                                           ipId.ToString("X2")));
                }
                catch (Exception e)
                {
                    HandleError(e);
                }
            }
            catch (Exception e)
            {
                HandleError(e);
            }
        }
示例#8
0
        internal void Start(int portNumber)
        {
            Port = portNumber;
            if (_listeningThread != null && _listeningThread.ThreadState == ThreadState.Running)
            {
                throw new Exception("Logger already running");
            }

            try
            {
                if (InitialParametersClass.NumberOfExternalEthernetInterfaces > 0)
                {
                    Logger.Log("Control system has external ethernet interfaces, will attempt to map port to internal IP");
                    var id = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetCSAdapter);
                    var controlSubnetIp = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, id);
                    Logger.Log($"CS IP Address is: {controlSubnetIp}");
                    var result = CrestronEthernetHelper.AddPortForwarding((ushort)portNumber, (ushort)portNumber,
                                                                          controlSubnetIp, CrestronEthernetHelper.ePortMapTransport.TCP);
                    if (result == CrestronEthernetHelper.PortForwardingUserPatRetCodes.NoErr)
                    {
                        _csPortForwardIp = controlSubnetIp;
                        Logger.Log(
                            $"Port Fowarding result = {result}, forwarded TCP port {portNumber} to internal IP: {controlSubnetIp}");
                    }
                    else
                    {
                        Logger.Warn($"Could not create port forwarding for Logger, result = {result}");
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e);
            }

            _listeningThread = new Thread(ListenProcess)
            {
                Name = "LoggerRx" + InitialParametersClass.ApplicationNumber
            };
            _listeningThread.Start();
            Logger.Highlight($"Logger started console on port {portNumber}");
        }
示例#9
0
        /// <summary>
        /// Read local network propertis of the control system and saves them to the config file
        /// </summary>
        private void SyncDeviceNetworkProperties()
        {
            short adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);

            //Mac Address
            _deviceConfig.networkProperties.macAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);

            //DHCP
            _deviceConfig.networkProperties.dhcp = (CrestronEthernetHelper.GetEthernetParameter(
                                                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, adapterId).Equals("ON", StringComparison.OrdinalIgnoreCase)) ? true : false;

            //Webserver status
            _deviceConfig.networkProperties.webServer = (CrestronEthernetHelper.GetEthernetParameter(
                                                             CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_WEBSERVER_STATUS, adapterId).Equals("ON", StringComparison.OrdinalIgnoreCase)) ? true : false;

            //Static IP Info
            _deviceConfig.networkProperties.staticIpAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_STATIC_IPADDRESS, adapterId);
            _deviceConfig.networkProperties.staticNetMask   = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_STATIC_IPMASK, adapterId);
            _deviceConfig.networkProperties.staticDefRouter = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_STATIC_ROUTER, adapterId);

            //HostName
            _deviceConfig.networkProperties.hostName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, adapterId);

            //Domain Name
            _deviceConfig.networkProperties.domainName = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, adapterId);

            //DNS Servers
            _deviceConfig.networkProperties.dnsServers =
                CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DNS_SERVER, adapterId).Split(',');

            //DNS server comes in the following format - x.x.x.x (static/DHCP) - Since we force the data to be in ipv4, we remove the (static/DHCP) section
            int i;

            foreach (string ds in _deviceConfig.networkProperties.dnsServers)
            {
                i = ds.IndexOf('(');
                if (i > 0)
                {
                    ds.Substring(0, i).Trim();
                }
            }
        }
示例#10
0
        public override void InitializeSystem()
        {
            try
            {
                myServer = new HttpCwsServer("/api");
                myServer.ReceivedRequestEvent += new HttpCwsRequestEventHandler(myServerReceivedRequestEvent);
                myServer.Routes.Add(new HttpCwsRoute("ver")
                {
                    Name = "shversion"
                });
                myServer.Register();

                CrestronConsole.SendControlSystemCommand("progcomments:1", ref cmdResponse);
                CrestronConsole.SendControlSystemCommand("ver", ref versionResponse);

                var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);
                macAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
            }
            catch (Exception e)
            {
                ErrorLog.Error("Error in InitializeSystem: {0}", e.Message);
            }
        }
        /// <summary>
        /// Gets the current control subnet info
        /// </summary>
        public void GetControlSubnetInfo()
        {
            OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);

            var adapter = new ControlSubnetInfo();

            try
            {
                // get cs adapter id
                var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetCSAdapter);
                if (!adapterId.Equals(EthernetAdapterType.EthernetUnknownAdapter))
                {
                    adapter.Enabled           = 1;
                    adapter.IsInAutomaticMode = (ushort)(CrestronEthernetHelper.IsControlSubnetInAutomaticMode ? 1 : 0);
                    adapter.MacAddress        = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
                    adapter.IpAddress         = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
                    adapter.Subnet            = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
                    adapter.RouterPrefix      = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CONTROL_SUBNET_ROUTER_PREFIX, adapterId);
                }
            }
            catch (Exception e)
            {
                adapter.Enabled           = 0;
                adapter.IsInAutomaticMode = 0;
                adapter.MacAddress        = "NA";
                adapter.IpAddress         = "NA";
                adapter.Subnet            = "NA";
                adapter.RouterPrefix      = "NA";

                var msg = string.Format("GetControlSubnetInfo failed: {0}", e.Message);
                CrestronConsole.PrintLine(msg);
                //ErrorLog.Error(msg);
            }

            OnControlSubnetInfoChange(adapter, 0, SystemInfoConstants.ControlSubnetConfigChange);
            OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
        }
示例#12
0
        public bool RequestTask(string siteId, long taskId, string roomName)
        {
            try
            {
                short adapter =
                    CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);
                string systemId =
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapter);
                string ipAddress =
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapter);

                var jsonData = JsonConvert.SerializeObject(new
                {
                    api_key           = _apiKey,
                    site_id           = siteId,
                    system_id         = systemId,
                    system_ip_address = ipAddress,
                    room_name         = roomName,
                    task_id           = taskId
                }, Formatting.Indented);

                JObject result = JObject.Parse(Post("sendmail", jsonData));

                CrestronConsole.PrintLine("\r\n{0}", result);

                return(result["status"].Value <string>() == "200 OK");
            }
            catch (Exception e)
            {
                CloudLog.Error("AssistanceClient.RequestTask(taskId = {0}, roomName = {1}) Error, {2}",
                               taskId, roomName, e.Message);
                return(false);
            }
        }
示例#13
0
        private object SshCommsProcess(object userSpecific)
        {
            var errorOnConnect = false;

            try
            {
                Thread.Sleep(1000);

                CloudLog.Info("{0} attempting connection to {1}", GetType().Name, _address);

                var firstFail = false;

                while (!_client.IsConnected && _reconnect)
                {
                    try
                    {
                        ConnectionStatus = SshClientStatus.AttemptingConnection;
                        _client.Connect();
                    }
                    catch
                    {
                        ConnectionStatus = SshClientStatus.Disconnected;
                        if (!firstFail)
                        {
                            CloudLog.Warn("{0} could not connect to {1}, will retry every 30 seconds until connected",
                                          GetType().Name, _address);
                            firstFail = true;
                        }

                        if (_threadWait.WaitOne(30000))
                        {
                            CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                            _reconnect = false;
                            break;
                        }
                    }
                }

                if (!_client.IsConnected && !_reconnect)
                {
                    _client.Dispose();
                    _client          = null;
                    ConnectionStatus = SshClientStatus.Disconnected;
                    return(null);
                }

                CloudLog.Notice("{0} Connected to {1}", GetType().Name, _address);

                _shell = _client.CreateShellStream("terminal", 80, 24, 800, 600, 100000);

                //_shell.DataReceived += (sender, args) => _threadWait.Set();

                var data = string.Empty;

                try
                {
                    while (_programRunning && _client.IsConnected)
                    {
                        while (_shell.CanRead && _shell.DataAvailable)
                        {
                            var bytes  = new byte[100000];
                            var length = _shell.Read(bytes, 0, bytes.Length);
#if DEBUG
                            _stopWatch.Start();
                            Debug.WriteSuccess("Codec rx {0} bytes", length);
#endif
                            var incoming = Encoding.ASCII.GetString(bytes, 0, length);

                            if (!_loggedIn && incoming.Contains("Failed to connect to system software"))
                            {
                                CloudLog.Error("Error received from codec at \"{0}\" on connect:\r\n{1}",
                                               _address, incoming);
                                errorOnConnect = true;
                                break;
                            }
#if DEBUG
                            Debug.WriteNormal(Debug.AnsiBlue + incoming + Debug.AnsiReset);
#endif
                            data = data + incoming;

                            if (!_loggedIn)
                            {
                                foreach (var line in Regex.Split(data, "\r\n|\r|\n"))
                                {
                                    if (line == "*r Login successful")
                                    {
                                        _loggedIn = true;
                                        try
                                        {
                                            Debug.WriteSuccess("Connected!", "{0} logged into {1}", GetType().Name,
                                                               _address);
                                            CloudLog.Info("{0} logged into {1}", GetType().Name, _address);

                                            _sendQueue.Enqueue(@"echo off");

                                            var adapterType = _client.EthernetAdapter;
                                            var adapterId   =
                                                CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(adapterType);
                                            var currentIp = CrestronEthernetHelper.GetEthernetParameter(
                                                CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                                                adapterId);
                                            var assembly     = Assembly.GetExecutingAssembly().GetName();
                                            var softwareInfo = assembly.Name + " " + assembly.Version;
                                            var model        = InitialParametersClass.ControllerPromptName;
                                            _sendQueue.Enqueue(string.Format(
                                                                   "xCommand Peripherals Connect ID: {0} Name: \"Crestron Control System\" HardwareInfo: \"{1}\" NetworkAddress: \"{2}\" SoftwareInfo: \"{3}\" Type: ControlSystem",
                                                                   _heartbeatId, string.Format("Crestron {0}", model), currentIp,
                                                                   softwareInfo));

                                            _sendQueue.Enqueue(@"xFeedback register /Configuration");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/SystemUnit");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Diagnostics");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Audio");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Standby");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Video");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Cameras");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Call");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Conference");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/UserInterface");
                                            _sendQueue.Enqueue(@"xFeedback register /Status/Bookings");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/OutgoingCallIndication");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/IncomingCallIndication");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallSuccessful");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallDisconnect");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/Bookings");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/CallHistory");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Extensions");
                                            _sendQueue.Enqueue(@"xFeedback register /Event/UserInterface/Presentation/ExternalSource");

                                            _sendQueue.Enqueue(@"xStatus");

                                            _heartBeatTimer =
                                                new CTimer(
                                                    specific =>
                                                    _sendQueue.Enqueue(
                                                        string.Format("xCommand Peripherals HeartBeat ID: {0}",
                                                                      _heartbeatId)),
                                                    null, 60000, 60000);

                                            ConnectionStatus = SshClientStatus.Connected;
                                        }
                                        catch (Exception e)
                                        {
                                            CloudLog.Exception(e);
                                        }
                                    }
                                }

                                data = string.Empty;
                            }
                            else if (data.Contains("** end"))
                            {
                                var chunks = Regex.Matches(data, @"(\*(\w) [\S\s]*?)(?=\*\* end)");

                                data = string.Empty;

                                if (chunks.Count > 0)
                                {
                                    foreach (Match chunk in chunks)
                                    {
                                        var type = ReceivedDataType.Status;

                                        switch (chunk.Groups[2].Value)
                                        {
                                        case "e":
                                            type = ReceivedDataType.Event;
                                            break;

                                        case "r":
                                            type = ReceivedDataType.Response;
                                            break;

                                        case "c":
                                            type = ReceivedDataType.Configuration;
                                            break;
                                        }
                                        OnReceivedData(this, type, chunk.Groups[1].Value);
                                    }
                                }
                            }
#if DEBUG
                            else
                            {
                                Debug.WriteWarn("Waiting for more data...");
                            }

                            _stopWatch.Stop();
                            Debug.WriteNormal("Time to process: {0} ms", _stopWatch.ElapsedMilliseconds);
                            _stopWatch.Reset();
#endif
                            CrestronEnvironment.AllowOtherAppsToRun();
                        }

                        if (errorOnConnect)
                        {
                            try
                            {
                                _client.Disconnect();
                            }
                            catch (Exception e)
                            {
                                CloudLog.Warn("Error closing connection to codec after error, {0}", e.Message);
                            }

                            break;
                        }

                        if (!_programRunning || !_client.IsConnected)
                        {
                            break;
                        }

                        while (_shell.CanWrite && !_sendQueue.IsEmpty)
                        {
                            var s = _sendQueue.Dequeue();
#if DEBUG
                            Debug.WriteWarn("Codec Tx", s);
#endif
                            _shell.WriteLine(s);
                        }
                    }

                    CloudLog.Debug("{0} left while(connected) loop", Thread.CurrentThread.Name);
                }
                catch (ObjectDisposedException e)
                {
                    CloudLog.Warn("{0} ObjectDisposedException, {1}, {2}", GetType().Name,
                                  string.IsNullOrEmpty(e.ObjectName) ? "unknown" : e.ObjectName, e.Message);
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error handling comms process");
                }

                _loggedIn = false;

                try
                {
                    if (_heartBeatTimer != null && !_heartBeatTimer.Disposed)
                    {
                        _heartBeatTimer.Stop();
                        _heartBeatTimer.Dispose();
                    }

                    if (_client != null)
                    {
                        CloudLog.Info("Disposing {0}", _client.ToString());
                        _client.Dispose();
                        _client = null;
                    }
                }
                catch (Exception e)
                {
                    CloudLog.Exception(e, "Error trying to dispose items in leaving thread");
                }

                CloudLog.Notice("{0} Disconnected from {1}", GetType().Name, _address);
            }
            catch (Exception e)
            {
                CloudLog.Exception(e, "Error in {0}.SshCommsProcess()", GetType().Name);
            }

            ConnectionStatus = SshClientStatus.Disconnected;

            if (errorOnConnect)
            {
                CloudLog.Warn("Error message while connecting to {0}, Disconnected and will retry in 60 seconds", _address);

                if (_threadWait.WaitOne(60000))
                {
                    CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                    _reconnect = false;
                }
            }

            if (!_reconnect)
            {
                CloudLog.Notice("Leaving connect thread for codec at {0}", _address);
                return(null);
            }

            CloudLog.Notice("Waiting for 10 seconds before reconnect attempt to {0}", _address);
            if (_threadWait.WaitOne(10000))
            {
                CloudLog.Info("{0} - Signal sent to leave thread on attempt to connect", GetType().Name);
                _reconnect = false;
                return(null);
            }

            CloudLog.Notice("Attempting reconnect to codec at {0}", _address);
            ConnectionStatus = SshClientStatus.AttemptingConnection;

            Connect();

            return(null);
        }
示例#14
0
 private string getLocalIP()
 {
     return(CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS,
                                                        CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter)));
 }
示例#15
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);
        }
示例#16
0
 /// <summary>
 /// Determines whether the specified <see cref="System.Net.IPAddress"/> represents
 /// a local IP address.
 /// </summary>
 /// <returns>
 /// <c>true</c> if <paramref name="address"/> represents a local IP address;
 /// otherwise, <c>false</c>.
 /// <remarks>
 /// This local means NOT REMOTE for the current host.
 /// </remarks>
 /// </returns>
 /// <param name="address">
 /// A <see cref="System.Net.IPAddress"/> to test.
 /// </param>
 /// <param name="adapter">adapter number to test against</param>
 /// <param name="adapterType">EthernetAdapterType to test against</param>
 public static bool IsLocal(this IPAddress address, EthernetAdapterType adapterType)
 {
     return
         (address.IsLocal(adapterType == EthernetAdapterType.EthernetUnknownAdapter
                                                                                 ? (short)-1 : CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(adapterType)));
 }
        /// <summary>
        /// Gets the current ethernet info
        /// </summary>
        public void GetEthernetInfo()
        {
            OnBoolChange(true, 0, SystemInfoConstants.BusyBoolChange);

            var adapter = new EthernetInfo();

            try
            {
                // get lan adapter id
                var adapterId = CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(EthernetAdapterType.EthernetLANAdapter);

                // get lan adapter info
                var dhcpState = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_DHCP_STATE, adapterId);
                if (!string.IsNullOrEmpty(dhcpState))
                {
                    adapter.DhcpIsOn = (ushort)(dhcpState.ToLower().Contains("on") ? 1 : 0);
                }

                adapter.Hostname   = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, adapterId);
                adapter.MacAddress = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_MAC_ADDRESS, adapterId);
                adapter.IpAddress  = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, adapterId);
                adapter.Subnet     = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_MASK, adapterId);
                adapter.Gateway    = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_ROUTER, adapterId);
                adapter.Domain     = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DOMAIN_NAME, adapterId);

                // returns comma seperate list of dns servers with trailing comma
                // example return: "8.8.8.8 (DHCP),8.8.4.4 (DHCP),"
                string dns = CrestronEthernetHelper.GetEthernetParameter(CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_DNS_SERVER, adapterId);
                if (dns.Contains(","))
                {
                    string[] dnsList = dns.Split(',');
                    for (var i = 0; i < dnsList.Length; i++)
                    {
                        if (i == 0)
                        {
                            adapter.Dns1 = !string.IsNullOrEmpty(dnsList[0]) ? dnsList[0] : "0.0.0.0";
                        }
                        if (i == 1)
                        {
                            adapter.Dns2 = !string.IsNullOrEmpty(dnsList[1]) ? dnsList[1] : "0.0.0.0";
                        }
                        if (i == 2)
                        {
                            adapter.Dns3 = !string.IsNullOrEmpty(dnsList[2]) ? dnsList[2] : "0.0.0.0";
                        }
                    }
                }
                else
                {
                    adapter.Dns1 = !string.IsNullOrEmpty(dns) ? dns : "0.0.0.0";
                    adapter.Dns2 = "0.0.0.0";
                    adapter.Dns3 = "0.0.0.0";
                }

                OnEthernetInfoChange(adapter, 0, SystemInfoConstants.EthernetConfigChange);
            }
            catch (Exception e)
            {
                var msg = string.Format("GetEthernetInfo failed: {0}", e.Message);
                CrestronConsole.PrintLine(msg);
                //ErrorLog.Error(msg);
            }

            OnBoolChange(false, 0, SystemInfoConstants.BusyBoolChange);
        }
示例#18
0
        public void Get()
        {
            if (RequireLogin(true))
            {
                return;
            }

            try
            {
                var ms        = new MemoryStream();
                var appNumber = InitialParametersClass.ApplicationNumber;
                var commands  = new[]
                {
                    "hostname",
                    "mycrestron",
                    "showlicense",
                    "osd",
                    "uptime",
                    "ver -v",
                    "ver all",
                    "uptime",
                    "time",
                    "timezone",
                    "sntp",
                    "showhw",
                    "ipconfig /all",
                    "progregister",
                    "progcomments:1",
                    "progcomments:2",
                    "progcomments:3",
                    "progcomments:4",
                    "progcomments:5",
                    "progcomments:6",
                    "progcomments:7",
                    "progcomments:8",
                    "progcomments:9",
                    "progcomments:10",
                    "proguptime:1",
                    "proguptime:2",
                    "proguptime:3",
                    "proguptime:4",
                    "proguptime:5",
                    "proguptime:6",
                    "proguptime:7",
                    "proguptime:8",
                    "proguptime:9",
                    "proguptime:10",
                    "ssptasks:1",
                    "ssptasks:2",
                    "ssptasks:3",
                    "ssptasks:4",
                    "ssptasks:5",
                    "ssptasks:6",
                    "ssptasks:7",
                    "ssptasks:8",
                    "ssptasks:9",
                    "ssptasks:10",
                    "appstat -p:" + appNumber,
                    "taskstat",
                    "ramfree",
                    "cpuload",
                    "cpuload",
                    "cpuload",
                    "showportmap -all",
                    "ramfree",
                    "showdiskinfo",
                    "ethwdog",
                    "iptable -p:all -t",
                    "who",
                    "netstat",
                    "threadpoolinfo",
                    "autodiscover query tableformat",
                    "reportcresnet",
                };
                using (var zip = new ZipFile())
                {
                    var directory = new DirectoryInfo(@"\NVRAM");
                    foreach (var file in directory.GetFiles())
                    {
                        zip.AddFile(file.FullName, @"\NVRAM Root");
                    }

                    directory = new DirectoryInfo(SystemBase.AppStoragePath);
                    foreach (var file in directory.GetFiles())
                    {
                        zip.AddFile(file.FullName,
                                    string.Format("\\NVRAM for App {0}", InitialParametersClass.ApplicationNumber.ToString("D2")));
                    }

                    var diagnosticsData = new StringWriter();
                    foreach (var message in System.StatusMessages)
                    {
                        diagnosticsData.WriteLine("{0}: {2} {1}", message.MessageLevel, message.MessageString,
                                                  message.SourceDeviceName);
                    }
                    zip.AddEntry("diagnostics.txt", diagnosticsData.ToString());

                    directory = new DirectoryInfo(@"/Sys/PLog/CurrentBoot");
                    foreach (var file in directory.GetFiles())
                    {
                        zip.AddFile(file.FullName, @"\CurrentBootLogs");
                    }

                    directory = new DirectoryInfo(@"/Sys/PLog/PreviousBoot");
                    foreach (var file in directory.GetFiles())
                    {
                        zip.AddFile(file.FullName, @"\PreviousBootLogs");
                    }

                    var statusData = new MemoryStream();
                    var sw         = new StreamWriter(statusData);
                    foreach (var command in commands)
                    {
                        sw.WriteLine("Console Cmd: {0}", command);
                        var response = string.Empty;
                        CrestronConsole.SendControlSystemCommand(command, ref response);
                        sw.WriteLine(response);
                    }
                    statusData.Position = 0;
                    zip.AddEntry(@"processor_status.txt", statusData);

                    zip.Save(ms);
                }
                Request.Response.Header.ContentType = MimeMapping.GetMimeMapping(".zip");
                Request.Response.ContentSource      = ContentSource.ContentStream;
                var hostname =
                    CrestronEthernetHelper.GetEthernetParameter(
                        CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME,
                        CrestronEthernetHelper.GetAdapterdIdForSpecifiedAdapterType(
                            EthernetAdapterType.EthernetLANAdapter));
                Request.Response.Header.AddHeader(new HttpHeader("content-disposition",
                                                                 string.Format("attachment; filename=processor_report_{0}_{1}.zip",
                                                                               hostname, DateTime.Now.ToString("yyyyMMddTHHmmss"))));
                ms.Position = 0;
                Request.Response.ContentStream = ms;
                Request.Response.CloseStream   = true;
            }
            catch (Exception e)
            {
                HandleError(e);
            }
        }