예제 #1
0
        public string GetChallenge(Config conf)
        {
            try
            {
                XDocument doc = XDocument.Load("http://" + conf.baseurl + "/login_sid.lua");
                XElement info = doc.FirstNode as XElement;

                return info.Element("Challenge").Value;
            }
            catch (Exception e)
            {
                if(e.GetType() == typeof(WebException))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[Error] Cant connect to fritzbox.");
                }
                else if (e.GetType() == typeof(System.Xml.XmlException))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[Error] Cant Read XML.");
                }
                Console.ReadKey();

                Environment.Exit(0);

                return null;
            }
        }
예제 #2
0
파일: Program.cs 프로젝트: halo779/FritzLog
        public static Config LoadDefaults(Config conf)
        {
            if (String.IsNullOrWhiteSpace(conf.baseurl))
                conf.baseurl = Config.DEFAULT_BASEURL;
            if (conf.ConfVersion == 0)
                conf.ConfVersion = Config.DEFAULT_CONFVERSION;
            if (String.IsNullOrWhiteSpace(conf.password))
                conf.password = Config.DEFAULT_PASSWORD;
            conf.logToTextFile = Config.DEFAULT_LOGTOTEXTFILE;

            return conf;
        }
예제 #3
0
        public void ProcessTelnet(Config conf, DslInfo dsl)
        {
            OutputScriptFile(conf.password, conf.baseurl, System.Windows.Forms.Application.StartupPath + @"\telnetscript.tmp");
            string outputPath;

            if(conf.TelnetDebug)
                outputPath = "telnetoutput-" + DateTime.Now.ToString("yyyyMMddHHmm") + ".txt";
            else
                outputPath = "telnetoutput.tmp";

            ProcessStartInfo pInfo = new ProcessStartInfo();
            pInfo.Arguments = "/r:telnetscript.tmp /o:" + outputPath + " /m";
            pInfo.WorkingDirectory = System.Windows.Forms.Application.StartupPath;
            pInfo.FileName = "TST10.exe";
            Process p = Process.Start(pInfo);
            Console.WriteLine("Querying Telnet");
            byte timeout = 15;
            while (!p.WaitForExit(1000))
            {
                Console.Write(".");
                if (timeout != 0)
                {
                    timeout--;
                }
                else
                {
                    Console.WriteLine("/nTelnet is taking too long to process. Skipping");
                    p.CloseMainWindow();
                    p.Close();
                    break;
                }
            }

            Console.WriteLine();
            ProcessOutput(System.Windows.Forms.Application.StartupPath + @"\" + outputPath, conf, dsl);

            //var lines = System.IO.File.ReadAllLines("test.txt");
            //System.IO.File.WriteAllLines("test.txt", lines.Skip(1).ToArray());

            if(!conf.TelnetDebug)
            {
                File.Delete(System.Windows.Forms.Application.StartupPath + @"\telnetscript.tmp");
                File.Delete(System.Windows.Forms.Application.StartupPath + @"\" + outputPath);
            }
        }
예제 #4
0
파일: Program.cs 프로젝트: halo779/FritzLog
        public static Config LoadSettings()
        {
            XmlSerializer serializerObj = new XmlSerializer(typeof(Config));

            Config loadedObj = new Config();
            try
            {
                // Create a new file stream for reading the XML file
                FileStream readFileStream = new FileStream(Environment.CurrentDirectory + @"\conf.xml", FileMode.Open, FileAccess.Read, FileShare.Read);

                // Load the object saved above by using the Deserialize function
                loadedObj = (Config)serializerObj.Deserialize(readFileStream);

                // Cleanup
                readFileStream.Close();
            }
            catch (Exception)
            {
                //do nothing.
            }

            return loadedObj;
        }
예제 #5
0
        private void ProcessOutput(string TelnetLog, Config conf, DslInfo dsl)
        {
            //string[] Log = File.ReadAllLines(TelnetLog);
            FileInfo fi = new FileInfo(TelnetLog);

            string tmp;

            tmp = fi.HuntForLine(s => s.Contains("Downstream Training Margin:"));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
                    dsl.DownstreamTrainingMargin = number;
                }
                catch
                {

                }
                tmp = null;
            }

            tmp = fi.HuntForLine(s => s.Contains("Tx total power "));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
                    dsl.TxTotalPower = number;
                }
                catch
                {

                }
                tmp = null;
            }

            tmp = fi.HuntForLine(s => s.Contains("FE Tx total power "));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
                    dsl.FeTxTotalPower = number;
                }
                catch
                {

                }
                tmp = null;
            }

            tmp = fi.HuntForLine(s => s.Contains("VDSL Estimated Loop Length"));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    long number = Convert.ToInt64(m.Value, CultureInfo.InvariantCulture);
                    dsl.VdslEstimatedLoopLengthFt = number;
                    dsl.VdslEstimatedLoopLengthMeters = Math.Round(Helpers.FeetToMeters(number), 2);
                }
                catch
                {

                }
                tmp = null;
            }

            tmp = fi.HuntForLine(s => s.Contains("G.Hs Estimated Near End Loop Length"));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
                    dsl.GHsEstimatedNearEndLoopLengthFt = number;
                    dsl.GHsEstimatedNearEndLoopLengthMeters = Math.Round(Helpers.FeetToMeters(number), 2);
                }
                catch
                {

                }
                tmp = null;
            }

            tmp = fi.HuntForLine(s => s.Contains("G.Hs Estimated Far End Loop Length"));
            if (!String.IsNullOrWhiteSpace(tmp))
            {
                try
                {
                    Match m = Regex.Match(tmp, "[0-9]+[.[0-9]+]?");
                    double number = Convert.ToDouble(m.Value, CultureInfo.InvariantCulture);
                    dsl.GHsEstimatedFarEndLoopLengthFt = number;
                    dsl.GHsEstimatedFarEndLoopLengthMeters = Math.Round(Helpers.FeetToMeters(number), 2);
                }
                catch
                {

                }
                tmp = null;
            }
        }
예제 #6
0
파일: Program.cs 프로젝트: halo779/FritzLog
        public static void SaveSettings(Config conf)
        {
            // Create a new XmlSerializer instance with the type of the test class
            XmlSerializer serializerObj = new XmlSerializer(typeof(Config));
            try
            {
                // Create a new file stream to write the serialized object to a file
                TextWriter writeFileStream = new StreamWriter(Environment.CurrentDirectory + @"\conf.xml");
                serializerObj.Serialize(writeFileStream, conf);

                // Cleanup
                writeFileStream.Close();
            }
            catch (UnauthorizedAccessException)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Error] Cant write config file!");
                Console.ReadKey();
                Environment.Exit(0);
            }
        }
예제 #7
0
파일: Program.cs 프로젝트: halo779/FritzLog
        static void Main(string[] args)
        {
            bool console = true, logToSingleFile = false, autoClose = false;
            string attemptOutPath = Environment.CurrentDirectory;
            string attemptWriteToSingleFile =  attemptOutPath + @"\latest.log";
            if (args.Length > 0)
            {
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                        case "-nc":
                        case "-noconsole":
                            {
                                console = false;
                                break;
                            }
                        case "-latestoutput":
                        case "-l":
                            {
                                logToSingleFile = true;
                                if (args.Length > (i + 1) && args[i] != null && args[i] != "")
                                {
                                    i++;
                                    attemptWriteToSingleFile = attemptOutPath + @"\" + args[i];
                                }

                                break;
                            }
                        case "-ac":
                        case "-autoclose":
                            {
                                autoClose = true;
                                break;
                            }
                    }
                }
            }
            if (console)
                ShowConsoleWindow();
            Version newestVer = Config.GetNewestVersion();
            if (newestVer > System.Reflection.Assembly.GetExecutingAssembly().GetName().Version)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("\nUpdate Available! - http://hio77.com/fritzlog/download/" + newestVer + "/fritzboxlog.zip\n");
                Console.ResetColor();

            }
            Config config = new Config();
            if(File.Exists(Environment.CurrentDirectory + @"\conf.xml"))
            {
                config = LoadSettings();
            }
            else
            {
                config = LoadDefaults(config);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("\nFirst Run Configuration\n");
                Console.ResetColor();
                Console.Write("Fritzbox ip/hostname? [" + Config.DEFAULT_BASEURL + "] : ");
                string k = Console.ReadLine();
                config.baseurl = String.IsNullOrWhiteSpace(k) ? Config.DEFAULT_BASEURL : k;
                Console.Write("Fritzbox password? [" + Config.DEFAULT_PASSWORD + "] : ");
                k = Console.ReadLine();
                config.password = String.IsNullOrWhiteSpace(k) ? Config.DEFAULT_PASSWORD : k;

                Console.Write("Log To Text File? (Y/N) [N] : ");
                k = Console.ReadKey().KeyChar.ToString().ToUpperInvariant();
                Console.WriteLine(Environment.NewLine);
                config.logToTextFile = String.IsNullOrWhiteSpace(k) ? Config.DEFAULT_LOGTOTEXTFILE : k == "Y" ? true : false;

                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("\nDone!\n");
                SaveSettings(config);
                Console.ResetColor();
            }

            Console.WriteLine("Fritzbox Status");
            Console.WriteLine("---------------");
            Console.Write("HTTP Service: ");
            bool httpStatus = IsServerUp(config.baseurl, 80, 200);
            WritelineColouredBool(httpStatus);
            Console.Write("Telnet Service: ");
            bool telnetStatus = IsServerUp(config.baseurl, 23, 200);
            WritelineColouredBool(telnetStatus);

            if (!httpStatus)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Error] Fritz box was unresposive.");
                goto ProgramClose;
            }

            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();

            DataCollector dc = new DataCollector();
            DslInfo info = new DslInfo();

            info.Firmware = dc.GetFirmwareVersion(config);
            int mainOsVer;
            int minorOsVer;
            int.TryParse(info.Firmware.Split('.')[1], out mainOsVer);
            int.TryParse(info.Firmware.Split('.')[2], out minorOsVer);

            if (mainOsVer > 5 || (mainOsVer == 5 && minorOsVer >= 50))
            {
                config.FritzOs5 = true;
                Console.WriteLine("Fritz OS 5.0 Detected.");
            }
            string challange = dc.GetChallenge(config);
            string response = dc.GetResponse(challange, config.password);
            string sid = dc.GetSid(challange, response, config);
            Console.WriteLine("SID: " + sid);
            if (sid == "0000000000000000")
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Error] Password or authentication process is wrong!");
                Console.ReadKey();
                Environment.Exit(0);
            }
            Console.WriteLine("Collecting Data From Fritz HTTP Service");

            dc.GetDslStats(sid, config, ref info);

            if (telnetStatus)
            {
                TelnetCollector tl = new TelnetCollector();

                tl.ProcessTelnet(config, info);
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Telnet was Inaccessable. Skipping..");
                Console.ResetColor();
            }

            //dc.MonitorErrorRatesForMins(sid, config, ref info, 600);

            /* RRD stuff
            NHawkCommand.Instance.RRDCommandPath = @"C:\rrd\rrdtool.exe";

            if (!File.Exists("test.rrd"))
            {
                RRD FritzStatsNew = new RRD("test.rrd", Helpers.ToUnixTime(DateTime.Now));
                FritzStatsNew.step = 300;
                FritzStatsNew.addDS(new DS("CurrentThroughputRx", DS.TYPE.DERIVE, 600, 0, 250000));
                FritzStatsNew.addDS(new DS("CurrentThroughputTx", DS.TYPE.DERIVE, 600, 0, 250000));
                FritzStatsNew.addRRA(new RRA(RRA.CF.MAX, 0.5, 1, 210240));
                FritzStatsNew.create(true);

            }

            RRD FritzStats = RRD.load("test.rrd");

            FritzStats.update(Helpers.ToUnixTime(DateTime.Now), new object[] { info.CurrentThroughputRx, info.CurrentThroughputTx });

            FritzStats.export("dump.xml", false);

            */

            Console.WriteLine("\n-=- DSL Info -=-\n");
            foreach (var field in typeof(DslInfo).GetFields())
            {
                if (field.Name != "SNRGraph" && field.Name != "BitLoaderGraph")
                    Console.WriteLine("{0}: {1}", field.Name, field.GetValue(info));
                /*
                if (field.Name == "SNRGraph")
                {

                    RRD SNRGraph = new RRD("test.rrd", 920800000);
                    SNRGraph.step = 1;
                    SNRGraph.addDS(new DS("SNR", DS.TYPE.COUNTER, 600, DS.U, DS.U));
                    SNRGraph.addRRA(new RRA(RRA.CF.AVERAGE, 0, 1, 60));
                    SNRGraph.create(true);

                    SNRGraph.update(920800001, new object[] { 20 });
                    SNRGraph.update(920800002, new object[] { 20 });
                    SNRGraph.update(920800006, new object[] { 20 });
                    SNRGraph.update(920800010, new object[] { 20 });

                    GRAPH grout = new GRAPH("test.png", "920800000", (920800000 + 4096).ToString());
                    grout.addDEF(new DEF("SNR", SNRGraph, "SNR", RRA.CF.AVERAGE));
                    grout.graph();
                    Console.WriteLine("blah");
                }
                */
            }

            if (config.logToTextFile)
            {
                try
                {
                    if(!Directory.Exists(Environment.CurrentDirectory + @"\logs\"))
                        Directory.CreateDirectory(Environment.CurrentDirectory + @"\logs");

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(Environment.CurrentDirectory + @"\logs\capture-" + DateTime.Now.ToString("yyyyMMddHHmm") + ".txt",false))
                    {
                        foreach (var field in typeof(DslInfo).GetFields())
                        {
                             file.WriteLine("{0}: {1}", field.Name, field.GetValue(info));
                        }
                        file.Flush();
                        file.Close();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write("\nStats saved to file");
                        Console.ResetColor();
                        Console.Write(" - " + Environment.CurrentDirectory + @"\logs\capture-" + DateTime.Now.ToString("yyyyMMddHHmm") + ".txt");
                    }
                }
                catch (Exception)
                {

                }

            }

            if (logToSingleFile)
            {
                try
                {
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(attemptWriteToSingleFile, false))
                    {
                        foreach (var field in typeof(DslInfo).GetFields())
                        {
                            file.WriteLine("{0}: {1}", field.Name, field.GetValue(info));
                        }
                        file.Flush();
                        file.Close();
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write("\nStats saved to file");
                        Console.ResetColor();
                        Console.Write(" - " + attemptWriteToSingleFile);
                    }
                }
                catch (Exception)
                {

                }

            }

            //info.dscrcCounts = new List<RelationalDouble>();

            //System.Windows.Forms.Form testy = new test(info.dscrcCounts);

            //info.dscrcCounts.Add(new RelationalDouble(4.0));

            //testy.ShowDialog();

            stopWatch.Stop();
            TimeSpan ts = stopWatch.Elapsed;
            string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
            Console.WriteLine("\n-=- RunTime " + elapsedTime + " -=-\n");
            if (info.UpgradesManaged)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Warning] Your Fritz is configured to automatically update its firmware.");
                Console.WriteLine("[Warning] Your Fritz is configured to automatically update its firmware.");
                Console.WriteLine("[Warning] Your Fritz is configured to automatically update its firmware.");
                Console.ResetColor();
            }

            if (config.TimeOutOfAlignment)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[Warning] Your Fritz Timezone May be wrong or out by more than 5 minutes.");
                Console.WriteLine("[Warning] Your Fritz Timezone May be wrong or out by more than 5 minutes.");
                Console.WriteLine("[Warning] Your Fritz Timezone May be wrong or out by more than 5 minutes.");
                Console.ResetColor();
            }
            ProgramClose:

            if (!autoClose)
            {
                Console.ForegroundColor = ConsoleColor.Blue;
                Console.Write("Press any key to close.");
                Console.ReadKey();
            }

            Console.ResetColor();
            Environment.Exit(0);
        }
예제 #8
0
        public void GetDslStats(string sid, Config conf, ref DslInfo stats)
        {
            Dictionary<string, string> modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ds_attenuation", "sar:status/ds_crc_minute", "sar:status/ds_crc_per15min", "sar:status/ds_delay", "sar:status/ds_es", "sar:status/ds_fec_minute", "sar:status/ds_fec_per15min", "sar:status/ds_margin", "sar:status/ds_path", "sar:status/ds_ses", "sar:status/dsl_ds_rate", "sar:status/dsl_tone_set", "sar:status/dsl_us_rate", "sar:status/exp_ds_inp_act", "sar:status/exp_ds_olr_Bitswap", "sar:status/exp_us_inp_act", "sar:status/exp_us_olr_Bitswap", "sar:status/us_attenuation", "sar:status/us_crc_minute", "sar:status/us_crc_per15min", "sar:status/us_delay", "sar:status/us_es", "sar:status/us_fec_minute", "sar:status/us_fec_per15min", "sar:status/us_margin", "sar:status/us_path", "sar:status/us_ses", "sar:status/vdsl_profile_string", "sar:status/dsl_train_state", "sar:status/dsl_carrier_state");

            stats.BitswapDownstream = GetBool(modemStats["sar:status/ds_path"]);
            stats.BitswapUpstream = GetBool(modemStats["sar:status/us_path"]);

            stats.CRCPerMinDownstream = GetDouble(modemStats["sar:status/ds_crc_minute"]); //Downstream CRC errors
            stats.CRCPerMinUpstream = GetDouble(modemStats["sar:status/us_crc_minute"]); // Upstream CRC errors

            stats.CurrentDslSyncRateDownstream = GetLong(modemStats["sar:status/dsl_ds_rate"]);
            stats.CurrentDslSyncRateUpstream = GetLong(modemStats["sar:status/dsl_us_rate"]);

            stats.DslTrainedModulation = GetByte(modemStats["sar:status/dsl_train_state"]);
            stats.DslTrainingState = GetByte(modemStats["sar:status/dsl_carrier_state"]);

            stats.FECPerMinDownstream = GetDouble(modemStats["sar:status/ds_fec_minute"]);
            stats.FECPerMinUpstream = GetDouble(modemStats["sar:status/us_fec_minute"]);

            stats.INPDownstream = GetDouble(modemStats["sar:status/exp_ds_inp_act"]);
            stats.INPUpstream = GetDouble(modemStats["sar:status/exp_us_inp_act"]);

            stats.LatencyDelayDownstream = GetByte(modemStats["sar:status/ds_delay"]);
            stats.LatencyModeDownstream = GetBool(modemStats["sar:status/ds_path"]); //might wanna change to a char...

            stats.LatencyDelayUpstream = GetByte(modemStats["sar:status/us_delay"]);
            stats.LatencyModeUpstream = GetBool(modemStats["sar:status/us_path"]);

            stats.LineAttenuationDownstream = GetByte(modemStats["sar:status/ds_attenuation"]);
            stats.LineAttenuationUpstream = GetByte(modemStats["sar:status/us_attenuation"]);//~not that it really matters.

            stats.SignalNoiseRatioDownstream = GetByte(modemStats["sar:status/ds_margin"]);
            stats.SignalNoiseRatioUpstream = GetByte(modemStats["sar:status/us_margin"]);

            stats.TextualLineProfile = modemStats["sar:status/vdsl_profile_string"];

            stats.CalcuateDLM();

            modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ATUC_vendor_ID", "sar:status/ATUC_vendor_version", "sar:status/dslam_VendorID", "sar:status/dslam_VendorID", "sar:status/dslam_VersionNumber", "sar:status/dslam_SerialNumber", "sar:status/DSP_Datapump_ver");

            stats.ATCUId = modemStats["sar:status/ATUC_vendor_ID"];

            stats.ATCUVendor = modemStats["sar:status/ATUC_vendor_version"];

            stats.DSLAMId = modemStats["sar:status/dslam_VendorID"];
            stats.DSLAMVersion = modemStats["sar:status/dslam_VersionNumber"];
            stats.DSLAMSerial = modemStats["sar:status/dslam_SerialNumber"];

            stats.DSLVersion = modemStats["sar:status/DSP_Datapump_ver"];

            modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ds_snrArrayXML", "sar:status/bitsArrayXML", "sar:status/pilot");

            stats.SNRGraph = modemStats["sar:status/ds_snrArrayXML"];

            stats.BitLoaderGraph = modemStats["sar:status/bitsArrayXML"];

            stats.BitPilotReference = (int)GetLong(modemStats["sar:status/pilot"]);

            modemStats = getInformationFromFritzLuaQuery(sid, conf, "box:status/localtime", "sar:settings/Annex", "sar:settings/DownstreamMarginOffset", "sar:settings/DsINP", "sar:settings/RFI_mode", "sar:settings/UsNoiseBits", "sar:status/AdvisedDownstreamMarginOffset", "sar:status/AdvisedDsINP", "sar:status/AdvisedRFI_mode", "sar:status/AdvisedUsNoiseBits", "sar:status/gui_version_number", "tr069:settings/UpgradesManaged", "logic:status/nspver", "logic:status/uptime_hours", "logic:status/uptime_minutes", "sar:status/modem_ShowtimeSecs");

            stats.DeviceCurrentTime = modemStats["box:status/localtime"];
            stats.Annex = modemStats["sar:settings/Annex"];
            stats.DownstreamMarginOffset = modemStats["sar:settings/DownstreamMarginOffset"];
            stats.DsINP = modemStats["sar:settings/DsINP"];
            stats.RFI_mode = modemStats["sar:settings/RFI_mode"];
            stats.UsNoiseBits = modemStats["sar:settings/UsNoiseBits"];
            stats.AdvisedDownstreamMarginOffset = modemStats["sar:status/AdvisedDownstreamMarginOffset"];
            stats.AdvisedDsINP = modemStats["sar:status/AdvisedDsINP"];
            stats.AdvisedRFIMode = modemStats["sar:status/AdvisedRFI_mode"];
            stats.AdvisedUsNoiseBits = modemStats["sar:status/AdvisedUsNoiseBits"];
            stats.FritzGuiVersion = modemStats["sar:status/gui_version_number"];
            stats.UpgradesManaged = GetBool(modemStats["tr069:settings/UpgradesManaged"]);
            stats.NspVersion = modemStats["logic:status/nspver"];

            DateTime local = DateTime.Now;

            try
            {
                local = Convert.ToDateTime(stats.DeviceCurrentTime);
            }
            catch (Exception)
            {
                //couldnt convert, using system time.
            }
            TimeSpan timediff = DateTime.Now - local;

            TimeSpan ts = new TimeSpan(Convert.ToInt32(GetLong(modemStats["logic:status/uptime_hours"])), Convert.ToInt32(GetLong(modemStats["logic:status/uptime_hours"])), 0);
            DateTime BootTime = local - ts;

            stats.DslUptimeTotalSeconds = ts.TotalSeconds;

            stats.DeviceBootTime = BootTime.ToString("HH:mm:ss dd.MM.yyyy");

            ts = new TimeSpan(0, 0, Convert.ToInt32(modemStats["sar:status/modem_ShowtimeSecs"]));
            DateTime ConnUpTime = local - ts;

            stats.DslConnectedSince = ConnUpTime.ToString("HH:mm:ss dd.MM.yyyy");

            if (timediff.Minutes > 5)
                conf.TimeOutOfAlignment = true;

            modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ds_los", "sar:status/us_los", "sar:status/ds_sef", "sar:status/us_sef", "sar:status/ds_fec", "sar:status/us_fec", "sar:status/ds_crc", "sar:status/us_crc", "sar:status/ds_es", "sar:status/us_es", "sar:status/ds_ses", "sar:status/us_ses", "sar:status/vdsl_profile", "sar:status/vdsl_transfer_mode");

            stats.LossOfSignalDownstream = GetLong(modemStats["sar:status/ds_los"]);
            stats.LossOfSignalUpstream = GetLong(modemStats["sar:status/us_los"]);

            stats.LossOfFrameDownstream = GetLong(modemStats["sar:status/ds_sef"]);
            stats.LossOfFrameUpstream = GetLong(modemStats["sar:status/us_sef"]);

            stats.FECDownstreamTotal = GetLong(modemStats["sar:status/ds_fec"]);
            stats.FECUpstreamTotal = GetLong(modemStats["sar:status/us_fec"]);

            stats.CRCDownstreamTotal = GetLong(modemStats["sar:status/ds_crc"]);
            stats.CRCUpstreamTotal = GetLong(modemStats["sar:status/us_crc"]);

            stats.ErroredSecondsDownstream = GetLong(modemStats["sar:status/ds_es"]);
            stats.ErroredSecondsUpstream = GetLong(modemStats["sar:status/us_es"]);

            stats.SeverelyErroredSecondsDownstream = GetLong(modemStats["sar:status/ds_ses"]);
            stats.SeverelyErroredSecondsUpstream = GetLong(modemStats["sar:status/us_ses"]);

            stats.VdslLineProfile = (DslInfo.VdslProfiles)GetByte(modemStats["sar:status/vdsl_profile"]);
            stats.VdslTransferMode = (DslInfo.VdslTransferModes)GetByte(modemStats["sar:status/vdsl_transfer_mode"]);

            stats.CalcuatedFECsPerMinDownstream = Math.Round(stats.FECDownstreamTotal / (stats.DslUptimeTotalSeconds / 60), 4);
            stats.CalcuatedFECsPerMinUpstream = Math.Round(stats.FECUpstreamTotal / (stats.DslUptimeTotalSeconds / 60), 4);

            stats.CalcuatedCRCsPerMinDownstream = Math.Round(stats.CRCDownstreamTotal / (stats.DslUptimeTotalSeconds / 60), 4);
            stats.CalcuatedCRCsPerMinUpstream = Math.Round(stats.CRCPerMinUpstream / (stats.DslUptimeTotalSeconds / 60), 4);
        }
예제 #9
0
        /// <summary>
        /// Gets the information from fritzbox lua Query.
        /// </summary>
        /// <param name="sid">String current sid for fritz</param>
        /// <param name="conf">Config current configurations for Fritz Log</param>
        /// <param name="query">String Array fields to Query from the Fritz</param>
        /// <returns>Dictionary </returns>
        private Dictionary<string, string> getInformationFromFritzLuaQuery(string sid, Config conf, params string[] query)
        {
            StringBuilder queryStr = new StringBuilder();
            foreach (string qr in query)
            {
                queryStr.Append(qr + "=" + qr + "&");
            }
            HttpWebRequest requestq = WebRequest.Create(@"http://" + conf.baseurl + "/query.lua?" + queryStr.ToString() + "sid=" + sid) as HttpWebRequest;
            requestq.Method = "GET";
            HttpWebResponse wrq = requestq.GetResponse() as HttpWebResponse;
            StreamReader readerq = new StreamReader(wrq.GetResponseStream());
            string strq = readerq.ReadToEnd();

            Dictionary<string, string> jsontest = JsonConvert.DeserializeObject<Dictionary<string, string>>(strq);

            return jsontest;
        }
예제 #10
0
        public void MonitorErrorRatesForMins(string sid, Config conf, ref DslInfo stats, int calcuationTime)
        {
            Console.WriteLine("Monitoring Error Rates for " + calcuationTime + " Mins");
            System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
            stopWatch.Start();
            Dictionary<string, string> modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ds_fec", "sar:status/us_fec", "sar:status/ds_crc", "sar:status/us_crc");

            long Lastdscrc = GetLong(modemStats["sar:status/ds_crc"]);
            long Lastuscrc = GetLong(modemStats["sar:status/us_crc"]);
            long Lastdsfec = GetLong(modemStats["sar:status/ds_fec"]);
            long Lastusfec = GetLong(modemStats["sar:status/us_fec"]);

            double[] dsfecCounts = new double[calcuationTime];
            double[] usfecCounts = new double[calcuationTime];
            double[] dscrcCounts = new double[calcuationTime];
            double[] uscrcCounts = new double[calcuationTime];

            System.IO.StreamWriter file = new StreamWriter(Environment.CurrentDirectory + @"\logs\errors\capture-" +
                             DateTime.Now.ToString("yyyyMMddHHmm") + ".csv");
            file.AutoFlush = true;
            file.WriteLine("time,crcdown,crcup,fecdown,fecup");
            Console.WriteLine( DateTime.Now );
            for (int i = 0; i < calcuationTime; i++)
            {
                Thread.Sleep(1000 * 60 * 5);
                modemStats = getInformationFromFritzLuaQuery(sid, conf, "sar:status/ds_fec", "sar:status/us_fec", "sar:status/ds_crc", "sar:status/us_crc");

                dsfecCounts[i] = GetLong(modemStats["sar:status/ds_fec"]) - Lastdsfec;
                usfecCounts[i] = GetLong(modemStats["sar:status/us_fec"]) - Lastusfec;

                dscrcCounts[i] = GetLong(modemStats["sar:status/ds_crc"]) - Lastdscrc;
                uscrcCounts[i] = GetLong(modemStats["sar:status/us_crc"]) - Lastuscrc;

                Lastdscrc = GetLong(modemStats["sar:status/ds_crc"]);
                Lastuscrc = GetLong(modemStats["sar:status/us_crc"]);
                Lastdsfec = GetLong(modemStats["sar:status/ds_fec"]);
                Lastusfec = GetLong(modemStats["sar:status/us_fec"]);
                TimeSpan ts = stopWatch.Elapsed;
                 string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}", ts.Hours, ts.Minutes, ts.Seconds);
                Console.WriteLine("(" + elapsedTime + ") CRC Downstream:" + dscrcCounts[i] + " Upstream: " + uscrcCounts[i] + " FEC Downstream: " + dsfecCounts[i] + " Upstream: " + usfecCounts[i]);
                file.WriteLine(DateTime.Now + "," + dscrcCounts[i] + "," + uscrcCounts[i] + "," + dsfecCounts[i] + "," + usfecCounts[i]);
                i = + 4;

            }

            file.Flush();
            file.Close();

            double dsfecaverage = RoundValue(dsfecCounts.Take(dsfecCounts.Count()).Average());
            double usfeccaverage = RoundValue(usfecCounts.Take(usfecCounts.Count()).Average());

            double dscrcaverage = RoundValue(dscrcCounts.Take(dscrcCounts.Count()).Average());
            double uscrccaverage = RoundValue(uscrcCounts.Take(uscrcCounts.Count()).Average());

            double dsfecStdDev = CalculateStdDev(from values in dsfecCounts select values);
            double usfecStdDev = CalculateStdDev(from values in usfecCounts select values);

            double dscrcStdDev = CalculateStdDev(from values in dscrcCounts select values);
            double uscrcStdDev = CalculateStdDev(from values in uscrcCounts select values);

            double test = CalculateStdDev(from values in dsfecCounts select values);

            Console.WriteLine("");
            Console.WriteLine("Averages - FEC Downstream: " + dsfecaverage + " Upstream: " + usfeccaverage + " CRC Downstream: " + dscrcaverage + " Upstream: " + uscrccaverage);
            Console.WriteLine("Standard Deviation  - FEC Downstream: " + dsfecStdDev + " Upstream: " + usfecStdDev + " CRC Downstream: " + dscrcStdDev + " Upstream: " + uscrcStdDev);
            Console.WriteLine("");
        }
예제 #11
0
        public string GetSid(string challenge, string response, Config conf)
        {
            string SID = "0000000000000000";
            if (conf.FritzOs5)
            {
                XDocument doc = XDocument.Load("http://" + conf.baseurl + "/login_sid.lua?username=&response=" + challenge + "-" + response);

                XElement info = doc.FirstNode as XElement;
                SID = info.Element("SID").Value;
            }
            else
            {
                HttpWebRequest request = WebRequest.Create("http://" + conf.baseurl + "/cgi-bin/webcm") as HttpWebRequest;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                string parameter = String.Format(@"login:command/response={0}-{1}&amp;getpage=../html/login_sid.xml", challenge, response);
                byte[] bytes = Encoding.ASCII.GetBytes(parameter);
                request.ContentLength = bytes.Length;
                Stream stream = request.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();
                HttpWebResponse wr = request.GetResponse() as HttpWebResponse;
                StreamReader reader = new StreamReader(wr.GetResponseStream());
                string str = reader.ReadToEnd();
                XDocument doc = XDocument.Parse(str);
                XElement info = doc.FirstNode as XElement;
                SID = info.Element("SID").Value;
            }
            return SID;
        }
예제 #12
0
        public string GetFirmwareVersion(Config conf)
        {
            try
            {
                XDocument doc = XDocument.Load("http://" + conf.baseurl + "/jason_boxinfo.xml");
                string ver = getXMLValue(doc, "Version", "http://jason.avm.de/updatecheck/");

                return ver;
            }
            catch (Exception e)
            {
                if (e.GetType() == typeof(WebException))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[Error] Cant connect to fritzbox.");
                }
                else if (e.GetType() == typeof(System.Xml.XmlException))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.Write("[Error] Cant Read XML.");
                }
                Console.ReadKey();

                Environment.Exit(0);

                return null; // doesnt get hit, but compiler is silly..
            }
        }