コード例 #1
0
 public static void TriggerSunsetActions(DateTime nextEventTime)
 {
     Logger.Info("TriggerSunsetActions");
     lock (syncLockCameraControl)
     {
         DahuaSunriseSunsetConfig cfg = new DahuaSunriseSunsetConfig();
         cfg.Load();
         ParallelOptions opt = new ParallelOptions();
         opt.MaxDegreeOfParallelism = NumberUtil.Clamp(cfg.DahuaCameras.Count, 1, 8);
         Parallel.ForEach(cfg.DahuaCameras, opt, (cam) =>
         {
             try
             {
                 WebClient wc   = new WebClient();
                 wc.Credentials = cam.GetCredentials();
                 WebRequestRobust(nextEventTime, wc, cam.GetUrlBase() + "cgi-bin/configManager.cgi?action=setConfig&VideoInMode[0].Config[0]=" + (int)cam.sunsetProfile);
                 HandleZoomAndFocus(nextEventTime, wc, cam, cam.nightZoom, cam.nightFocus);
             }
             catch (ThreadAbortException) { throw; }
             catch (Exception ex)
             {
                 Logger.Debug(ex);
             }
         });
     }
 }
コード例 #2
0
 public static void TriggerSunriseActions(DateTime nextEventTime)
 {
     Logger.Info("TriggerSunriseActions");
     lock (syncLockCameraControl)
     {
         DahuaSunriseSunsetConfig cfg = new DahuaSunriseSunsetConfig();
         cfg.Load();
         ParallelOptions opt = new ParallelOptions();
         opt.MaxDegreeOfParallelism = NumberUtil.Clamp(cfg.DahuaCameras.Count, 1, 8);
         Parallel.ForEach(cfg.DahuaCameras, opt, (cam) =>
         {
             try
             {
                 WebClient wc         = new WebClient();
                 wc.Credentials       = cam.GetCredentials();
                 int[] channelIndexes = cam.ChannelIndexes;
                 for (int i = 0; i < channelIndexes.Length; i++)
                 {
                     WebRequestRobust(nextEventTime, wc, cam.GetUrlBase() + "cgi-bin/configManager.cgi?action=setConfig&VideoInMode[" + channelIndexes[i] + "].Config[0]=" + (int)cam.sunriseProfile);
                     if (i + 1 < channelIndexes.Length)
                     {
                         Thread.Sleep(5000);
                     }
                 }
                 HandleZoomAndFocus(nextEventTime, wc, cam, cam.dayZoom, cam.dayFocus);
             }
             catch (ThreadAbortException) { throw; }
             catch (Exception ex)
             {
                 Logger.Debug(ex);
             }
         });
     }
 }
コード例 #3
0
        public Camera(string name, RegistryKey cameraKey)
        {
            this.name = name;

            RegEdit camera = new RegEdit(cameraKey);

            this.shortname    = camera.String("shortname");
            this.enabled      = camera.DWord("enabled") == 1;
            this.MaxRate      = NumberUtil.Clamp(Math.Round(10000000.0 / camera.DWord("interval")), 0, 255);
            this.CapType      = (ScreenCapType)camera.DWord("screencap");
            this.Hwva         = (HWAccelCamera)camera.DWord("ip_hwaccel");
            this.LimitDecode  = camera.DWord("smartdecode") == 1;
            this.WidthPx      = camera.DWord("fullxres");
            this.HeightPx     = camera.DWord("fullyres");
            this.Pixels       = this.WidthPx * this.HeightPx;
            this.Type         = (CameraType)camera.DWord("type");
            this.ip_subpath   = camera.String("ip_subpath");
            this.MainWidthPx  = camera.DWord("mainxres");
            this.MainHeightPx = camera.DWord("mainyres");
            this.MainPixels   = this.MainWidthPx * this.MainHeightPx;
            this.hasSubStream = !string.IsNullOrWhiteSpace(ip_subpath) &&
                                this.MainWidthPx != 0 &&
                                this.WidthPx != 0 &&
                                this.MainHeightPx != 0 &&
                                this.HeightPx != 0 &&
                                this.MainWidthPx != this.WidthPx &&
                                this.MainHeightPx != this.HeightPx;

            // Read profile-specific configurations
            for (int i = 1; i <= 7; i++)
            {
                recordSettings[i]  = new RecordTabSettings(cameraKey, i);
                triggerSettings[i] = new TriggerTabSettings(cameraKey, i);
            }
        }
コード例 #4
0
        private Tile TransformHeightToTile(int x, int y, double height)
        {
            int adjustedHeight = (int)Math.Ceiling(CircleGradient[x / 2, y / 2] * 1.2 * height);

            adjustedHeight = NumberUtil.Clamp(adjustedHeight, MinHeight, MaxHeight);

            double moisture = (GetNoise2D(3, 0.5f, 1, x, y) + 1d) / 2d;

            if (adjustedHeight < 5)
            {
                return(Tile.DeepWater);
            }

            if (adjustedHeight < 7)
            {
                return(Tile.Water);
            }

            if (adjustedHeight < 13)
            {
                return(Tile.ShallowWater);
            }

            if (adjustedHeight < 16)
            {
                return(Tile.Sand);
            }

            if (adjustedHeight < 40)
            {
                return(Tile.ValleyGrass);
            }

            if (adjustedHeight < 65)
            {
                return(Tile.ForestGrass);
            }

            if (adjustedHeight < 80)
            {
                return(Tile.Stone);
            }

            if (adjustedHeight < 95)
            {
                return(Tile.Mountain);
            }

            return(Tile.Snow);
        }
コード例 #5
0
		/// <summary>
		/// Parses the input string and returns true if it is valid or false if invalid. Also outputs an array of valid channel indexes that is guaranteed not to be empty.
		/// </summary>
		/// <param name="channelIndexes"></param>
		/// <returns></returns>
		public static bool GetChannelIndexes(string str, out int[] channelIndexes)
		{
			List<int> indexes = new List<int>();
			bool allOk = true;
			if (!string.IsNullOrWhiteSpace(str))
			{
				foreach (string strNum in str.Split(','))
				{
					if (int.TryParse(strNum.Trim(), out int num))
						indexes.Add(NumberUtil.Clamp(num - 1, 0, 255));
					else
						allOk = false;
				}
			}
			if (indexes.Count == 0)
				indexes.Add(0);
			channelIndexes = indexes.ToArray();
			return allOk;
		}
コード例 #6
0
        public void Load()
        {
            ComputerInfo computerInfo = new ComputerInfo();

            MemMB     = (int)(computerInfo.TotalPhysicalMemory / 1000000);
            MemFreeMB = (int)(computerInfo.AvailablePhysicalMemory / 1000000);

            using (PerformanceCounter totalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
            {
                totalCpuCounter.NextValue();
                Stopwatch sw = new Stopwatch();
                sw.Start();
                List <Process> biProcs = Process.GetProcesses().Where(p => p.ProcessName.ToLower() == "blueiris").ToList();
                if (biProcs.Count < 1)
                {
                    Logger.Info("Unable to calculate BI Active Stats because Blue Iris is not running.");
                    return;
                }
                TimeSpan[] startTimes = new TimeSpan[biProcs.Count];
                for (int i = 0; i < biProcs.Count; i++)
                {
                    startTimes[i] = biProcs[i].TotalProcessorTime;
                }

                // Wait for CPU usage to happen.
                Thread.Sleep(Debugger.IsAttached ? 1000 : 10000);

                // Take CPU usage measurements.
                CpuUsage = (byte)Math.Round(totalCpuCounter.NextValue());
                sw.Stop();
                TimeSpan totalTime = TimeSpan.Zero;
                for (int i = 0; i < biProcs.Count; i++)
                {
                    biProcs[i].Refresh();
                    if (biProcs[i].HasExited)
                    {
                        Logger.Info("Unable to calculate BI Active Stats because Blue Iris exited while CPU usage was being measured.");
                        return;
                    }
                    totalTime += biProcs[i].TotalProcessorTime - startTimes[i];
                }
                double fraction = totalTime.TotalMilliseconds / sw.Elapsed.TotalMilliseconds;
                BiCpuUsage = (byte)Math.Round((fraction / Environment.ProcessorCount) * 100);
                // Done with CPU usage

                long physicalMemUsage = 0;
                long virtualMemUsage  = 0;
                foreach (Process p in biProcs)
                {
                    if (BiVersion == null)
                    {
                        BiVersion = p.MainModule.FileVersionInfo.FileVersion + " " + (Is64Bit(p) ? "x64" : "x86");
                    }
                    physicalMemUsage += p.WorkingSet64;
                    virtualMemUsage  += p.VirtualMemorySize64;
                }
                BiMemUsageMB            = (int)(physicalMemUsage / 1000000);
                BiPeakVirtualMemUsageMB = (int)(virtualMemUsage / 1000000);
                // Done with MEM usage

                foreach (Process p in biProcs)
                {
                    IntPtr handle = p.MainWindowHandle;
                    if (handle == IntPtr.Zero)
                    {
                        // This is the service.
                    }
                    else
                    {
                        // This is the console.
                        ConsoleOpen = true;
                        try
                        {
                            WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
                            if (GetWindowPlacement(handle, ref placement))
                            {
                                if (placement.showCmd == 2)
                                {
                                    // Minimized
                                    ConsoleWidth  = -2;
                                    ConsoleHeight = -2;
                                }
                                else
                                {
                                    // Not Minimized
                                    RECT Rect = new RECT();
                                    if (GetWindowRect(handle, ref Rect))
                                    {
                                        ConsoleWidth  = (short)NumberUtil.Clamp(Rect.right - Rect.left, 0, short.MaxValue);
                                        ConsoleHeight = (short)NumberUtil.Clamp(Rect.bottom - Rect.top, 0, short.MaxValue);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex);
                        }
                    }
                }
                if (biProcs.Count > 1 && !ConsoleOpen)
                {
                    ConsoleOpen = true;
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Creates an anonymous usage record.  This method spends 10 seconds measuring CPU usage.  Returns null if any BlueIris.exe processes close while CPU usage is being measured, or if no BlueIris.exe processes were open.
        /// </summary>
        /// <returns></returns>
        public static Upload_Record GetPerfDataRecord()
        {
            Upload_Record record = new Upload_Record();

            // Begin measuring CPU usage.
            using (PerformanceCounter totalCpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"))
            {
                totalCpuCounter.NextValue();
                Stopwatch sw = new Stopwatch();
                sw.Start();
                List <Process> biProcs = Process.GetProcesses().Where(p => p.ProcessName.ToLower() == "blueiris").ToList();
                if (biProcs.Count < 1)
                {
                    Logger.Info("Unable to generate anonymous performance data record because Blue Iris is not running.");
                    return(null);
                }
                TimeSpan[] startTimes = new TimeSpan[biProcs.Count];
                for (int i = 0; i < biProcs.Count; i++)
                {
                    startTimes[i] = biProcs[i].TotalProcessorTime;
                }

                // Wait for CPU usage to happen.
                Thread.Sleep(10000);

                // Take CPU usage measurements.
                record.CpuUsage = (byte)Math.Round(totalCpuCounter.NextValue());
                sw.Stop();
                TimeSpan totalTime = TimeSpan.Zero;
                for (int i = 0; i < biProcs.Count; i++)
                {
                    biProcs[i].Refresh();
                    if (biProcs[i].HasExited)
                    {
                        Logger.Info("Unable to generate anonymous performance data record because Blue Iris exited while CPU usage was being measured.");
                        return(null);
                    }
                    totalTime += biProcs[i].TotalProcessorTime - startTimes[i];
                }
                double fraction = totalTime.TotalMilliseconds / sw.Elapsed.TotalMilliseconds;
                record.BiCpuUsage = (byte)Math.Round((fraction / Environment.ProcessorCount) * 100);
                record.CpuThreads = (short)Environment.ProcessorCount;

                long physicalMemUsage = 0;
                long virtualMemUsage  = 0;
                foreach (Process p in biProcs)
                {
                    if (record.BiVersion == null)
                    {
                        record.BiVersion = p.MainModule.FileVersionInfo.FileVersion + " " + (MainSvc.Is64Bit(p) ? "x64" : "x86");
                    }
                    physicalMemUsage += p.WorkingSet64;
                    virtualMemUsage  += p.VirtualMemorySize64;
                }
                record.BiMemUsageMB            = (int)(physicalMemUsage / 1000000);
                record.BiPeakVirtualMemUsageMB = (int)(virtualMemUsage / 1000000);

                foreach (Process p in biProcs)
                {
                    IntPtr handle = p.MainWindowHandle;
                    if (handle == IntPtr.Zero)
                    {
                        // This is the service.
                    }
                    else
                    {
                        // This is the console.
                        record.ConsoleOpen = true;
                        try
                        {
                            WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
                            if (GetWindowPlacement(handle, ref placement))
                            {
                                if (placement.showCmd == 2)
                                {
                                    // Minimized
                                    record.ConsoleWidth  = -2;
                                    record.ConsoleHeight = -2;
                                }
                                else
                                {
                                    // Not Minimized
                                    RECT Rect = new RECT();
                                    if (GetWindowRect(handle, ref Rect))
                                    {
                                        record.ConsoleWidth  = (short)NumberUtil.Clamp(Rect.right - Rect.left, 0, short.MaxValue);
                                        record.ConsoleHeight = (short)NumberUtil.Clamp(Rect.bottom - Rect.top, 0, short.MaxValue);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Debug(ex);
                        }
                    }
                }
                if (biProcs.Count > 1 && !record.ConsoleOpen)
                {
                    record.ConsoleOpen = true;
                }
            }

            record.Secret = Program.settings.secret;
            record.OS     = GetOsVersion();
            CpuInfo cpuInfo = GetCpuInfo();

            if (cpuInfo == null)
            {
                record.CpuModel = "Unknown";
                record.CpuMHz   = NumberUtil.ParseInt(cpuInfo.maxClockSpeed);
            }
            else
            {
                record.CpuModel = cpuInfo.GetModel();
                record.CpuMHz   = NumberUtil.ParseInt(cpuInfo.maxClockSpeed);
            }
            record.HelperVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            record.HwAccel       = (byte)RegistryUtil.GetHKLMValue <int>(@"SOFTWARE\Perspective Software\Blue Iris\Options", "hwaccel", 0);
            record.ServiceMode   = RegistryUtil.GetHKLMValue <int>(@"SOFTWARE\Perspective Software\Blue Iris\Options", "Service", 0) == 1;
            if (RegistryUtil.GetHKLMValue <int>(@"SOFTWARE\Perspective Software\Blue Iris\Options", "limitlive", 0) == 0)
            {
                record.LivePreviewFPS = -2;
            }
            else
            {
                record.LivePreviewFPS = (short)RegistryUtil.GetHKLMValue <int>(@"SOFTWARE\Perspective Software\Blue Iris\Options", "livefps", -1);
            }

            ComputerInfo computerInfo = new ComputerInfo();

            record.MemMB     = (int)(computerInfo.TotalPhysicalMemory / 1000000);
            record.MemFreeMB = (int)(computerInfo.AvailablePhysicalMemory / 1000000);

            RamInfo ramInfo = GetRamInfo();

            record.RamGiB        = ramInfo.GiB;
            record.RamChannels   = ramInfo.Channels;
            record.DimmLocations = ramInfo.DimmLocations;
            record.RamMHz        = ramInfo.MHz;

            // Get camera info.
            // Get frame rates (only accessible via BI's web server).
            Dictionary <string, double> fpsMap = new Dictionary <string, double>();

            BiServerInfo.Reload();
            if (BiServerInfo.enabled)
            {
                try
                {
                    using (WebClient wc = new WebClient())
                    {
                        string session  = CameraWebInterfaceLinker.GetSecureAuthenticatedSession(wc);
                        string response = wc.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"camlist\",\"session\":\"" + session + "\"}");
                        wc.UploadString(CameraWebInterfaceLinker.GetJsonURL(), "{\"cmd\":\"logout\",\"session\":\"" + session + "\"}");
                        CamListResponse camListResponse = JsonConvert.DeserializeObject <CamListResponse>(response);
                        if (camListResponse != null && camListResponse.result == "success")
                        {
                            foreach (CameraListCamera camera in camListResponse.data)
                            {
                                if (camera.group == null)
                                {
                                    fpsMap[camera.optionValue] = camera.FPS;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(ex, "Error reading camera list from web server.");
                }
            }

            // Get camera info from registry
            List <Upload_Camera> cameras = new List <Upload_Camera>();

            RegistryKey camerasKey = RegistryUtil.GetHKLMKey(@"SOFTWARE\Perspective Software\Blue Iris\Cameras");

            foreach (string camName in camerasKey.GetSubKeyNames())
            {
                RegistryKey camKey = camerasKey.OpenSubKey(camName);
                if (RegistryUtil.GetIntValue(camKey, "enabled", 0) != 1)
                {
                    continue;
                }
                string        shortName = RegistryUtil.GetStringValue(camKey, "shortname");
                Upload_Camera cam       = new Upload_Camera();

                if (fpsMap.TryGetValue(shortName, out double fps))
                {
                    cam.FPS = (byte)NumberUtil.Clamp(Math.Round(fps), 0, 255);
                }
                else
                {
                    int interval = RegistryUtil.GetIntValue(camKey, "interval", 1000000);
                    if (interval <= 0)
                    {
                        cam.FPS = 0;
                    }
                    else
                    {
                        cam.FPS = (byte)NumberUtil.Clamp(Math.Round(10000000.0 / interval), 0, 255);
                    }
                }
                cam.CapType     = (byte)RegistryUtil.GetIntValue(camKey, "screencap", 0);
                cam.Hwaccel     = (byte)RegistryUtil.GetIntValue(camKey, "ip_hwaccel", 0);
                cam.LimitDecode = RegistryUtil.GetIntValue(camKey, "smartdecode", 0) == 1;
                cam.Pixels      = RegistryUtil.GetIntValue(camKey, "fullxres", 0) * RegistryUtil.GetIntValue(camKey, "fullyres", 0);
                cam.Type        = (byte)RegistryUtil.GetIntValue(camKey, "type", 0);
                RegistryKey motionKey = camKey.OpenSubKey("Motion");
                cam.MotionDetector    = RegistryUtil.GetIntValue(motionKey, "enabled", 0) == 1;
                cam.RecordTriggerType = (byte)RegistryUtil.GetIntValue(motionKey, "continuous", 0);
                RegistryKey clipsKey = camKey.OpenSubKey("Clips");
                cam.RecordFormat = (byte)RegistryUtil.GetIntValue(clipsKey, "movieformat", 0);
                cam.DirectToDisk = RegistryUtil.GetIntValue(clipsKey, "transcode", 0) == 0;
                cam.VCodec       = RegistryUtil.GetStringValue(clipsKey, "vcodec");
                cameras.Add(cam);
            }

            record.cameras = cameras.ToArray();
            record.gpus    = GetGpuInfo().Select(g => new Upload_Gpu()
            {
                Name = g.Name, Version = g.DriverVersion
            }).ToArray();

            return(record);
        }