Пример #1
0
        private void UpdateProfile()
        {
            string last = "Default";

            if (AppSettings.Settings.ImageAdjustProfiles.Count == 0)
            {
                AppSettings.Settings.ImageAdjustProfiles.Add(new ClsImageAdjust("Default"));
            }


            if (!string.IsNullOrEmpty(this.comboBox1.Text.Trim()))
            {
                last = this.comboBox1.Text.Trim();

                this.CurIA = AITOOL.GetImageAdjustProfileByName(this.comboBox1.Text.Trim(), false);

                if (this.CurIA == null)
                {
                    this.CurIA = new ClsImageAdjust(this.comboBox1.Text, tb_jpegquality.Text, tb_SizePercent.Text, tb_Width.Text, tb_Height.Text, tb_brightness.Text, tb_contrast.Text);
                    AppSettings.Settings.ImageAdjustProfiles.Add(this.CurIA);
                }
                else
                {
                    this.CurIA.Update(this.comboBox1.Text, tb_jpegquality.Text, tb_SizePercent.Text, tb_Width.Text, tb_Height.Text, tb_brightness.Text, tb_contrast.Text);
                }
            }

            this.comboBox1.Items.Clear();

            int i      = 0;
            int oldidx = 0;

            foreach (ClsImageAdjust ia in AppSettings.Settings.ImageAdjustProfiles)
            {
                this.comboBox1.Items.Add(ia.Name);
                if (string.Equals(last.Trim(), ia.Name.Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    oldidx = i + 1;
                }
                i++;
            }

            if (this.comboBox1.Items.Count > 0)
            {
                this.comboBox1.SelectedIndex = oldidx;
            }

            this.CurIA = AITOOL.GetImageAdjustProfileByName(this.comboBox1.Text.Trim(), false);
        }
Пример #2
0
        /********************* Start EVENT section*************************************/

        private void Frm_CustomMasking_Load(object sender, EventArgs e)
        {
            Global_GUI.RestoreWindowState(this);
            this._maskfilename = AITOOL.GetMaskFile(this.Cam.Name);
            this.Text          = "Custom Masking - " + this._maskfilename;

            if (!File.Exists(this._maskfilename))
            {
                this.Text += " (Missing)";
            }

            this.BrushSize          = this.Cam.mask_brush_size;
            this.numBrushSize.Value = this.Cam.mask_brush_size;
            this.ShowImage();
        }
Пример #3
0
        private void comboBox_filter_camera_SelectionChangeCommitted(object sender, EventArgs e)
        {
            //I think this event only triggers when user picks something NOT when items are initially added to combobox
            if (!(this.comboBox_filter_camera.Text == "All Cameras"))
            {
                this.BtnDynamicMaskingSettings.Enabled = true;
                this.cam = AITOOL.GetCamera(this.comboBox_filter_camera.Text);
            }
            else
            {
                this.BtnDynamicMaskingSettings.Enabled = false;
            }

            this.Refresh();
        }
Пример #4
0
        public bool CopyFileTo(string outputFilePath)
        {
            bool ret = false;

            int bufferSize = 1024 * 1024;

            try
            {
                if (this.IsValid())  //loads into memory if not already loaded
                {
                    DirectoryInfo d = new DirectoryInfo(Path.GetDirectoryName(outputFilePath));
                    if (d.Root != null && !d.Exists)
                    {
                        //dont try to create if working off root drive
                        d.Create();
                    }
                    Stream inStream = this.ToStream();

                    if (File.Exists(outputFilePath))
                    {
                        File.Delete(outputFilePath);
                    }

                    using (FileStream fileStream = new FileStream(outputFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                    {
                        fileStream.SetLength(inStream.Length);
                        int    bytesRead = -1;
                        byte[] bytes     = new byte[bufferSize];

                        while ((bytesRead = inStream.Read(bytes, 0, bufferSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, bytesRead);
                        }
                    }
                    ret = true;
                }
                else
                {
                    AITOOL.Log($"Error: File not valid: {this.image_path}");
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: Copying to {outputFilePath}: {Global.ExMsg(ex)}");
            }

            return(ret);
        }
        private void SetROM()
        {
            try
            {
                if (this.ROMName.IsEmpty())
                {
                    return;
                }

                this.TempObjectManager = null;

                foreach (Camera cam in AppSettings.Settings.CameraList)
                {
                    foreach (PropertyInfo prop in cam.GetType().GetProperties())
                    {
                        if (prop.PropertyType == typeof(ClsRelevantObjectManager))
                        {
                            ClsRelevantObjectManager rom = (ClsRelevantObjectManager)prop.GetValue(cam);
                            if ($"{cam.Name}\\{rom.TypeName}".EqualsIgnoreCase(this.ROMName))
                            {
                                this.TempObjectManager = rom;
                                break;
                            }
                        }
                    }

                    string item = $"{cam.Name}\\{cam.maskManager.MaskTriggeringObjects.TypeName}";
                    if (item.EqualsIgnoreCase(this.ROMName))
                    {
                        this.TempObjectManager = cam.maskManager.MaskTriggeringObjects;
                        break;
                    }
                }

                if (this.TempObjectManager.IsNull())
                {
                    MessageBox.Show($"Error: Could not match '{this.ROMName}' to existing RelevantObjectManager?");
                }
                else
                {
                    this.TempObjectManager.Update();
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {ex.Message}");
            }
        }
Пример #6
0
        private async Task <PushoverUserResponse> PushoverPost(Uri uri, MultipartFormDataContent parameters)
        {
            PushoverUserResponse ret = new PushoverUserResponse();

            if (this.httpClient == null)
            {
                this.httpClient         = new HttpClient();
                this.httpClient.Timeout = TimeSpan.FromSeconds(AppSettings.Settings.HTTPClientTimeoutSeconds);
            }

            // Remove content type that is not in the docs
            //foreach (HttpContent param in parameters)
            //    param.Headers.ContentType = null;

            try
            {
                HttpResponseMessage response = null;
                string json = "";

                response = await httpClient.PostAsync(uri, parameters);

                json = Global.CleanString(response.Content.ReadAsStringAsync().Result);

                if (response.IsSuccessStatusCode && !string.IsNullOrWhiteSpace(json))
                {
                    //var json = this.Encoding.GetString(await wc.UploadValuesTaskAsync(uri, parameters).ConfigureAwait(false));
                    ret = await ParseResponse <PushoverUserResponse>(json, response.Headers);
                }
                else
                {
                    if (response.StatusCode.ToString().Contains("TooLarge"))
                    {
                        ret.Errors = new string[] { $"StatusCode='{response.StatusCode}', Reason='{response.ReasonPhrase}' (Max pushover attachment size is 2.5MB), ResponseText='{json}'" };
                    }
                    else
                    {
                        ret.Errors = new string[] { $"StatusCode='{response.StatusCode}', Reason='{response.ReasonPhrase}', ResponseText='{json}'" };
                    }
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {Global.ExMsg(ex)}");
                ret.Errors = new string[] { Global.ExMsg(ex) };
            }

            return(ret);
        }
        private void FillCombo()
        {
            try
            {
                toolStripComboBoxCameras.Items.Clear();
                int idx = 0;
                int fnd = -1;
                foreach (Camera cam in AppSettings.Settings.CameraList)
                {
                    foreach (PropertyInfo prop in cam.GetType().GetProperties())
                    {
                        if (prop.PropertyType == typeof(ClsRelevantObjectManager))
                        {
                            ClsRelevantObjectManager rom = (ClsRelevantObjectManager)prop.GetValue(cam);
                            string item = $"{cam.Name}\\{rom.TypeName}";
                            toolStripComboBoxCameras.Items.Add(item);
                            if (item.EqualsIgnoreCase(this.ROMName))
                            {
                                fnd = idx;
                            }
                            idx++;
                        }
                    }
                    string item2 = $"{cam.Name}\\{cam.maskManager.MaskTriggeringObjects.TypeName}";
                    toolStripComboBoxCameras.Items.Add(item2);
                    if (item2.EqualsIgnoreCase(this.ROMName))
                    {
                        fnd = idx;
                    }
                    idx++;
                }

                if (fnd != -1)
                {
                    toolStripComboBoxCameras.SelectedIndex = fnd;
                }
                else if (idx > 0)
                {
                    toolStripComboBoxCameras.SelectedIndex = 0;
                }

                this.Text = $"Relevant Objects - {this.ROMName}";
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {ex.Message}");
            }
        }
Пример #8
0
        public void FromString(string Objects)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            try
            {
                //take anything before the first semicolon:
                if (Objects.Contains(";"))
                {
                    Objects = Objects.GetWord("", ";");
                }

                this.EnabledCount = 0;
                int order = 0;

                List <string> lst    = Objects.SplitStr(",");
                List <string> deflst = AppSettings.Settings.ObjectPriority.ToLower().SplitStr(",");

                foreach (var obj in lst)
                {
                    ClsRelevantObject ro = new ClsRelevantObject(obj);

                    if (!ObjectDict.Contains(ro.Name.ToLower()))
                    {
                        if (ro.Enabled)
                        {
                            this.EnabledCount++;
                        }

                        order = deflst.IndexOf(ro.Name.ToLower());

                        if (order > -1)
                        {
                            ro.Priority = order + 1;
                        }

                        ObjectDict.Add(ro.Name.ToLower(), ro);
                    }
                }

                AddDefaults();
            }
            catch (Exception ex)
            {
                AITOOL.Log("Error: " + ex.Msg());
            }
        }
Пример #9
0
        private void addAmazonReToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ClsURLItem url = new ClsURLItem("", AppSettings.Settings.AIURLList.Count + 1, URLTypeEnum.AWSRekognition_Objects);

            if (!AppSettings.Settings.AIURLList.Contains(url))
            {
                this.CurURL = url;
                AppSettings.Settings.AIURLList.Add(url);
                Global_GUI.UpdateFOLV(FOLV_AIServers, AppSettings.Settings.AIURLList, UseSelected: true, SelectObject: this.CurURL, FullRefresh: true);
                AITOOL.UpdateAIURLs();
            }
            else
            {
                MessageBox.Show("Already exists");
            }
            UpdateButtons();
        }
Пример #10
0
        private void FOLV_MaskHistory_SelectionChanged(object sender, EventArgs e)
        {
            this.CurObjPosLst.Clear();

            if (this.FOLV_MaskHistory.SelectedObjects != null && this.FOLV_MaskHistory.SelectedObjects.Count > 0)
            {
                this.contextMenuPosObj = (ObjectPosition)this.FOLV_MaskHistory.SelectedObjects[0];
                this.cam = AITOOL.GetCamera(this.contextMenuPosObj.CameraName);

                this.ShowMaskImage();

                foreach (object obj in this.FOLV_MaskHistory.SelectedObjects)
                {
                    this.CurObjPosLst.Add((ObjectPosition)obj);
                }
            }
            this.pictureBox1.Refresh();
        }
Пример #11
0
        private void FOLV_Masks_SelectionChanged(object sender, EventArgs e)
        {
            this.CurObjPosLst.Clear();

            if (FOLV_Masks.SelectedObjects != null && FOLV_Masks.SelectedObjects.Count > 0)
            {
                contextMenuPosObj = (ObjectPosition)FOLV_Masks.SelectedObject;
                this.cam          = AITOOL.GetCamera(contextMenuPosObj.cameraName);

                ShowMaskImage();

                foreach (object obj in FOLV_Masks.SelectedObjects)
                {
                    CurObjPosLst.Add((ObjectPosition)obj);
                }
            }
            pictureBox1.Refresh();
        }
Пример #12
0
        private void Updateformat()
        {
            try
            {
                lbl_Confidence.Text = string.Format(tb_ConfidenceFormat.Text.Trim(), 99.123);
                if (!string.IsNullOrEmpty(tb_ConfidenceFormat.Text.Trim()))
                {
                    AppSettings.Settings.DisplayPercentageFormat = tb_ConfidenceFormat.Text.Trim();
                }

                lbl_Confidence.ForeColor = Color.DarkGreen;
                lbl_DetectionFormat.Text = AITOOL.ReplaceParams(cam, null, null, tb_DetectionFormat.Text, Global.IPType.Path);
                lbl_DetectionFormat.Text = lbl_DetectionFormat.Text.Replace("[]", "").Replace("()", "").Replace("   ", " ").Replace("  ", " ");
            }
            catch (Exception)
            {
                lbl_Confidence.ForeColor = Color.Red;
            }
        }
Пример #13
0
        private void FOLV_AIServers_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.FOLV_AIServers.SelectedObjects != null && this.FOLV_AIServers.SelectedObjects.Count > 0)
                {
                    this.CurURL = (ClsURLItem)this.FOLV_AIServers.SelectedObjects[0];
                }
                else
                {
                    this.CurURL = null;
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {ex.Msg()}");
            }

            UpdateButtons();
        }
        private void SaveRO([CallerMemberName()] string memberName = null)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.
            try
            {
                if (!Loading && NeedsSaving && !this.ro.IsNull() && !this.tb_Name.Text.IsEmpty())
                {
                    this.ro.Enabled           = this.cb_enabled.Checked;
                    this.ro.Name              = this.tb_Name.Text;
                    this.ro.ActiveTimeRange   = this.tb_Time.Text;
                    this.ro.Trigger           = this.cb_ObjectTriggers.Checked;
                    this.ro.IgnoreImageMask   = this.cb_ObjectIgnoreImageMask.Checked;
                    this.ro.IgnoreDynamicMask = this.cb_ObjectIgnoreDynamicMask.Checked;
                    double lower = this.tb_ConfidenceLower.Text.ToDouble();
                    double upper = this.tb_ConfidenceUpper.Text.ToDouble();
                    //if (!this.TempObjectManager.TypeName.EqualsIgnoreCase("default"))
                    //{
                    //    ClsRelevantObject ro = this.TempObjectManager.Get(this.ro.Name, false, out int FoundIDX, UseMainCamList: true);
                    //    if (!ro.IsNull() && lower < ro.Threshold_lower || upper > ro.Threshold_upper)
                    //    {
                    //        MessageBox.Show($"The threshold cannot be lower or higher than {this.TempObjectManager.CameraName}\\Default setting: ({ro.Threshold_lower}-{ro.Threshold_upper}%)");
                    //        return;
                    //    }
                    //}
                    this.ro.Threshold_lower = lower;
                    this.ro.Threshold_upper = upper;

                    this.ro.PredSizeMinPercentOfImage = tb_MinPercent.Text.ToDouble();
                    this.ro.PredSizeMaxPercentOfImage = tb_maxpercent.Text.ToDouble();
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log("Error: " + ex.Msg());
            }
            finally
            {
                this.FOLV_RelevantObjects.Refresh();
                NeedsSaving = false;
            }
        }
Пример #15
0
        private void UpdateCombo()
        {
            string last = "Default";

            if (AppSettings.Settings.ImageAdjustProfiles.Count == 0)
            {
                AppSettings.Settings.ImageAdjustProfiles.Add(new ClsImageAdjust("Default"));
            }

            if (!string.IsNullOrEmpty(this.comboBox1.Text.Trim()))
            {
                last = this.comboBox1.Text.Trim();
            }

            if (!AITOOL.HasImageAdjustProfile(this.comboBox1.Text.Trim()) && !string.IsNullOrEmpty(this.comboBox1.Text.Trim()))
            {
                AppSettings.Settings.ImageAdjustProfiles.Add(new ClsImageAdjust(this.comboBox1.Text.Trim()));
            }

            this.comboBox1.Items.Clear();

            int i      = 0;
            int oldidx = 0;

            foreach (ClsImageAdjust ia in AppSettings.Settings.ImageAdjustProfiles)
            {
                this.comboBox1.Items.Add(ia.Name);
                if (string.Equals(last.Trim(), ia.Name.Trim(), StringComparison.OrdinalIgnoreCase))
                {
                    oldidx = i + 1;
                }
                i++;
            }

            if (this.comboBox1.Items.Count > 0)
            {
                this.comboBox1.SelectedIndex = oldidx;
            }

            this.CurIA = AITOOL.GetImageAdjustProfileByName(this.comboBox1.Text.Trim());
        }
Пример #16
0
        public void ShowCamera()
        {
            if (cmb_cameras.Text.Trim().EqualsIgnoreCase("all cameras"))
            {
                this.CurrentCam = AITOOL.GetCamera("default", true);
            }
            else
            {
                this.CurrentCam = AITOOL.GetCamera(cmb_cameras.Text.Trim());
            }

            cb_Paused.Checked         = this.CurrentCam.Paused;
            tb_minutes.Text           = this.CurrentCam.PauseMinutes.ToString();
            cb_FileMonitoring.Checked = this.CurrentCam.PauseFileMon;
            cb_MQTT.Checked           = this.CurrentCam.PauseMQTT;
            cb_Pushover.Checked       = this.CurrentCam.PausePushover;
            cb_Telegram.Checked       = this.CurrentCam.PauseTelegram;
            cb_URL.Checked            = this.CurrentCam.PauseURL;

            UpdateButton();
        }
Пример #17
0
        public MemoryStream ToStream()
        {
            MemoryStream ms = new MemoryStream();

            if (this.IsValid())
            {
                try
                {
                    ms = new MemoryStream(this.ImageByteArray, false);
                }
                catch (Exception ex)
                {
                    AITOOL.Log($"Error: Cannot convert to MemoryStream: {ex.Message}");
                }
            }
            else
            {
                AITOOL.Log($"Error: Cannot convert to MemoryStream because image is not valid.");
            }
            return(ms);
        }
        private void SaveROM()
        {
            try
            {
                if (this.ROMName.IsEmpty())
                {
                    return;
                }


                foreach (Camera cam in AppSettings.Settings.CameraList)
                {
                    foreach (PropertyInfo prop in cam.GetType().GetProperties())
                    {
                        if (prop.PropertyType == typeof(ClsRelevantObjectManager))
                        {
                            ClsRelevantObjectManager rom = (ClsRelevantObjectManager)prop.GetValue(cam);
                            if ($"{cam.Name}\\{rom.TypeName}".EqualsIgnoreCase(this.ROMName))
                            {
                                rom.ObjectList = this.TempObjectManager.ObjectList;
                                //rom = this.TempObjectManager;
                                break;
                            }
                        }
                    }

                    string item = $"{cam.Name}\\{cam.maskManager.MaskTriggeringObjects.TypeName}";
                    if (item.EqualsIgnoreCase(this.ROMName))
                    {
                        cam.maskManager.MaskTriggeringObjects.ObjectList = this.TempObjectManager.ObjectList;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {ex.Message}");
            }
        }
Пример #19
0
 private void bt_variables_Click(object sender, EventArgs e)
 {
     try
     {
         string         vars    = "[Camera];[Prefix];[CamInputFolder];[InputFolder];[ImagePath];[ImagePathEscaped];[ImageFilename];[ImageFilenameNoExt];[Username];[Password];[BlueIrisServerIP];[BlueIrisURL];[SummaryNonEscaped];[Summary];[Detection];[Label];[Detail];[Result];[Position];[Confidence];[Detections];[Confidences];[SummaryJson];[DetectionsJson];[AllJson];[PercentOfImage];%DATE%;%TIME%;%DATETIME%;%TEMP%;%APPDATA%;%USERPROFILE%;%USERNAME%";
         List <string>  varlist = vars.SplitStr(";");
         List <ClsProp> props   = new List <ClsProp>();
         foreach (var varitm in varlist)
         {
             string value = AITOOL.ReplaceParams(cam, null, null, varitm, Global.IPType.URL);
             props.Add(new ClsProp(varitm, value));
         }
         using (Frm_Variables frm = new Frm_Variables())
         {
             frm.props = props;
             frm.ShowDialog();
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error: " + ex.Message);
     }
 }
Пример #20
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.
            try
            {
                SaveRO();

                List <ClsRelevantObject> rolist = new List <ClsRelevantObject>();
                foreach (ClsRelevantObject ro in FOLV_RelevantObjects.Objects)
                {
                    rolist.Add(ro);
                }

                this.ObjectManager.FromList(rolist);

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                AITOOL.Log("Error: " + ex.Msg());
            }
        }
Пример #21
0
        private void UpdateMaskFile()
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            try
            {
                this._maskfilename = this.Cam.GetMaskFile(false, null, this._imageRes);
                this.Text          = "Custom Masking - " + this._maskfilename;

                if (!File.Exists(this._maskfilename))
                {
                    this.Text += " (Missing)";
                }

                this.BrushSize          = this.Cam.mask_brush_size;
                this.numBrushSize.Value = this.Cam.mask_brush_size;
                this.ShowImage();
            }
            catch (Exception ex)
            {
                AITOOL.Log($"Error: {ex.Msg()}");
            }
        }
Пример #22
0
        public override string ToString()
        {
            //LabelDisplayFormat = "[Detection] [[Detail]] ({0:0}%)"

            if (this._cam == null)
            {
                this._cam = AITOOL.GetCamera(this.Camera);
            }

            //Dont call this or we get a stack overflow!
            //string ret = AITOOL.ReplaceParams(this._cam, null, this._curimg, this._cam.DetectionDisplayFormat, this);

            string ret = this._cam.DetectionDisplayFormat;

            ret = Global.ReplaceCaseInsensitive(ret, "[label]", this.Label); //only gives first detection
            ret = Global.ReplaceCaseInsensitive(ret, "[detail]", this.Detail);
            ret = Global.ReplaceCaseInsensitive(ret, "[result]", this.Result.ToString());
            ret = Global.ReplaceCaseInsensitive(ret, "[position]", this.PositionString());
            ret = Global.ReplaceCaseInsensitive(ret, "[confidence]", this.ConfidenceString());
            //if there was no detail string, clean up:
            ret = ret.Replace("[]", "").Replace("()", "").Replace("   ", " ").Replace("  ", " ");

            return(ret);
        }
Пример #23
0
        public MemoryStream ToStream()
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            MemoryStream ms = new MemoryStream();

            if (this.IsValid())
            {
                try
                {
                    ms = new MemoryStream(this.ImageByteArray, false);
                    ms.Flush();
                }
                catch (Exception ex)
                {
                    AITOOL.Log($"Error: Cannot convert to MemoryStream: {ex.Message}");
                }
            }
            else
            {
                AITOOL.Log($"Error: Cannot convert to MemoryStream because image is not valid.");
            }
            return(ms);
        }
        public List <ClsRelevantObject> FromString(string Objects, bool Clear, bool ExactMatchonly)
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            List <ClsRelevantObject> ret = new List <ClsRelevantObject>();

            this.Init();
            if (!this.Initialized)
            {
                return(ret);
            }


            try
            {
                if (Clear)
                {
                    this.ObjectList.Clear();
                    this.EnabledCount = 0;
                }
                //take anything before the first semicolon:
                if (Objects.Contains(";"))
                {
                    Objects = Objects.GetWord("", ";");
                }

                bool AlreadyHasItems = ObjectList.Count > 0;

                List <string>            lst = Objects.SplitStr(",");
                List <ClsRelevantObject> DefaultObjectList = new List <ClsRelevantObject>();

                if (!this.Camera.EqualsIgnoreCase("default"))
                {
                    DefaultObjectList = this.GetDefaultObjectList(false);
                }

                foreach (var obj in lst)
                {
                    ClsRelevantObject ro = new ClsRelevantObject(obj);

                    ClsRelevantObject rofound = this.Get(ro, false, out int FoundIDX, ExactMatchonly, ret);

                    if (rofound.IsNull())
                    {
                        //Only add items as enabled if we started out from an empty list
                        if (AlreadyHasItems)
                        {
                            ro.Enabled = false;
                        }

                        if (ro.Enabled)
                        {
                            this.EnabledCount++;
                        }

                        //set the order if found in the default list
                        ClsRelevantObject defRo = this.Get(ro, false, out int DefFoundIDX, false, DefaultObjectList);

                        if (DefFoundIDX > -1)
                        {
                            ro.Priority = DefFoundIDX + 1;
                        }
                        else
                        {
                            ro.Priority = ret.Count + 1;
                        }

                        ret.Add(ro);
                    }
                }
            }
            catch (Exception ex)
            {
                AITOOL.Log("Error: " + ex.Msg());
            }

            return(ret);
        }
        public ResultType IsRelevant(List <ClsPrediction> preds, bool IsNew, out bool IgnoreMask, string DbgDetail = "")
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            ResultType ret = ResultType.UnwantedObject;

            IgnoreMask = false;

            this.Init();
            if (!this.Initialized)
            {
                return(ret);
            }


            //if nothing is 'enabled' assume everything should be let through to be on the safe side  (As if they passed an empty list)
            if (this.ObjectList.Count == 0 || this.EnabledCount == 0)  //assume if no list is provided to always return relevant
            {
                return(ResultType.Relevant);
            }

            //if fred is found, the whole prediction will be ignored
            //triggering_objects = person, car, -FRED
            //found objects = person, fred

            if (preds != null && preds.Count > 0)
            {
                //find at least one thing in the triggered objects list in order to send
                string notrelevant = "";
                string relevant    = "";
                string ignored     = "";
                string notenabled  = "";
                string nottime     = "";
                string nothreshold = "";
                bool   ignore      = false;

                foreach (ClsPrediction pred in preds)
                {
                    string label = pred.Label;


                    if (pred.Result == ResultType.Relevant || IsNew)
                    {
                        ClsRelevantObject ro = this.Get(label, AllowEverything: true, out int FoundIDX);

                        if (!ro.IsNull())
                        {
                            if (ro.Enabled)
                            {
                                if (Global.IsTimeBetween(DateTime.Now, ro.ActiveTimeRange))
                                {
                                    //assume if confidence is 0 it has not been set yet (dynamic masking routine, etc)
                                    if (pred.Confidence == 0 || pred.Confidence.Round() >= ro.Threshold_lower && pred.Confidence.Round() <= ro.Threshold_upper)
                                    {
                                        ro.LastHitTime = DateTime.Now;
                                        ro.Hits++;
                                        if (!ro.Trigger)
                                        {
                                            ignore = true;
                                            if (!ignored.Contains(label))
                                            {
                                                ignored += label + ",";
                                            }
                                        }
                                        else
                                        {
                                            ret        = ResultType.Relevant;
                                            IgnoreMask = ro.IgnoreMask;
                                            if (!relevant.Contains(label))
                                            {
                                                relevant += label + ",";
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!nothreshold.Contains(label))
                                        {
                                            nothreshold += label + $" ({pred.Confidence.Round()}%),";
                                        }
                                    }
                                }
                                else
                                {
                                    if (!nottime.Contains(label))
                                    {
                                        nottime += label + ",";
                                    }
                                }
                            }
                            else
                            {
                                if (!notenabled.Contains(label))
                                {
                                    notenabled += label + ",";
                                }
                            }
                        }
                        else
                        {
                            if (!notrelevant.Contains(label))
                            {
                                notrelevant += label + ",";
                            }
                        }
                    }
                    else
                    {
                        if (!notrelevant.Contains(label))
                        {
                            notrelevant += label + ",";
                        }
                    }
                }

                //Add to the main list
                if (this.cam == null)
                {
                    this.cam = AITOOL.GetCamera(this.Camera);
                }

                if (this.defaultcam == null)
                {
                    this.defaultcam = AITOOL.GetCamera("Default", true);
                }

                //always try to add the current prediction to the list (disabled) to give them the option of enabling later
                foreach (ClsPrediction pred in preds)
                {
                    this.TryAdd(pred.Label, false, out int AddedIDX);


                    //add it to the Current camera list (disabled)
                    this.cam.DefaultTriggeringObjects.TryAdd(pred.Label, false, out int AddedIDX2);

                    //add it to the default camera list (disabled)
                    if (!this.defaultcam.IsNull())
                    {
                        this.defaultcam.DefaultTriggeringObjects.TryAdd(pred.Label, false, out int AddedIDX3);
                    }
                }


                if (ignore)
                {
                    ret = ResultType.IgnoredObject;
                }

                if (!DbgDetail.IsEmpty())
                {
                    DbgDetail = $" ({DbgDetail})";
                }

                if (relevant.IsEmpty())
                {
                    relevant = "(NONE)";
                }

                if (notrelevant.IsEmpty())
                {
                    notrelevant = "(NONE)";
                }

                if (ignored.IsEmpty())
                {
                    ignored = "(NONE)";
                }

                if (notenabled.IsEmpty())
                {
                    notenabled = "(NONE)";
                }

                if (nottime.IsEmpty())
                {
                    nottime = "(NONE)";
                }

                if (nothreshold.IsEmpty())
                {
                    nothreshold = "(NONE)";
                }

                string maskignore = "";
                if (IgnoreMask)
                {
                    maskignore = " (Mask will be ignored)";
                }

                if (ret != ResultType.Relevant)
                {
                    AITOOL.Log($"Trace: RelevantObjectManager: Skipping '{this.TypeName}{DbgDetail}' because objects were not defined to trigger, or were set to ignore: Relevant='{relevant.Trim(", ".ToCharArray())}', Irrelevant='{notrelevant.Trim(", ".ToCharArray())}', Caused ignore='{ignored.Trim(", ".ToCharArray())}', Not Enabled={notenabled.Trim(" ,".ToCharArray())}, Not Time={nottime.Trim(" ,".ToCharArray())}, No Threshold Match={nothreshold.Trim(" ,".ToCharArray())}  All Triggering Objects='{this.ToString()}', {preds.Count} predictions(s), Enabled={this.EnabledCount} of {this.ObjectList.Count}");
                }
                else
                {
                    AITOOL.Log($"Trace: RelevantObjectManager: Object is valid for '{this.TypeName}{DbgDetail}' because object(s) '{relevant.Trim(", ".ToCharArray())}' were in trigger objects list '{this.ToString()}',{maskignore} Enabled={this.EnabledCount} of {this.ObjectList.Count}");
                }
            }

            return(ret);
        }
 public void Reset()
 {
     AITOOL.Log($"Using Relevant Objects list from the 'Default' camera for {this.TypeName} RelevantObjectManager.");
     this.ObjectList = this.GetDefaultObjectList(true);
 }
Пример #27
0
        public bool UpdateIsValid()
        {
            bool ret = false;

            this.UrlFixed = false;

            Uri uri = null;

            if (this.Type == URLTypeEnum.DOODS)
            {
                if (!this.url.Contains("://"))
                {
                    this.UrlFixed = true;
                    this.url      = "http://" + this.url;
                }

                if (!(this.url.IndexOf("/detect", StringComparison.OrdinalIgnoreCase) >= 0))
                {
                    this.UrlFixed = true;
                    this.url      = this.url + "/detect";
                }

                if (Global.IsValidURL(this.url) && this.url.IndexOf("/detect", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    uri = new Uri(this.url);
                    if (uri.Port > 0)
                    {
                        ret = true;
                        this.IsLocalHost = Global.IsLocalHost(uri.Host);
                        if (this.IsLocalHost)
                        {
                            if (this.IsLocalHost)
                            {
                                //force it to always be 127.0.0.1 for localhost
                                uri      = new Uri($"{uri.Scheme}://127.0.0.1:{uri.Port}{uri.PathAndQuery}");
                                this.url = uri.ToString();
                            }
                        }
                    }
                }
            }
            else if (this.Type == URLTypeEnum.AWSRekognition)
            {
                this.IsLocalHost = false;
                if (this.url.Equals("amazon", StringComparison.OrdinalIgnoreCase))
                {
                    ret = true;
                }
            }
            else if (this.Type == URLTypeEnum.SightHound_Person)
            {
                if (!this.url.Contains("://"))
                {
                    this.UrlFixed = true;
                    this.url      = "https://" + this.url;
                }

                bool hasdet = this.url.IndexOf("/v1/detections", StringComparison.OrdinalIgnoreCase) >= 0;
                bool hasrec = this.url.IndexOf("/v1/recognition", StringComparison.OrdinalIgnoreCase) >= 0;

                if (!hasdet)
                {
                    this.UrlFixed = true;
                    this.url      = this.url + "/v1/recognition?objectType=vehicle,licenseplate";
                }

                if (Global.IsValidURL(this.url) && hasdet && !hasrec)
                {
                    ret = true;
                }
            }
            else if (this.Type == URLTypeEnum.SightHound_Vehicle)
            {
                if (!this.url.Contains("://"))
                {
                    this.UrlFixed = true;
                    this.url      = "https://" + this.url;
                }

                bool hasdet = this.url.IndexOf("/v1/detections", StringComparison.OrdinalIgnoreCase) >= 0;
                bool hasrec = this.url.IndexOf("/v1/recognition", StringComparison.OrdinalIgnoreCase) >= 0;

                if (!hasrec)
                {
                    this.UrlFixed = true;
                    this.url      = this.url + "/v1/detections?type=face,person&faceOption=gender,landmark,age,pose,emotion";
                }

                if (Global.IsValidURL(this.url) && hasrec && !hasdet)
                {
                    ret = true;
                }
            }
            else // assume deepstack
            {
                if (!this.url.Contains("://"))
                {
                    this.UrlFixed = true;
                    this.url      = "http://" + this.url.Trim();
                }


                bool hasdet = this.url.IndexOf("/v1/vision/detection", StringComparison.OrdinalIgnoreCase) >= 0;
                bool hascus = this.url.IndexOf("/v1/vision/custom", StringComparison.OrdinalIgnoreCase) >= 0;

                if (!hasdet && !hascus)
                {
                    this.UrlFixed = true;
                    this.url      = this.url.Trim() + ":80/v1/vision/detection";
                }
                ///v1/vision/custom/catsanddogs
                if (Global.IsValidURL(this.url) && (hasdet || hascus))
                {
                    uri = new Uri(this.url);
                    if (uri.Port > 0)
                    {
                        ret = true;
                        this.IsLocalHost = Global.IsLocalHost(uri.Host);
                        if (this.IsLocalHost)
                        {
                            //force it to always be 127.0.0.1 for localhost
                            uri      = new Uri($"{uri.Scheme}://127.0.0.1:{uri.Port}{uri.PathAndQuery}");
                            this.url = uri.ToString();
                        }
                    }
                }
            }

            if (uri != null)
            {
                this.CurSrv = uri.Host + ":" + uri.Port;
            }

            if (!ret)
            {
                AITOOL.Log($"Error: '{this.Type.ToString()}' URL is not valid: '{this.url}'");
            }

            this.IsValid = ret;

            if (!this.isValid)
            {
                this.Enabled.WriteFullFence(false);
            }

            return(ret);
        }
Пример #28
0
        private async void btTest_ClickAsync(object sender, EventArgs e)
        {
            this.btTest.Enabled    = false;
            this.btnSave.Enabled   = false;
            this.btnCancel.Enabled = false;

            try
            {
                AppSettings.Settings.mqtt_serverandport = this.tb_ServerPort.Text.Trim();
                AppSettings.Settings.mqtt_password      = this.tb_Password.Text.Trim();
                AppSettings.Settings.mqtt_username      = this.tb_Username.Text.Trim();
                AppSettings.Settings.mqtt_UseTLS        = this.cb_UseTLS.Checked;

                using (Global_GUI.CursorWait cw = new Global_GUI.CursorWait())
                {
                    Log("------ TESTING MQTT --------");


                    string topic   = AITOOL.ReplaceParams(this.cam, null, null, this.tb_Topic.Text.Trim());
                    string payload = AITOOL.ReplaceParams(this.cam, null, null, this.tb_Payload.Text.Trim());

                    List <string> topics   = Global.Split(topic, ";|");
                    List <string> payloads = Global.Split(payload, ";|");

                    MQTTClient mq = new MQTTClient();
                    MqttClientPublishResult pr     = null;
                    ClsImageQueueItem       CurImg = null;


                    for (int i = 0; i < topics.Count; i++)
                    {
                        if (this.cam.Action_mqtt_send_image)
                        {
                            if (topics[i].IndexOf("/image", StringComparison.OrdinalIgnoreCase) >= 0)
                            {
                                if (!string.IsNullOrEmpty(this.cam.last_image_file_with_detections) && File.Exists(this.cam.last_image_file_with_detections))
                                {
                                    CurImg = new ClsImageQueueItem(this.cam.last_image_file_with_detections, 0);
                                }
                                else if (!string.IsNullOrEmpty(this.cam.last_image_file) && File.Exists(this.cam.last_image_file))
                                {
                                    CurImg = new ClsImageQueueItem(this.cam.last_image_file, 0);
                                }
                                else
                                {
                                    CurImg = null;
                                }
                            }
                            else
                            {
                                CurImg = null;
                            }
                        }

                        pr = await mq.PublishAsync(topics[i], payloads[i], this.cam.Action_mqtt_retain_message, CurImg);
                    }

                    Log("------ DONE TESTING MQTT --------");

                    if (pr != null && (pr.ReasonCode == MqttClientPublishReasonCode.Success))
                    {
                        MessageBox.Show("Success! See Log for details.");
                    }
                    else if (pr != null)
                    {
                        MessageBox.Show($"Failed. See log for details. Reason={pr.ReasonCode}", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show($"Failed. See log for details.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch
            {
            }
            finally
            {
                this.btTest.Enabled    = true;
                this.btnSave.Enabled   = true;
                this.btnCancel.Enabled = true;
            }
        }
Пример #29
0
 private void label3_Click(object sender, EventArgs e)
 {
     MessageBox.Show(AITOOL.ReplaceParams(this.cam, null, label3.Text));
 }
Пример #30
0
        public void AnalyzePrediction()
        {
            using var Trace = new Trace();  //This c# 8.0 using feature will auto dispose when the function is done.

            MaskResultInfo result = new MaskResultInfo();

            try
            {
                if (this._cam.enabled)
                {
                    if (!string.IsNullOrWhiteSpace(this._cam.triggering_objects_as_string))
                    {
                        if (this._cam.IsRelevant(this.Label))
                        {
                            // -> OBJECT IS RELEVANT

                            //if confidence limits are satisfied
                            bool OverrideThreshold = this._cururl != null && (this._cururl.Threshold_Lower > 0 || (this._cururl.Threshold_Upper > 0 && this._cururl.Threshold_Upper < 100));

                            if ((!OverrideThreshold && this.Confidence >= this._cam.threshold_lower && this.Confidence <= this._cam.threshold_upper) ||
                                (OverrideThreshold && this.Confidence >= this._cururl.Threshold_Lower && this.Confidence <= this._cururl.Threshold_Upper))
                            {
                                // -> OBJECT IS WITHIN CONFIDENCE LIMITS

                                //only if the object is outside of the masked area
                                result                      = AITOOL.Outsidemask(this._cam, this.XMin, this.XMax, this.YMin, this.YMax, this._curimg.Width, this._curimg.Height);
                                this.ImgMaskResult          = result.Result;
                                this.ImgMaskType            = result.MaskType;
                                this.ImagePointsOutsideMask = result.ImagePointsOutsideMask;

                                if (!result.IsMasked)
                                {
                                    this.Result = ResultType.Relevant;
                                }
                                else if (result.MaskType == MaskType.None) //if the object is in a masked area
                                {
                                    this.Result = ResultType.NoMask;
                                }
                                else if (result.MaskType == MaskType.Image) //if the object is in a masked area
                                {
                                    this.Result = ResultType.ImageMasked;
                                }

                                //check the mask manager if the image mask didnt flag anything
                                if (!result.IsMasked)
                                {
                                    //check the dynamic or static masks
                                    if (this._cam.maskManager.MaskingEnabled)
                                    {
                                        ObjectPosition currentObject = new ObjectPosition(this.XMin, this.XMax, this.YMin, this.YMax, this.Label,
                                                                                          this._curimg.Width, this._curimg.Height, this._cam.Name, this._curimg.image_path);
                                        //creates history and masked lists for objects returned
                                        result                     = this._cam.maskManager.CreateDynamicMask(currentObject);
                                        this.DynMaskResult         = result.Result;
                                        this.DynMaskType           = result.MaskType;
                                        this.DynamicThresholdCount = result.DynamicThresholdCount;
                                        this.PercentMatch          = result.PercentMatch;

                                        //there is a dynamic or static mask
                                        if (result.MaskType == MaskType.Dynamic)
                                        {
                                            this.Result = ResultType.DynamicMasked;
                                        }
                                        else if (result.MaskType == MaskType.Static)
                                        {
                                            this.Result = ResultType.StaticMasked;
                                        }
                                    }
                                }

                                if (result.Result == MaskResult.Error || result.Result == MaskResult.Unknown)
                                {
                                    this.Result = ResultType.Error;
                                    Log($"Error: Masking error? '{this._cam.Name}' ('{this.Label}') - DynMaskResult={this.DynMaskResult}, ImgMaskResult={this.ImgMaskResult}", "", this._cam.Name, this._curimg.image_path);
                                }
                            }
                            else //if confidence limits are not satisfied
                            {
                                this.Result = ResultType.NoConfidence;
                            }
                        }
                        else
                        {
                            this.Result = ResultType.UnwantedObject;
                        }
                    }
                    else
                    {
                        Log($"Error: Camera does not have any objects enabled '{this._cam.Name}' ('{this.Label}')", "", this._cam.Name, this._curimg.image_path);
                        this.Result = ResultType.Error;
                    }
                }
                else
                {
                    Log($"Debug: Camera not enabled '{this._cam.Name}' ('{this.Label}')", "", this._cam.Name, this._curimg.image_path);
                    this.Result = ResultType.CameraNotEnabled;
                }
            }
            catch (Exception ex)
            {
                Log($"Error: Label '{this.Label}', Camera '{this._cam.Name}': {Global.ExMsg(ex)}", "", this._cam.Name, this._curimg.image_path);
                this.Result = ResultType.Error;
            }
        }