From f073e372543fe1192de7e67053578585b7fbaa4c Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Mon, 15 Feb 2021 20:11:14 +0100 Subject: [PATCH 01/15] spostato save in libreria --- ThermalImageStreamerDemo/MainForm.Designer.cs | 52 ++-- ThermalImageStreamerDemo/MainForm.cs | 235 +++++++++--------- ThermoCamUtils/ImageData.cs | 147 ++++++++++- ThermoCamUtils/Objects.cs | 22 ++ ThermoCamUtils/ThermoCamConf.cs | 14 +- ThermoCamUtils/ThermoCamUtils.csproj | 3 + ThermoCamUtils/packages.config | 1 + 7 files changed, 325 insertions(+), 149 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.Designer.cs b/ThermalImageStreamerDemo/MainForm.Designer.cs index d1a3cd50..0a208c0a 100644 --- a/ThermalImageStreamerDemo/MainForm.Designer.cs +++ b/ThermalImageStreamerDemo/MainForm.Designer.cs @@ -44,6 +44,8 @@ this.chkSaveAll = new System.Windows.Forms.CheckBox(); this.btnLoad = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); + this.lblMaxTemp = new System.Windows.Forms.Label(); + this.lblMinTemp = new System.Windows.Forms.Label(); this.lblTempRGB = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.txtMaxScale = new System.Windows.Forms.TextBox(); @@ -75,8 +77,6 @@ this.lblImgB = new System.Windows.Forms.Label(); this.lblImgC = new System.Windows.Forms.Label(); this.chkShowOrig = new System.Windows.Forms.CheckBox(); - this.lblMinTemp = new System.Windows.Forms.Label(); - this.lblMaxTemp = new System.Windows.Forms.Label(); this.menuStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pBoxA)).BeginInit(); @@ -243,6 +243,29 @@ this.groupBox3.TabStop = false; this.groupBox3.Text = "Temperature"; // + // lblMaxTemp + // + this.lblMaxTemp.AutoSize = true; + this.lblMaxTemp.ForeColor = System.Drawing.SystemColors.ControlLightLight; + this.lblMaxTemp.Location = new System.Drawing.Point(89, 67); + this.lblMaxTemp.MinimumSize = new System.Drawing.Size(80, 0); + this.lblMaxTemp.Name = "lblMaxTemp"; + this.lblMaxTemp.Size = new System.Drawing.Size(80, 13); + this.lblMaxTemp.TabIndex = 17; + this.lblMaxTemp.Text = "? °C"; + this.lblMaxTemp.TextAlign = System.Drawing.ContentAlignment.TopRight; + // + // lblMinTemp + // + this.lblMinTemp.AutoSize = true; + this.lblMinTemp.ForeColor = System.Drawing.SystemColors.ControlText; + this.lblMinTemp.Location = new System.Drawing.Point(7, 67); + this.lblMinTemp.MinimumSize = new System.Drawing.Size(80, 0); + this.lblMinTemp.Name = "lblMinTemp"; + this.lblMinTemp.Size = new System.Drawing.Size(80, 13); + this.lblMinTemp.TabIndex = 16; + this.lblMinTemp.Text = "? °C"; + // // lblTempRGB // this.lblTempRGB.AutoSize = true; @@ -272,6 +295,7 @@ this.txtMaxScale.TabIndex = 12; this.txtMaxScale.Text = "60"; this.txtMaxScale.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + this.txtMaxScale.TextChanged += new System.EventHandler(this.txtMaxScale_TextChanged); // // label7 // @@ -290,6 +314,7 @@ this.txtMinScale.TabIndex = 10; this.txtMinScale.Text = "0"; this.txtMinScale.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; + this.txtMinScale.TextChanged += new System.EventHandler(this.txtMinScale_TextChanged); // // chkReadTemp // @@ -566,29 +591,6 @@ this.chkShowOrig.Text = "Show Original"; this.chkShowOrig.UseVisualStyleBackColor = true; // - // lblMinTemp - // - this.lblMinTemp.AutoSize = true; - this.lblMinTemp.ForeColor = System.Drawing.SystemColors.ControlText; - this.lblMinTemp.Location = new System.Drawing.Point(7, 67); - this.lblMinTemp.MinimumSize = new System.Drawing.Size(80, 0); - this.lblMinTemp.Name = "lblMinTemp"; - this.lblMinTemp.Size = new System.Drawing.Size(80, 13); - this.lblMinTemp.TabIndex = 16; - this.lblMinTemp.Text = "? °C"; - // - // lblMaxTemp - // - this.lblMaxTemp.AutoSize = true; - this.lblMaxTemp.ForeColor = System.Drawing.SystemColors.ControlLightLight; - this.lblMaxTemp.Location = new System.Drawing.Point(89, 67); - this.lblMaxTemp.MinimumSize = new System.Drawing.Size(80, 0); - this.lblMaxTemp.Name = "lblMaxTemp"; - this.lblMaxTemp.Size = new System.Drawing.Size(80, 13); - this.lblMaxTemp.TabIndex = 17; - this.lblMaxTemp.Text = "? °C"; - this.lblMaxTemp.TextAlign = System.Drawing.ContentAlignment.TopRight; - // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 5b5d0ba3..a2952a54 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -52,25 +52,18 @@ namespace ThermalImageStreamerDemo /// protected ImageData ImgData = new ImageData(); -#if false - protected double lastCalcTemp = 0; - - protected Point ImgData.lastPoint = new Point(); - - protected double lastReadTemp = 0; -#endif - protected double msLastCam = 0; - protected double msLastCol = 0; - +#if false protected double msLastMsr = 0; protected double msLastPts = 0; + protected double msLastCol = 0; protected double msLastTra = 0; protected Point refTempPoint = new Point(); +#endif protected Stopwatch sw = new Stopwatch(); @@ -92,6 +85,8 @@ namespace ThermalImageStreamerDemo _timerRefreshUi.Tick += _timerRefreshUi_Tick; // cerco se ho un set di parametri già impostati... tryReloadConf(); + // sistemo le conf temp + setRangeTemp(); // calcolo i currConf.destPoints updateDestPt(); } @@ -176,51 +171,30 @@ namespace ThermalImageStreamerDemo } } - /// - /// Ultimo range di temperature osservato - /// - protected Range lastTempRange - { - get - { - return _lastTempRange; - } - set - { - _lastTempRange = value; - lblMinTemp.Text = $"{value.Minimum:N2}"; - lblMaxTemp.Text = $"{value.Maximum:N2}"; - } - } - - protected double maxScale + protected double maxRangeTemp { get { double answ = 1000; double.TryParse(txtMaxScale.Text, out answ); - currConf.TargetRange.Max = answ; return answ; } set { - currConf.TargetRange.Max = value; txtMaxScale.Text = $"{value:N0}"; } } - protected double minScale + protected double minRangeTemp { get { double answ = 0; double.TryParse(txtMinScale.Text, out answ); - currConf.TargetRange.Min = answ; return answ; } set { - currConf.TargetRange.Min = value; txtMinScale.Text = $"{value:N0}"; } } @@ -308,18 +282,26 @@ namespace ThermalImageStreamerDemo { try { - ImgData.Thermal = new ThermalImageFile(filePath); - ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; - ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; + using (var flirImg = new ThermalImageFile(filePath)) + { + //ImgData.Thermal = new ThermalImageFile(filePath); + ImgData.Thermal = (ThermalImage)flirImg; + ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; + ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; + } + // carico DIRETTAMENTE da file... - ImgData.Origin = (Bitmap)Image.FromFile(filePath); - ImgData.Decorated = (Bitmap)Image.FromFile(filePath); + using (Image loadedImg = Image.FromFile(filePath)) + { + ImgData.Origin = (Bitmap)loadedImg; + ImgData.Decorated = (Bitmap)loadedImg; + } // aggiorno visualizzazione processImage(); refreshDisplay(); } - catch + catch (Exception exc) { } } } @@ -327,7 +309,7 @@ namespace ThermalImageStreamerDemo private void btnReset_Click(object sender, EventArgs e) { pointSetup = true; - currConf.origPoints = new SetPoints(); + currConf.OrigPoints = new SetPoints(); } private void btnSave_Click(object sender, EventArgs e) @@ -458,6 +440,7 @@ namespace ThermalImageStreamerDemo IRCam.ThermoCamera.Dispose(); } +#if false private void drawCrossAtPoints() { if (ImgData.Thermal != null) @@ -505,25 +488,6 @@ namespace ThermalImageStreamerDemo } } } - -#if false - private void getTemperatures() - { - if (ImgData.Thermal != null) - { - lastReadTemp = 0; - if (readTemp) - { - // recupero temp da FLIR - lastReadTemp = ImgData.Thermal.GetValueAt(ImgData.lastPoint).Value; - - // calcolo temp da RGB considerato limiti minMAX... - //int rgbVal = ImgData.lastImageOrig.Image.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y).R; - int rgbVal = getRSmooth(ImgData.lastPoint); - lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); - } - } - } #endif private void Image_Changed(object sender, Flir.Atlas.Image.ImageChangedEventArgs e) @@ -606,15 +570,15 @@ namespace ThermalImageStreamerDemo if (pointSetup) { // max 4 punti... se sono già FULL --> imposto singolo valore nuovo - if (currConf.origPoints.curr >= 4) + if (currConf.OrigPoints.curr >= 4) { if (currPoint >= 0) { - currConf.origPoints.Coords[currPoint] = ImgData.lastPoint; + currConf.OrigPoints.Coords[currPoint] = ImgData.lastPoint; } else { - currConf.origPoints = new SetPoints(); + currConf.OrigPoints = new SetPoints(); } } else @@ -622,8 +586,8 @@ namespace ThermalImageStreamerDemo // salvo coordinate in base al num corrente... try { - currConf.origPoints.Coords.Add(ImgData.lastPoint); - currConf.origPoints.curr++; + currConf.OrigPoints.Coords.Add(ImgData.lastPoint); + currConf.OrigPoints.curr++; } catch { } @@ -637,7 +601,8 @@ namespace ThermalImageStreamerDemo } else if (readTemp) { - refTempPoint = ImgData.lastPoint; + // x ora fisso 1 solo valore... + ImgData.saveMeasurePoint(false); // aggiorno visualizzazione processImage(); refreshDisplay(); @@ -665,7 +630,7 @@ namespace ThermalImageStreamerDemo private void refreshDisplay() { - drawCrossAtPoints(); + ImgData.drawCrossAtPoints(); displayImages(); updateDisplay(); updateTempDisplay(); @@ -690,6 +655,7 @@ namespace ThermalImageStreamerDemo return answ; } +#if false private void saveImgFile() { try @@ -704,10 +670,59 @@ namespace ThermalImageStreamerDemo // salvo! ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; ImgData.Thermal.SaveSnapshot(filePath); + var rawData = JsonConvert.SerializeObject(ImgData.Thermal, Formatting.Indented); } catch { } } +#endif + + /// + /// Sistema le temp range min/Max + /// + private void setRangeTemp() + { + currConf.TargetRange.Min = minRangeTemp; + currConf.TargetRange.Max = maxRangeTemp; + } + +#if false + /// + /// Ultimo range di temperature osservato + /// + protected Range lastTempRange + { + get + { + return _lastTempRange; + } + set + { + _lastTempRange = value; + lblMinTemp.Text = $"{value.Minimum:N2}"; + lblMaxTemp.Text = $"{value.Maximum:N2}"; + } + } +#endif +#if false + private void getTemperatures() + { + if (ImgData.Thermal != null) + { + lastReadTemp = 0; + if (readTemp) + { + // recupero temp da FLIR + lastReadTemp = ImgData.Thermal.GetValueAt(ImgData.lastPoint).Value; + + // calcolo temp da RGB considerato limiti minMAX... + //int rgbVal = ImgData.lastImageOrig.Image.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y).R; + int rgbVal = getRSmooth(ImgData.lastPoint); + lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); + } + } + } +#endif /// /// recupera immagine effettuando eventuale salvataggio @@ -740,7 +755,10 @@ namespace ThermalImageStreamerDemo ImgData.Decorated = ImgData.Thermal.Image; if (doSave) { +#if false saveImgFile(); +#endif + ImgData.saveImgFiles(); } } catch (Exception exception) @@ -824,14 +842,24 @@ namespace ThermalImageStreamerDemo updateDestPt(); } + private void txtMaxScale_TextChanged(object sender, EventArgs e) + { + setRangeTemp(); + } + + private void txtMinScale_TextChanged(object sender, EventArgs e) + { + setRangeTemp(); + } + private void updateDestPt() { - currConf.destPoints.Coords = new List(); + currConf.DestPoints.Coords = new List(); // ciclo i punti A-B-C-D... - currConf.destPoints.Coords.Add(new Point() { X = 0, Y = 0 }); - currConf.destPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); - currConf.destPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); - currConf.destPoints.Coords.Add(new Point() { X = 0, Y = dimY }); + currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = 0 }); + currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); + currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); + currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = dimY }); // salvo conf saveConf(); } @@ -843,28 +871,36 @@ namespace ThermalImageStreamerDemo lblOrigC.Text = "C"; lblOrigD.Text = "D"; // popolo - if (currConf.origPoints.Coords.Count > 0) + if (currConf.OrigPoints.Coords.Count > 0) { - lblOrigA.Text = $"A: ({currConf.origPoints.Coords[0].X},{currConf.origPoints.Coords[0].Y})"; + lblOrigA.Text = $"A: ({currConf.OrigPoints.Coords[0].X},{currConf.OrigPoints.Coords[0].Y})"; } - if (currConf.origPoints.Coords.Count > 1) + if (currConf.OrigPoints.Coords.Count > 1) { - lblOrigB.Text = $"B: ({currConf.origPoints.Coords[1].X},{currConf.origPoints.Coords[1].Y})"; + lblOrigB.Text = $"B: ({currConf.OrigPoints.Coords[1].X},{currConf.OrigPoints.Coords[1].Y})"; } - if (currConf.origPoints.Coords.Count > 2) + if (currConf.OrigPoints.Coords.Count > 2) { - lblOrigC.Text = $"C: ({currConf.origPoints.Coords[2].X},{currConf.origPoints.Coords[2].Y})"; + lblOrigC.Text = $"C: ({currConf.OrigPoints.Coords[2].X},{currConf.OrigPoints.Coords[2].Y})"; } - if (currConf.origPoints.Coords.Count > 3) + if (currConf.OrigPoints.Coords.Count > 3) { - lblOrigD.Text = $"D: ({currConf.origPoints.Coords[3].X},{currConf.origPoints.Coords[3].Y})"; + lblOrigD.Text = $"D: ({currConf.OrigPoints.Coords[3].X},{currConf.OrigPoints.Coords[3].Y})"; ImgData.calculateTarget(chkParallel.Checked, chkRevProc.Checked); } } private void updateStatDisplay() { - lblStats.Text = $"Camera: {msLastCam}ms | Persp {msLastTra}ms | Color {msLastCol}ms | Points {msLastPts}ms | Measures {msLastMsr}ms"; + if (ImgData.ExTime.Stats.Count > 0) + { + try + { + lblStats.Text = $"Camera: {msLastCam}ms | Persp {ImgData.ExTime.Stats["ImageTransf"]}ms | Color {ImgData.ExTime.Stats["ImageColor"]}ms | Points {ImgData.ExTime.Stats["AddPoints"]}ms | Measures {ImgData.ExTime.Stats["GetTemperatures"]}ms"; + } + catch + { } + } } private void updateTempDisplay() @@ -896,47 +932,16 @@ namespace ThermalImageStreamerDemo { lblTempRGB.ForeColor = Color.Red; } + + // mostro minimo / massimo + lblMinTemp.Text = $"{ImgData.Thermal.Scale.Range.Minimum:N2}"; + lblMaxTemp.Text = $"{ImgData.Thermal.Scale.Range.Maximum:N2}"; } } } #endregion Private Methods -#if false - /// - /// Calcola valore R ponderato dato un punto + intorno - /// - /// - /// - protected int getRSmooth(Point reqPoint) - { - int answ = 0; - if (ImgData.Origin != null) - { - // solo se il punto è entro limiti immagine --> 1 pixel entro bordo - if (reqPoint.X > 0 && reqPoint.X < ImgData.Origin.Width) - { - if (reqPoint.Y > 0 && reqPoint.Y < ImgData.Origin.Height) - { - int rgbValMain = ImgData.Origin.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y).R; - - int rgbValN = ImgData.Origin.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y - 1).R; - int rgbValNO = ImgData.Origin.GetPixel(ImgData.lastPoint.X - 1, ImgData.lastPoint.Y - 1).R; - int rgbValO = ImgData.Origin.GetPixel(ImgData.lastPoint.X - 1, ImgData.lastPoint.Y).R; - int rgbValSO = ImgData.Origin.GetPixel(ImgData.lastPoint.X - 1, ImgData.lastPoint.Y + 1).R; - int rgbValS = ImgData.Origin.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y + 1).R; - int rgbValSE = ImgData.Origin.GetPixel(ImgData.lastPoint.X + 1, ImgData.lastPoint.Y + 1).R; - int rgbValE = ImgData.Origin.GetPixel(ImgData.lastPoint.X + 1, ImgData.lastPoint.Y).R; - int rgbValNE = ImgData.Origin.GetPixel(ImgData.lastPoint.X + 1, ImgData.lastPoint.Y - 1).R; - // calcolo valore ponderato - answ = (int)Math.Round((double)(1 * rgbValMain + 1 * (rgbValN + rgbValO + rgbValS + rgbValE) + rgbValNO + rgbValSO + rgbValSE + rgbValNE) / 10, 0); - } - } - } - return answ; - } -#endif - #region Public Methods public void discoveryCamera() diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index 594bbf70..cfcaeffc 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -1,9 +1,13 @@ using Flir.Atlas.Image; +using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; +using System.Drawing.Drawing2D; +using System.IO; using System.Linq; +using System.Reflection; using System.Text; using System.Threading.Tasks; @@ -16,6 +20,16 @@ namespace ThermoCamUtils { #region Protected Fields + protected const string colorPath = "images\\Color"; + + protected const string confFormat = "json"; + + protected const string currImgFile = "_last"; + + protected const string imgFormat = "jpg"; + + protected const string thermPath = "images\\Therm"; + /// /// Ultimo range di temperature osservato /// @@ -30,6 +44,8 @@ namespace ThermoCamUtils #region Public Fields + public static readonly string BASE_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + /// /// Statistiche esecuzione task /// @@ -83,6 +99,35 @@ namespace ThermoCamUtils #endregion Public Properties + #region Private Methods + + private void drawPoint(Color currColor, Point currPoint) + { + // disegno! + using (Graphics gr = Graphics.FromImage(Decorated)) + { + gr.SmoothingMode = SmoothingMode.AntiAlias; + + Point[] crsPoints = new Point[4]; + for (int i = 0; i < 4; i++) + { + crsPoints[i] = currPoint; + } + crsPoints[0].X = crsPoints[0].X - 4; + crsPoints[1].X = crsPoints[1].X + 4; + crsPoints[2].Y = crsPoints[2].Y - 4; + crsPoints[3].Y = crsPoints[3].Y + 4; + + using (Pen thick_pen = new Pen(currColor, 1)) + { + gr.DrawLine(thick_pen, crsPoints[0], crsPoints[1]); + gr.DrawLine(thick_pen, crsPoints[2], crsPoints[3]); + } + } + } + + #endregion Private Methods + #region Protected Methods /// @@ -137,7 +182,7 @@ namespace ThermoCamUtils lastTempRange = new Range(Thermal.Scale.Range.Minimum, Thermal.Scale.Range.Maximum); sw.Restart(); - var pTransf = new PerspectiveTransform(currConf.origPoints.Coords, currConf.destPoints.Coords); + var pTransf = new PerspectiveTransform(currConf.OrigPoints.Coords, currConf.DestPoints.Coords); var rTrasf = new ReColorize(lastTempRange.Minimum, lastTempRange.Maximum, currConf.TargetRange.Min, currConf.TargetRange.Max); var transfImg = pTransf.convertImage(Origin, currConf.TargetSize.X, currConf.TargetSize.Y); GrayTransf = transfImg; @@ -167,6 +212,33 @@ namespace ThermoCamUtils } } + public void drawCrossAtPoints() + { + if (Thermal != null) + { + sw.Restart(); + // se ho dei punti x trasformazione --> disegno + if (currConf.OrigPoints.curr > 0) + { + foreach (var item in currConf.OrigPoints.Coords) + { + drawPoint(Color.Green, item); + } + } + // se ho punto acquisizione temp --> disegno! + if (currConf.MeasPoints.Count > 0) + { + foreach (var item in currConf.MeasPoints) + { + // disegno! + drawPoint(Color.Blue, item.Coords); + } + } + sw.Stop(); + ExTime.recordData("AddPoints", sw.ElapsedMilliseconds); + } + } + /// /// Recupera temperature coi 2 metodi da FLIR e da B/N /// @@ -178,13 +250,19 @@ namespace ThermoCamUtils lastReadTemp = 0; if (readTemp) { - // recupero temp da FLIR - lastReadTemp = Thermal.GetValueAt(lastPoint).Value; + sw.Restart(); + foreach (var item in currConf.MeasPoints) + { + // recupero temp da FLIR + lastReadTemp = Thermal.GetValueAt(item.Coords).Value; - // calcolo temp da RGB considerato limiti minMAX... - //int rgbVal = lastImageOrig.Image.GetPixel(lastPoint.X, lastPoint.Y).R; - int rgbVal = getRSmooth(lastPoint); - lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); + // calcolo temp da RGB considerato limiti minMAX... + //int rgbVal = lastImageOrig.Image.GetPixel(lastPoint.X, lastPoint.Y).R; + int rgbVal = getRSmooth(item.Coords); + lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); + } + sw.Stop(); + ExTime.recordData("GetTemperatures", sw.ElapsedMilliseconds); } } } @@ -212,6 +290,61 @@ namespace ThermoCamUtils } } + public void saveImgFiles() + { + try + { + // fix percorsi + string thermoDirPath = $"{BASE_PATH}\\{thermPath}"; + string thermoColPath = $"{BASE_PATH}\\{colorPath}"; + if (!Directory.Exists(thermoDirPath)) + { + Directory.CreateDirectory(thermoDirPath); + } + if (!Directory.Exists(thermoColPath)) + { + Directory.CreateDirectory(thermoColPath); + } + + // nomi file + string themoFilePath = $"{thermoDirPath}\\{currImgFile}.{imgFormat}"; + string themoDataPath = $"{thermoDirPath}\\{currImgFile}.{confFormat}"; + string colorFilePath = $"{thermoColPath}\\{currImgFile}.{imgFormat}"; + + // salvo thermo! + Thermal.Scale.IsAutoAdjustEnabled = true; + Thermal.SaveSnapshot(themoFilePath); + // salvo conf thermo + string rawData = JsonConvert.SerializeObject(Thermal, Formatting.Indented); + File.WriteAllText(themoDataPath, rawData); + + // salvo colorata + ColorTransf.Save(colorFilePath); + } + catch + { } + } + + /// + /// Salvo il punto di misura selezionato + /// + /// + public void saveMeasurePoint(bool addOnEnd) + { + // se NO devo accodare resetto... + if (!addOnEnd) + { + currConf.MeasPoints = new List(); + } + MeasurePoint newPoint = new MeasurePoint() + { + Id = currConf.MeasPoints.Count, + Coords = lastPoint, + Temperature = 0 + }; + currConf.MeasPoints.Add(newPoint); + } + #endregion Public Methods } } \ No newline at end of file diff --git a/ThermoCamUtils/Objects.cs b/ThermoCamUtils/Objects.cs index 8fb76872..d403f634 100644 --- a/ThermoCamUtils/Objects.cs +++ b/ThermoCamUtils/Objects.cs @@ -7,6 +7,28 @@ using System.Threading.Tasks; namespace ThermoCamUtils { + public class MeasurePoint + { + #region Public Properties + + /// + /// Punto di riferimento + /// + public Point Coords { get; set; } = new Point(); + + /// + /// Id del punto + /// + public int Id { get; set; } = 0; + + /// + /// Temperatura rilevata al punto + /// + public double Temperature { get; set; } = 0; + + #endregion Public Properties + } + public class SetPoints { #region Public Properties diff --git a/ThermoCamUtils/ThermoCamConf.cs b/ThermoCamUtils/ThermoCamConf.cs index 4b62017f..b73b6d3d 100644 --- a/ThermoCamUtils/ThermoCamConf.cs +++ b/ThermoCamUtils/ThermoCamConf.cs @@ -2,6 +2,7 @@ using Flir.Atlas.Live.Discovery; using System; using System.Collections.Generic; +using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -44,6 +45,15 @@ namespace ThermoCamUtils public class ThermoCamConf { + #region Public Fields + + /// + /// Elenco di punti x misurazione temperatura + /// + public List MeasPoints = new List(); + + #endregion Public Fields + #region Public Properties /// @@ -54,12 +64,12 @@ namespace ThermoCamUtils /// /// Punti su IMG destinazione /// - public SetPoints destPoints { get; set; } = new SetPoints(); + public SetPoints DestPoints { get; set; } = new SetPoints(); /// /// Punti su IMG origine /// - public SetPoints origPoints { get; set; } = new SetPoints(); + public SetPoints OrigPoints { get; set; } = new SetPoints(); /// /// Range scala colori desiderata diff --git a/ThermoCamUtils/ThermoCamUtils.csproj b/ThermoCamUtils/ThermoCamUtils.csproj index 13371e27..5639ab6b 100644 --- a/ThermoCamUtils/ThermoCamUtils.csproj +++ b/ThermoCamUtils/ThermoCamUtils.csproj @@ -46,6 +46,9 @@ ..\..\..\..\..\..\Program Files (x86)\FLIR Systems\FLIR Atlas SDK 4\bin\x64\Flir.Atlas.Live.dll + + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + ..\packages\OpenCvSharp4.4.5.1.20210208\lib\net461\OpenCvSharp.dll diff --git a/ThermoCamUtils/packages.config b/ThermoCamUtils/packages.config index 125cbfb0..6a88e754 100644 --- a/ThermoCamUtils/packages.config +++ b/ThermoCamUtils/packages.config @@ -1,5 +1,6 @@  + From 134f891f034911ae9ad2dcd3b5d755e5fa50c282 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Mon, 15 Feb 2021 20:17:52 +0100 Subject: [PATCH 02/15] copia img unique +code cleanup (2 test...) --- ThermalImageStreamerDemo/MainForm.cs | 140 --------------------------- ThermoCamUtils/ImageData.cs | 11 ++- 2 files changed, 10 insertions(+), 141 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index a2952a54..3680766f 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -54,17 +54,6 @@ namespace ThermalImageStreamerDemo protected double msLastCam = 0; -#if false - protected double msLastMsr = 0; - - protected double msLastPts = 0; - - protected double msLastCol = 0; - protected double msLastTra = 0; - - protected Point refTempPoint = new Point(); -#endif - protected Stopwatch sw = new Stopwatch(); #endregion Protected Fields @@ -440,56 +429,6 @@ namespace ThermalImageStreamerDemo IRCam.ThermoCamera.Dispose(); } -#if false - private void drawCrossAtPoints() - { - if (ImgData.Thermal != null) - { - sw.Restart(); - // se ho dei punti x trasformazione --> disegno - if (currConf.origPoints.curr > 0) - { - foreach (var item in currConf.origPoints.Coords) - { - drawPoint(Color.Green, item); - } - } - // se ho punto acquisizione temp --> disegno! - if (refTempPoint != null) - { - drawPoint(Color.Blue, refTempPoint); - } - sw.Stop(); - msLastPts = sw.ElapsedMilliseconds; - } - } - - private void drawPoint(Color currColor, Point currPoint) - { - // disegno! - using (Graphics gr = Graphics.FromImage(ImgData.Decorated)) - { - gr.SmoothingMode = SmoothingMode.AntiAlias; - - Point[] crsPoints = new Point[4]; - for (int i = 0; i < 4; i++) - { - crsPoints[i] = currPoint; - } - crsPoints[0].X = crsPoints[0].X - 4; - crsPoints[1].X = crsPoints[1].X + 4; - crsPoints[2].Y = crsPoints[2].Y - 4; - crsPoints[3].Y = crsPoints[3].Y + 4; - - using (Pen thick_pen = new Pen(currColor, 1)) - { - gr.DrawLine(thick_pen, crsPoints[0], crsPoints[1]); - gr.DrawLine(thick_pen, crsPoints[2], crsPoints[3]); - } - } - } -#endif - private void Image_Changed(object sender, Flir.Atlas.Image.ImageChangedEventArgs e) { IsDirty = true; @@ -655,28 +594,6 @@ namespace ThermalImageStreamerDemo return answ; } -#if false - private void saveImgFile() - { - try - { - // fix percorsi - string dirPath = $"{BASE_PATH}\\{thermPath}"; - string filePath = $"{dirPath}\\{currImgFile}"; - if (!Directory.Exists(dirPath)) - { - Directory.CreateDirectory(dirPath); - } - // salvo! - ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; - ImgData.Thermal.SaveSnapshot(filePath); - var rawData = JsonConvert.SerializeObject(ImgData.Thermal, Formatting.Indented); - } - catch - { } - } -#endif - /// /// Sistema le temp range min/Max /// @@ -686,44 +603,6 @@ namespace ThermalImageStreamerDemo currConf.TargetRange.Max = maxRangeTemp; } -#if false - /// - /// Ultimo range di temperature osservato - /// - protected Range lastTempRange - { - get - { - return _lastTempRange; - } - set - { - _lastTempRange = value; - lblMinTemp.Text = $"{value.Minimum:N2}"; - lblMaxTemp.Text = $"{value.Maximum:N2}"; - } - } -#endif -#if false - private void getTemperatures() - { - if (ImgData.Thermal != null) - { - lastReadTemp = 0; - if (readTemp) - { - // recupero temp da FLIR - lastReadTemp = ImgData.Thermal.GetValueAt(ImgData.lastPoint).Value; - - // calcolo temp da RGB considerato limiti minMAX... - //int rgbVal = ImgData.lastImageOrig.Image.GetPixel(ImgData.lastPoint.X, ImgData.lastPoint.Y).R; - int rgbVal = getRSmooth(ImgData.lastPoint); - lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); - } - } - } -#endif - /// /// recupera immagine effettuando eventuale salvataggio /// @@ -738,15 +617,6 @@ namespace ThermalImageStreamerDemo IRCam.ThermoCamera.GetImage().EnterLock(); try { - // non funziona -#if false - // se richiesto imposto temperature min/max... - if (!chkAutoTemp.Checked) - { - Range limits = new Range(273.1 + minTemp, 273.1 + maxTemp); - IRCam.ThermoCamera.RemoteControl.CameraSettings.SetScaleLimits(limits); - } -#endif ImgData.Thermal = (ThermalImage)IRCam.ThermoCamera.GetImage(); ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; @@ -755,9 +625,6 @@ namespace ThermalImageStreamerDemo ImgData.Decorated = ImgData.Thermal.Image; if (doSave) { -#if false - saveImgFile(); -#endif ImgData.saveImgFiles(); } } @@ -772,13 +639,6 @@ namespace ThermalImageStreamerDemo sw.Stop(); msLastCam = sw.ElapsedMilliseconds; - -#if false - ThermalImage myImg = (ThermalImage)_stream.GetImage(); - myImg.TemperatureUnit = TemperatureUnit.Celsius; - string currPath = $"{labelOutputPath.Text}\\{DateTime.Now:yyyyMMyy_HHmmss}.jpg"; - myImg.SaveSnapshot(currPath); -#endif } /// diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index cfcaeffc..1c911059 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -290,8 +290,9 @@ namespace ThermoCamUtils } } - public void saveImgFiles() + public string saveImgFiles() { + string answ = ""; try { // fix percorsi @@ -320,9 +321,17 @@ namespace ThermoCamUtils // salvo colorata ColorTransf.Save(colorFilePath); + + // copia immagine con nome univoco da rendere a liberia x eventuale salvataggio in area PROD... + string uniqueName = $"{DateTime.Now:yyyyMMdd_HHmmss}"; + File.Copy(themoFilePath, themoFilePath.Replace(currImgFile, uniqueName)); + File.Copy(themoDataPath, themoDataPath.Replace(currImgFile, uniqueName)); + File.Copy(colorFilePath, colorFilePath.Replace(currImgFile, uniqueName)); + answ = uniqueName; } catch { } + return answ; } /// From c7018202c3f17345e9abe7db1e2cf258417067ec Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 09:50:07 +0100 Subject: [PATCH 03/15] ok salvataggio 3 img + dati temperature --- Thermo.Active/Properties/AssemblyInfo.cs | 2 +- ThermoCamUtils/Enums.cs | 7 +- ThermoCamUtils/ImageData.cs | 125 ++++++++++++++++++----- ThermoCamUtils/Objects.cs | 26 +++++ 4 files changed, 128 insertions(+), 32 deletions(-) diff --git a/Thermo.Active/Properties/AssemblyInfo.cs b/Thermo.Active/Properties/AssemblyInfo.cs index 48d6809d..354b939c 100644 --- a/Thermo.Active/Properties/AssemblyInfo.cs +++ b/Thermo.Active/Properties/AssemblyInfo.cs @@ -30,4 +30,4 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.1.158")] +[assembly: AssemblyVersion("1.1.159")] diff --git a/ThermoCamUtils/Enums.cs b/ThermoCamUtils/Enums.cs index 7613fdb4..f78e67a2 100644 --- a/ThermoCamUtils/Enums.cs +++ b/ThermoCamUtils/Enums.cs @@ -6,10 +6,6 @@ using System.Threading.Tasks; namespace ThermoCamUtils { - public class Enums - { - } - public enum pointList { A = 0, @@ -17,5 +13,4 @@ namespace ThermoCamUtils C, D } - -} +} \ No newline at end of file diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index 1c911059..f838716a 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -8,6 +8,7 @@ using System.Drawing.Drawing2D; using System.IO; using System.Linq; using System.Reflection; +using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; @@ -20,15 +21,14 @@ namespace ThermoCamUtils { #region Protected Fields - protected const string colorPath = "images\\Color"; - - protected const string confFormat = "json"; - - protected const string currImgFile = "_last"; - + protected const string colorPath = "images\\colored"; + protected const string currName = "_last"; + protected const string dataFormat = "dat"; + protected const string dataPath = "images\\data"; protected const string imgFormat = "jpg"; - protected const string thermPath = "images\\Therm"; + protected const string thermPath = "images\\original"; + protected const string transPath = "images\\transformed"; /// /// Ultimo range di temperature osservato @@ -46,6 +46,11 @@ namespace ThermoCamUtils public static readonly string BASE_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + /// + /// Array completo immagine + /// + public List AllPoints = new List(); + /// /// Statistiche esecuzione task /// @@ -68,6 +73,12 @@ namespace ThermoCamUtils #endregion Public Fields + #region Protected Properties + + protected Point[] _reticolo { get; set; } + + #endregion Protected Properties + #region Public Properties /// @@ -75,6 +86,9 @@ namespace ThermoCamUtils /// public Bitmap ColorTransf { get; set; } + /// + /// conf corrente applicata + /// public ThermoCamConf currConf { get; set; } = new ThermoCamConf(); /// @@ -130,6 +144,32 @@ namespace ThermoCamUtils #region Protected Methods + /// + /// se ho una immagine thermo --> reticolo punti x misura (griglia completa...) + /// + protected Point[] getReticolo() + { + Point[] answ = _reticolo; + if (answ == null) + { + if (Thermal != null) + { + int i = 0; + answ = new Point[Thermal.Size.Width * Thermal.Size.Height]; + for (int y = 0; y < Thermal.Size.Height; y++) + { + for (int x = 0; x < Thermal.Size.Width; x++) + { + answ[i] = new Point() { X = x, Y = y }; + i++; + } + } + _reticolo = answ; + } + } + return answ; + } + /// /// Calcola valore R ponderato dato un punto + intorno /// @@ -290,46 +330,81 @@ namespace ThermoCamUtils } } + /// + /// effettua salvataggio files (immagini + misure?) + /// + /// public string saveImgFiles() { string answ = ""; try { // fix percorsi - string thermoDirPath = $"{BASE_PATH}\\{thermPath}"; - string thermoColPath = $"{BASE_PATH}\\{colorPath}"; - if (!Directory.Exists(thermoDirPath)) + string dirDataTemp = $"{BASE_PATH}\\{dataPath}"; + string dirImgColor = $"{BASE_PATH}\\{colorPath}"; + string dirImgOrigi = $"{BASE_PATH}\\{thermPath}"; + string dirImgGrTra = $"{BASE_PATH}\\{transPath}"; + if (!Directory.Exists(dirDataTemp)) { - Directory.CreateDirectory(thermoDirPath); + Directory.CreateDirectory(dirDataTemp); } - if (!Directory.Exists(thermoColPath)) + if (!Directory.Exists(dirImgColor)) { - Directory.CreateDirectory(thermoColPath); + Directory.CreateDirectory(dirImgColor); + } + if (!Directory.Exists(dirImgOrigi)) + { + Directory.CreateDirectory(dirImgOrigi); + } + if (!Directory.Exists(dirImgGrTra)) + { + Directory.CreateDirectory(dirImgGrTra); } // nomi file - string themoFilePath = $"{thermoDirPath}\\{currImgFile}.{imgFormat}"; - string themoDataPath = $"{thermoDirPath}\\{currImgFile}.{confFormat}"; - string colorFilePath = $"{thermoColPath}\\{currImgFile}.{imgFormat}"; + string dataTempPath = $"{dirDataTemp}\\{currName}.{dataFormat}"; + string colorFilePath = $"{dirImgColor}\\{currName}.{imgFormat}"; + string origiFilePath = $"{dirImgOrigi}\\{currName}.{imgFormat}"; + string grTraFilePath = $"{dirImgGrTra}\\{currName}.{imgFormat}"; // salvo thermo! Thermal.Scale.IsAutoAdjustEnabled = true; - Thermal.SaveSnapshot(themoFilePath); - // salvo conf thermo - string rawData = JsonConvert.SerializeObject(Thermal, Formatting.Indented); - File.WriteAllText(themoDataPath, rawData); - + Thermal.SaveSnapshot(origiFilePath); + // salvo trasformata + GrayTransf.Save(grTraFilePath); // salvo colorata ColorTransf.Save(colorFilePath); + // richiedo tutte! + var allData = Thermal.GetValues(getReticolo()); + /// riduco info a 1 decimale + double[] floatData = Array.ConvertAll(allData, x => Math.Round(x, 1)); + + // salvo oggetto unico + TemperatureData currData = new TemperatureData() + { + ArraySize = new Size() + { + X = Thermal.Size.Width, + Y = Thermal.Size.Height + }, + ScanOrder = "YX", + Values = floatData + }; + + // salvo conf thermo + string rawData = JsonConvert.SerializeObject(currData, Formatting.None); + File.WriteAllText(dataTempPath, rawData); + // copia immagine con nome univoco da rendere a liberia x eventuale salvataggio in area PROD... string uniqueName = $"{DateTime.Now:yyyyMMdd_HHmmss}"; - File.Copy(themoFilePath, themoFilePath.Replace(currImgFile, uniqueName)); - File.Copy(themoDataPath, themoDataPath.Replace(currImgFile, uniqueName)); - File.Copy(colorFilePath, colorFilePath.Replace(currImgFile, uniqueName)); + File.Copy(origiFilePath, origiFilePath.Replace(currName, uniqueName)); + File.Copy(colorFilePath, colorFilePath.Replace(currName, uniqueName)); + File.Copy(grTraFilePath, grTraFilePath.Replace(currName, uniqueName)); + File.Copy(dataTempPath, dataTempPath.Replace(currName, uniqueName)); answ = uniqueName; } - catch + catch (Exception exc) { } return answ; } diff --git a/ThermoCamUtils/Objects.cs b/ThermoCamUtils/Objects.cs index d403f634..8b2a3ebb 100644 --- a/ThermoCamUtils/Objects.cs +++ b/ThermoCamUtils/Objects.cs @@ -38,4 +38,30 @@ namespace ThermoCamUtils #endregion Public Properties } + + [Serializable] + /// + /// Classe + /// + public class TemperatureData + { + #region Public Properties + + /// + /// Size Reticolo (=immagine) + /// + public Size ArraySize { get; set; } + + /// + /// Ordine scansione coordinate immagine, YX = prima Y (per righe), XY = prima X (per colonne) + /// + public string ScanOrder { get; set; } = "YX"; + + /// + /// valori associati al reticolo + /// + public double[] Values { get; set; } + + #endregion Public Properties + } } \ No newline at end of file From 22c25ee2bbe6489eb6d066d63a63d9553af45ecc Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 12:53:18 +0100 Subject: [PATCH 04/15] modifica comportamento LOAD image... --- ThermalImageStreamerDemo/MainForm.cs | 50 ++--- ThermoCamUtils/ImageData.cs | 322 +++++++++++++++++++-------- ThermoCamUtils/ReColorize.cs | 161 +++++++++----- 3 files changed, 356 insertions(+), 177 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 3680766f..e866830a 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -265,34 +265,12 @@ namespace ThermalImageStreamerDemo private void btnLoad_Click(object sender, EventArgs e) { - string dirPath = $"{BASE_PATH}\\{thermPath}"; - string filePath = $"{dirPath}\\{currImgFile}"; - if (File.Exists(filePath)) - { - try - { - using (var flirImg = new ThermalImageFile(filePath)) - { - //ImgData.Thermal = new ThermalImageFile(filePath); - ImgData.Thermal = (ThermalImage)flirImg; - ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; - ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; - } + // "" --> carica ultima scattata (altrimenti nome) + ImgData.fileLoad(""); - // carico DIRETTAMENTE da file... - using (Image loadedImg = Image.FromFile(filePath)) - { - ImgData.Origin = (Bitmap)loadedImg; - ImgData.Decorated = (Bitmap)loadedImg; - } - - // aggiorno visualizzazione - processImage(); - refreshDisplay(); - } - catch (Exception exc) - { } - } + // aggiorno visualizzazione + processImage(); + refreshDisplay(); } private void btnReset_Click(object sender, EventArgs e) @@ -623,9 +601,12 @@ namespace ThermalImageStreamerDemo // salvo img locale ImgData.Origin = ImgData.Thermal.Image; ImgData.Decorated = ImgData.Thermal.Image; + // recupero le temperature... + ImgData.readAllTemperatures(); + //verifico se devo salvare... if (doSave) { - ImgData.saveImgFiles(); + ImgData.fileSave(); } } catch (Exception exception) @@ -756,7 +737,7 @@ namespace ThermalImageStreamerDemo { try { - lblStats.Text = $"Camera: {msLastCam}ms | Persp {ImgData.ExTime.Stats["ImageTransf"]}ms | Color {ImgData.ExTime.Stats["ImageColor"]}ms | Points {ImgData.ExTime.Stats["AddPoints"]}ms | Measures {ImgData.ExTime.Stats["GetTemperatures"]}ms"; + lblStats.Text = $"Camera: {msLastCam}ms | Persp {ImgData.lastStatTime("ImageTransf")}ms | Color {ImgData.lastStatTime("ImageColor")}ms | Points {ImgData.lastStatTime("AddPoints")}ms | Measures {ImgData.lastStatTime("GetAllTemperatures")}ms"; } catch { } @@ -793,9 +774,14 @@ namespace ThermalImageStreamerDemo lblTempRGB.ForeColor = Color.Red; } - // mostro minimo / massimo - lblMinTemp.Text = $"{ImgData.Thermal.Scale.Range.Minimum:N2}"; - lblMaxTemp.Text = $"{ImgData.Thermal.Scale.Range.Maximum:N2}"; + try + { + // mostro minimo / massimo + lblMinTemp.Text = $"{ImgData.Thermal.Scale.Range.Minimum:N2}"; + lblMaxTemp.Text = $"{ImgData.Thermal.Scale.Range.Maximum:N2}"; + } + catch + { } } } } diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index f838716a..9ba713b4 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -30,6 +30,20 @@ namespace ThermoCamUtils protected const string thermPath = "images\\original"; protected const string transPath = "images\\transformed"; + protected string dirDataTemp = ""; + protected string dirImgColor = ""; + protected string dirImgGrTra = ""; + protected string dirImgOrigi = ""; + protected string fileColorPath = ""; + protected string fileDataPath = ""; + protected string fileGrTraPath = ""; + protected string fileOrigiPath = ""; + + /// + /// Ultimi Dati letti x temperature + /// + protected TemperatureData lastFlirData = new TemperatureData(); + /// /// Ultimo range di temperature osservato /// @@ -73,6 +87,23 @@ namespace ThermoCamUtils #endregion Public Fields + #region Public Constructors + + /// + /// Setup oggetto e variabili + /// + public ImageData() + { + // setup folder varie + dirDataTemp = $"{BASE_PATH}\\{dataPath}"; + dirImgColor = $"{BASE_PATH}\\{colorPath}"; + dirImgOrigi = $"{BASE_PATH}\\{thermPath}"; + dirImgGrTra = $"{BASE_PATH}\\{transPath}"; + checkLocadOutDir(); + } + + #endregion Public Constructors + #region Protected Properties protected Point[] _reticolo { get; set; } @@ -115,29 +146,55 @@ namespace ThermoCamUtils #region Private Methods + private void checkLocadOutDir() + { + // verifico esistenza directory + if (!Directory.Exists(dirDataTemp)) + { + Directory.CreateDirectory(dirDataTemp); + } + if (!Directory.Exists(dirImgColor)) + { + Directory.CreateDirectory(dirImgColor); + } + if (!Directory.Exists(dirImgOrigi)) + { + Directory.CreateDirectory(dirImgOrigi); + } + if (!Directory.Exists(dirImgGrTra)) + { + Directory.CreateDirectory(dirImgGrTra); + } + } + private void drawPoint(Color currColor, Point currPoint) { - // disegno! - using (Graphics gr = Graphics.FromImage(Decorated)) + try { - gr.SmoothingMode = SmoothingMode.AntiAlias; - - Point[] crsPoints = new Point[4]; - for (int i = 0; i < 4; i++) + // disegno! + using (Graphics gr = Graphics.FromImage(Decorated)) { - crsPoints[i] = currPoint; - } - crsPoints[0].X = crsPoints[0].X - 4; - crsPoints[1].X = crsPoints[1].X + 4; - crsPoints[2].Y = crsPoints[2].Y - 4; - crsPoints[3].Y = crsPoints[3].Y + 4; + gr.SmoothingMode = SmoothingMode.AntiAlias; - using (Pen thick_pen = new Pen(currColor, 1)) - { - gr.DrawLine(thick_pen, crsPoints[0], crsPoints[1]); - gr.DrawLine(thick_pen, crsPoints[2], crsPoints[3]); + Point[] crsPoints = new Point[4]; + for (int i = 0; i < 4; i++) + { + crsPoints[i] = currPoint; + } + crsPoints[0].X = crsPoints[0].X - 4; + crsPoints[1].X = crsPoints[1].X + 4; + crsPoints[2].Y = crsPoints[2].Y - 4; + crsPoints[3].Y = crsPoints[3].Y + 4; + + using (Pen thick_pen = new Pen(currColor, 1)) + { + gr.DrawLine(thick_pen, crsPoints[0], crsPoints[1]); + gr.DrawLine(thick_pen, crsPoints[2], crsPoints[3]); + } } } + catch (Exception exc) + { } } #endregion Private Methods @@ -218,12 +275,17 @@ namespace ThermoCamUtils { try { +#if false //lastTempRange = new Range(lastThermalImage.GetValueFromSignal(lastThermalImage.MinSignalValue), lastThermalImage.GetValueFromSignal(lastThermalImage.MaxSignalValue)); lastTempRange = new Range(Thermal.Scale.Range.Minimum, Thermal.Scale.Range.Maximum); +#endif sw.Restart(); var pTransf = new PerspectiveTransform(currConf.OrigPoints.Coords, currConf.DestPoints.Coords); + var rTrasf = new ReColorize(currConf.TargetRange.Min, currConf.TargetRange.Max); +#if false var rTrasf = new ReColorize(lastTempRange.Minimum, lastTempRange.Maximum, currConf.TargetRange.Min, currConf.TargetRange.Max); +#endif var transfImg = pTransf.convertImage(Origin, currConf.TargetSize.X, currConf.TargetSize.Y); GrayTransf = transfImg; sw.Stop(); @@ -233,16 +295,21 @@ namespace ThermoCamUtils if (colorizeFirst) { // ora calcolo ricolorazione da immagine originale + var colImg = rTrasf.process(Origin, lastFlirData.Values); +#if false var colImg = rTrasf.process(Origin, fastBitmap); +#endif // e faccio la stessa trasformazione di riscalatura var transfColImg = pTransf.convertImage(colImg, currConf.TargetSize.X, currConf.TargetSize.Y); ColorTransf = transfColImg; } +#if false else { // old way da immagine BN full size ColorTransf = rTrasf.process(GrayTransf, fastBitmap); } +#endif sw.Stop(); ExTime.recordData("ImageColor", sw.ElapsedMilliseconds); } @@ -279,6 +346,103 @@ namespace ThermoCamUtils } } + /// + /// effettua salvataggio files (immagini + misure) + /// + /// + public bool fileLoad(string fileName) + { + bool answ = false; + if (string.IsNullOrEmpty(fileName)) + { + // uso last... + fileName = currName; + } + + // setup nomi files + fileDataPath = $"{dirDataTemp}\\{fileName}.{dataFormat}"; + fileColorPath = $"{dirImgColor}\\{fileName}.{imgFormat}"; + fileOrigiPath = $"{dirImgOrigi}\\{fileName}.{imgFormat}"; + fileGrTraPath = $"{dirImgGrTra}\\{fileName}.{imgFormat}"; + + // se trovo i files... + if (File.Exists(fileOrigiPath)) + { + try + { + // carico oggetto FLIR + using (var flirImg = new ThermalImageFile(fileOrigiPath)) + { + //ImgData.Thermal = new ThermalImageFile(filePath); + Thermal = (ThermalImage)flirImg; + Thermal.TemperatureUnit = TemperatureUnit.Celsius; + Thermal.Scale.IsAutoAdjustEnabled = true; + } + + // carico DIRETTAMENTE da file le immagini iniziali da generare... + using (Image loadedImg = Image.FromFile(fileOrigiPath)) + { + Origin = (Bitmap)loadedImg.Clone(); + Decorated = (Bitmap)loadedImg.Clone(); + } + + // carico il file delle temperature + string rawData = File.ReadAllText(fileDataPath); + if (!string.IsNullOrEmpty(rawData)) + { + lastFlirData = JsonConvert.DeserializeObject(rawData); + } + } + catch (Exception exc) + { } + } + + return answ; + } + + /// + /// effettua salvataggio files (immagini + misure) + /// + /// + public string fileSave() + { + string answ = ""; + try + { + // x sicurezza check directory... + checkLocadOutDir(); + + // setup nomi files + fileDataPath = $"{dirDataTemp}\\{currName}.{dataFormat}"; + fileColorPath = $"{dirImgColor}\\{currName}.{imgFormat}"; + fileOrigiPath = $"{dirImgOrigi}\\{currName}.{imgFormat}"; + fileGrTraPath = $"{dirImgGrTra}\\{currName}.{imgFormat}"; + + // salvo thermo! + Thermal.Scale.IsAutoAdjustEnabled = true; + Thermal.SaveSnapshot(fileOrigiPath); + // salvo trasformata + GrayTransf.Save(fileGrTraPath); + // salvo colorata + ColorTransf.Save(fileColorPath); + + // salvo conf thermo + string rawData = JsonConvert.SerializeObject(lastFlirData, Formatting.None); + File.WriteAllText(fileDataPath, rawData); + + // copia immagine con nome univoco da rendere a libreria x eventuale salvataggio in area PROD del nome immagine associato... + string uniqueName = $"{DateTime.Now:yyyyMMdd_HHmmss}"; + File.Copy(fileOrigiPath, fileOrigiPath.Replace(currName, uniqueName)); + File.Copy(fileColorPath, fileColorPath.Replace(currName, uniqueName)); + File.Copy(fileGrTraPath, fileGrTraPath.Replace(currName, uniqueName)); + File.Copy(fileDataPath, fileDataPath.Replace(currName, uniqueName)); + answ = uniqueName; + } + catch (Exception exc) + { } + return answ; + } + /// /// Recupera temperature coi 2 metodi da FLIR e da B/N /// @@ -290,19 +454,22 @@ namespace ThermoCamUtils lastReadTemp = 0; if (readTemp) { - sw.Restart(); - foreach (var item in currConf.MeasPoints) + try { - // recupero temp da FLIR - lastReadTemp = Thermal.GetValueAt(item.Coords).Value; + sw.Restart(); + foreach (var item in currConf.MeasPoints) + { + // recupero da ARRAY in memoria delle ultime letture fatte... + lastCalcTemp = lastFlirData.Values[item.Coords.X + Thermal.Size.Width * item.Coords.Y]; - // calcolo temp da RGB considerato limiti minMAX... - //int rgbVal = lastImageOrig.Image.GetPixel(lastPoint.X, lastPoint.Y).R; - int rgbVal = getRSmooth(item.Coords); - lastCalcTemp = lastTempRange.Minimum + ((lastTempRange.Maximum - lastTempRange.Minimum) * rgbVal / 255); + // recupero temp da FLIR + lastReadTemp = Thermal.GetValueAt(item.Coords).Value; + } + sw.Stop(); + ExTime.recordData("GetTemperatures", sw.ElapsedMilliseconds); } - sw.Stop(); - ExTime.recordData("GetTemperatures", sw.ElapsedMilliseconds); + catch (Exception exc) + { } } } } @@ -331,84 +498,51 @@ namespace ThermoCamUtils } /// - /// effettua salvataggio files (immagini + misure?) + /// recupero valore statistica richiesta /// + /// /// - public string saveImgFiles() + public double lastStatTime(string statName) { - string answ = ""; - try + double answ = -1; + if (ExTime.Stats.ContainsKey(statName)) { - // fix percorsi - string dirDataTemp = $"{BASE_PATH}\\{dataPath}"; - string dirImgColor = $"{BASE_PATH}\\{colorPath}"; - string dirImgOrigi = $"{BASE_PATH}\\{thermPath}"; - string dirImgGrTra = $"{BASE_PATH}\\{transPath}"; - if (!Directory.Exists(dirDataTemp)) + try { - Directory.CreateDirectory(dirDataTemp); + answ = ExTime.Stats[statName]; } - if (!Directory.Exists(dirImgColor)) - { - Directory.CreateDirectory(dirImgColor); - } - if (!Directory.Exists(dirImgOrigi)) - { - Directory.CreateDirectory(dirImgOrigi); - } - if (!Directory.Exists(dirImgGrTra)) - { - Directory.CreateDirectory(dirImgGrTra); - } - - // nomi file - string dataTempPath = $"{dirDataTemp}\\{currName}.{dataFormat}"; - string colorFilePath = $"{dirImgColor}\\{currName}.{imgFormat}"; - string origiFilePath = $"{dirImgOrigi}\\{currName}.{imgFormat}"; - string grTraFilePath = $"{dirImgGrTra}\\{currName}.{imgFormat}"; - - // salvo thermo! - Thermal.Scale.IsAutoAdjustEnabled = true; - Thermal.SaveSnapshot(origiFilePath); - // salvo trasformata - GrayTransf.Save(grTraFilePath); - // salvo colorata - ColorTransf.Save(colorFilePath); - - // richiedo tutte! - var allData = Thermal.GetValues(getReticolo()); - /// riduco info a 1 decimale - double[] floatData = Array.ConvertAll(allData, x => Math.Round(x, 1)); - - // salvo oggetto unico - TemperatureData currData = new TemperatureData() - { - ArraySize = new Size() - { - X = Thermal.Size.Width, - Y = Thermal.Size.Height - }, - ScanOrder = "YX", - Values = floatData - }; - - // salvo conf thermo - string rawData = JsonConvert.SerializeObject(currData, Formatting.None); - File.WriteAllText(dataTempPath, rawData); - - // copia immagine con nome univoco da rendere a liberia x eventuale salvataggio in area PROD... - string uniqueName = $"{DateTime.Now:yyyyMMdd_HHmmss}"; - File.Copy(origiFilePath, origiFilePath.Replace(currName, uniqueName)); - File.Copy(colorFilePath, colorFilePath.Replace(currName, uniqueName)); - File.Copy(grTraFilePath, grTraFilePath.Replace(currName, uniqueName)); - File.Copy(dataTempPath, dataTempPath.Replace(currName, uniqueName)); - answ = uniqueName; + catch + { } } - catch (Exception exc) - { } return answ; } + /// + /// Effettua al lettura di tutte el temperature e le salva nell'oggetto in memoria + /// + public void readAllTemperatures() + { + sw.Restart(); + // richiedo tutte! + var allData = Thermal.GetValues(getReticolo()); + /// riduco info a 1 decimale + double[] floatData = Array.ConvertAll(allData, x => Math.Round(x, 2)); + + // salvo oggetto unico + lastFlirData = new TemperatureData() + { + ArraySize = new Size() + { + X = Thermal.Size.Width, + Y = Thermal.Size.Height + }, + ScanOrder = "YX", + Values = floatData + }; + sw.Stop(); + ExTime.recordData("GetAllTemperatures", sw.ElapsedMilliseconds); + } + /// /// Salvo il punto di misura selezionato /// diff --git a/ThermoCamUtils/ReColorize.cs b/ThermoCamUtils/ReColorize.cs index 5c4ebe52..b5bd7d1c 100644 --- a/ThermoCamUtils/ReColorize.cs +++ b/ThermoCamUtils/ReColorize.cs @@ -13,29 +13,99 @@ namespace ThermoCamUtils { #region Protected Fields - protected double delta = 0; protected double maxSca = 5000; - protected double maxVal = 5000; protected double minSca = -999; - protected double minVal = -999; #endregion Protected Fields +#if false + protected double delta = 0; + protected double maxVal = 5000; + protected double minVal = -999; +#endif + #region Public Constructors - public ReColorize(double minValue, double maxValue, double minScale, double maxScale) + //public ReColorize(double minValue, double maxValue, double minScale, double maxScale) + public ReColorize(double minScale, double maxScale) { - minVal = minValue; - maxVal = maxValue; minSca = minScale; maxSca = maxScale; +#if false + minVal = minValue; + maxVal = maxValue; delta = minVal - minSca; +#endif } #endregion Public Constructors #region Protected Methods + /// + /// Calcola colore su scala dato rapporto valore temperatura su min/max + /// + /// + /// + protected Color Rescale(ref double currTemp) + { + int R = 0; + int G = 0; + int B = 0; + int ValScal = 0; + + // ora calcolo valore scalare + ValScal = (int)(255 * (currTemp - minSca) / (maxSca - minSca)); + + if (ValScal < 0) + { + R = 0; + G = 0; + B = 0; + } + else if (ValScal <= 51) + { + R = 0; + G = 0; + B = (int)(ValScal * 5); + } + else if (ValScal <= 102) + { + R = (int)((ValScal - 51) * 5); + G = 0; + B = 255; + } + else if (ValScal <= 153) + { + R = 255; + G = 0; + B = (int)(255 - ((ValScal - 102) * 5)); + } + else if (ValScal <= 204) + { + R = 255; + G = (int)((ValScal - 153) * 5); + B = 0; + } + else if (ValScal <= 255) + { + R = 255; + G = 255; + B = (int)((ValScal - 204) * 5); + } + else + { + R = 255; + G = 255; + B = 255; + } + + return Color.FromArgb(R, G, B); + } + + #endregion Protected Methods + +#if false /// /// Calcola colore su scala dato rapporto valore B/N su min/max /// @@ -99,12 +169,17 @@ namespace ThermoCamUtils return Color.FromArgb(R, G, B); } - - #endregion Protected Methods +#endif #region Public Methods - public Bitmap process(Bitmap original, bool doFast) + /// + /// Processing ricolorazione + /// + /// + /// + /// + public Bitmap process(Bitmap original, double[] tempVal) { /*--------------------------------------------- // indicazioni x ottimizzare da qui: @@ -112,55 +187,39 @@ namespace ThermoCamUtils -----------------------------------------------*/ Bitmap imgColor = original.Clone(new Rectangle(0, 0, original.Width, original.Height), original.PixelFormat); +#if true int currVal = 0; +#endif - if (doFast) + BitmapData bitmapData = imgColor.LockBits(new Rectangle(0, 0, imgColor.Width, imgColor.Height), ImageLockMode.ReadWrite, imgColor.PixelFormat); + + int bytesPerPixel = Bitmap.GetPixelFormatSize(imgColor.PixelFormat) / 8; + int byteCount = bitmapData.Stride * imgColor.Height; + byte[] pixels = new byte[byteCount]; + IntPtr ptrFirstPixel = bitmapData.Scan0; + Marshal.Copy(ptrFirstPixel, pixels, 0, pixels.Length); + int heightInPixels = bitmapData.Height; + int widthInBytes = bitmapData.Width * bytesPerPixel; + + for (int y = 0; y < heightInPixels; y++) { - BitmapData bitmapData = imgColor.LockBits(new Rectangle(0, 0, imgColor.Width, imgColor.Height), ImageLockMode.ReadWrite, imgColor.PixelFormat); - - int bytesPerPixel = Bitmap.GetPixelFormatSize(imgColor.PixelFormat) / 8; - int byteCount = bitmapData.Stride * imgColor.Height; - byte[] pixels = new byte[byteCount]; - IntPtr ptrFirstPixel = bitmapData.Scan0; - Marshal.Copy(ptrFirstPixel, pixels, 0, pixels.Length); - int heightInPixels = bitmapData.Height; - int widthInBytes = bitmapData.Width * bytesPerPixel; - - for (int y = 0; y < heightInPixels; y++) + int currentLine = y * bitmapData.Stride; + for (int x = 0; x < widthInBytes; x = x + bytesPerPixel) { - int currentLine = y * bitmapData.Stride; - for (int x = 0; x < widthInBytes; x = x + bytesPerPixel) - { - // prendo il rosso - int oldRed = pixels[currentLine + x + 0]; - currVal = pixels[currentLine + x + 2]; - var newCol = Rescale(ref currVal); - pixels[currentLine + x] = (byte)newCol.B; - pixels[currentLine + x + 1] = (byte)newCol.G; - pixels[currentLine + x + 2] = (byte)newCol.R; - //currVal = original.GetPixel(x, y).R; - //imgColor.SetPixel(x, y, Rescale(ref currVal)); - } - } - - // copy modified bytes back - Marshal.Copy(pixels, 0, ptrFirstPixel, pixels.Length); - imgColor.UnlockBits(bitmapData); - } - else - { - // recupero matrice di punti con valore RGB - for (int x = 0; x < original.Width; x++) - { - for (int y = 0; y < original.Height; y++) - { - // esecuo ricalcolo - currVal = original.GetPixel(x, y).R; - imgColor.SetPixel(x, y, Rescale(ref currVal)); - } +#if true + currVal = pixels[currentLine + x + 2]; +#endif + var newCol = Rescale(ref tempVal[x + original.Width * y]); + pixels[currentLine + x] = (byte)newCol.B; + pixels[currentLine + x + 1] = (byte)newCol.G; + pixels[currentLine + x + 2] = (byte)newCol.R; } } + // copy modified bytes back + Marshal.Copy(pixels, 0, ptrFirstPixel, pixels.Length); + imgColor.UnlockBits(bitmapData); + return imgColor; } From c9c1f20f9efa0511177474cfba9383803dfd7218 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 14:50:13 +0100 Subject: [PATCH 05/15] fix range reload + fix color reload --- ThermalImageStreamerDemo/MainForm.cs | 5 +++-- ThermoCamUtils/ImageData.cs | 30 +++++++++++++++++++++++----- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index e866830a..9676beb5 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -598,6 +598,7 @@ namespace ThermalImageStreamerDemo ImgData.Thermal = (ThermalImage)IRCam.ThermoCamera.GetImage(); ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; + ImgData.lastTempRange = new Range(ImgData.Thermal.Scale.Range.Minimum, ImgData.Thermal.Scale.Range.Maximum); // salvo img locale ImgData.Origin = ImgData.Thermal.Image; ImgData.Decorated = ImgData.Thermal.Image; @@ -777,8 +778,8 @@ namespace ThermalImageStreamerDemo try { // mostro minimo / massimo - lblMinTemp.Text = $"{ImgData.Thermal.Scale.Range.Minimum:N2}"; - lblMaxTemp.Text = $"{ImgData.Thermal.Scale.Range.Maximum:N2}"; + lblMinTemp.Text = $"{ImgData.lastTempRange.Minimum:N2}"; + lblMaxTemp.Text = $"{ImgData.lastTempRange.Maximum:N2}"; } catch { } diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index 9ba713b4..e28cea2d 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -44,11 +44,6 @@ namespace ThermoCamUtils /// protected TemperatureData lastFlirData = new TemperatureData(); - /// - /// Ultimo range di temperature osservato - /// - protected Range lastTempRange = new Range(0, 5000); - /// /// Stopwatch x benchmarking /// @@ -85,6 +80,11 @@ namespace ThermoCamUtils /// public double lastReadTemp = 0; + /// + /// Ultimo range di temperature osservato + /// + public Range lastTempRange = new Range(0, 5000); + #endregion Public Fields #region Public Constructors @@ -352,6 +352,8 @@ namespace ThermoCamUtils /// public bool fileLoad(string fileName) { + double minTemp = 5000; + double maxTemp = 0; bool answ = false; if (string.IsNullOrEmpty(fileName)) { @@ -386,11 +388,29 @@ namespace ThermoCamUtils Decorated = (Bitmap)loadedImg.Clone(); } + using (Image loadedImg = Image.FromFile(fileColorPath)) + { + ColorTransf = (Bitmap)loadedImg.Clone(); + } + // carico il file delle temperature string rawData = File.ReadAllText(fileDataPath); if (!string.IsNullOrEmpty(rawData)) { lastFlirData = JsonConvert.DeserializeObject(rawData); + // calcolo min/Max + foreach (var item in lastFlirData.Values) + { + if (item < minTemp) + { + minTemp = item; + } + if (item > maxTemp) + { + maxTemp = item; + } + } + lastTempRange = new Range(minTemp, maxTemp); } } catch (Exception exc) From bb4ac545a08e459f47bf0ec09f52e910fe19ba85 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 18:13:15 +0100 Subject: [PATCH 06/15] completato spostamento metodi connect/disconnect camera in class lib --- ThermalImageStreamerDemo/MainForm.Designer.cs | 60 +----- ThermalImageStreamerDemo/MainForm.cs | 170 +++++++-------- ThermoCamUtils/ImageData.cs | 194 +++++++++++++----- ThermoCamUtils/ReColorize.cs | 2 +- 4 files changed, 234 insertions(+), 192 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.Designer.cs b/ThermalImageStreamerDemo/MainForm.Designer.cs index 0a208c0a..ac334c4f 100644 --- a/ThermalImageStreamerDemo/MainForm.Designer.cs +++ b/ThermalImageStreamerDemo/MainForm.Designer.cs @@ -46,15 +46,12 @@ this.groupBox3 = new System.Windows.Forms.GroupBox(); this.lblMaxTemp = new System.Windows.Forms.Label(); this.lblMinTemp = new System.Windows.Forms.Label(); - this.lblTempRGB = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.txtMaxScale = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.txtMinScale = new System.Windows.Forms.TextBox(); this.chkReadTemp = new System.Windows.Forms.CheckBox(); this.lblReadTemp = new System.Windows.Forms.Label(); - this.chkRevProc = new System.Windows.Forms.CheckBox(); - this.chkParallel = new System.Windows.Forms.CheckBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.label5 = new System.Windows.Forms.Label(); this.txtBC = new System.Windows.Forms.TextBox(); @@ -193,8 +190,6 @@ this.panelCmd.Controls.Add(this.chkSaveAll); this.panelCmd.Controls.Add(this.btnLoad); this.panelCmd.Controls.Add(this.groupBox3); - this.panelCmd.Controls.Add(this.chkRevProc); - this.panelCmd.Controls.Add(this.chkParallel); this.panelCmd.Controls.Add(this.groupBox2); this.panelCmd.Controls.Add(this.groupBox1); this.panelCmd.Controls.Add(this.checkLive); @@ -229,7 +224,6 @@ // this.groupBox3.Controls.Add(this.lblMaxTemp); this.groupBox3.Controls.Add(this.lblMinTemp); - this.groupBox3.Controls.Add(this.lblTempRGB); this.groupBox3.Controls.Add(this.label6); this.groupBox3.Controls.Add(this.txtMaxScale); this.groupBox3.Controls.Add(this.label7); @@ -238,7 +232,7 @@ this.groupBox3.Controls.Add(this.lblReadTemp); this.groupBox3.Location = new System.Drawing.Point(8, 333); this.groupBox3.Name = "groupBox3"; - this.groupBox3.Size = new System.Drawing.Size(175, 175); + this.groupBox3.Size = new System.Drawing.Size(175, 119); this.groupBox3.TabIndex = 5; this.groupBox3.TabStop = false; this.groupBox3.Text = "Temperature"; @@ -247,7 +241,7 @@ // this.lblMaxTemp.AutoSize = true; this.lblMaxTemp.ForeColor = System.Drawing.SystemColors.ControlLightLight; - this.lblMaxTemp.Location = new System.Drawing.Point(89, 67); + this.lblMaxTemp.Location = new System.Drawing.Point(89, 42); this.lblMaxTemp.MinimumSize = new System.Drawing.Size(80, 0); this.lblMaxTemp.Name = "lblMaxTemp"; this.lblMaxTemp.Size = new System.Drawing.Size(80, 13); @@ -259,29 +253,17 @@ // this.lblMinTemp.AutoSize = true; this.lblMinTemp.ForeColor = System.Drawing.SystemColors.ControlText; - this.lblMinTemp.Location = new System.Drawing.Point(7, 67); + this.lblMinTemp.Location = new System.Drawing.Point(7, 42); this.lblMinTemp.MinimumSize = new System.Drawing.Size(80, 0); this.lblMinTemp.Name = "lblMinTemp"; this.lblMinTemp.Size = new System.Drawing.Size(80, 13); this.lblMinTemp.TabIndex = 16; this.lblMinTemp.Text = "? °C"; // - // lblTempRGB - // - this.lblTempRGB.AutoSize = true; - this.lblTempRGB.ForeColor = System.Drawing.SystemColors.ButtonHighlight; - this.lblTempRGB.Location = new System.Drawing.Point(89, 41); - this.lblTempRGB.MinimumSize = new System.Drawing.Size(80, 0); - this.lblTempRGB.Name = "lblTempRGB"; - this.lblTempRGB.Size = new System.Drawing.Size(80, 13); - this.lblTempRGB.TabIndex = 15; - this.lblTempRGB.Text = "? °C"; - this.lblTempRGB.TextAlign = System.Drawing.ContentAlignment.TopRight; - // // label6 // this.label6.AutoSize = true; - this.label6.Location = new System.Drawing.Point(7, 135); + this.label6.Location = new System.Drawing.Point(7, 91); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(57, 13); this.label6.TabIndex = 13; @@ -289,7 +271,7 @@ // // txtMaxScale // - this.txtMaxScale.Location = new System.Drawing.Point(92, 132); + this.txtMaxScale.Location = new System.Drawing.Point(92, 88); this.txtMaxScale.Name = "txtMaxScale"; this.txtMaxScale.Size = new System.Drawing.Size(77, 20); this.txtMaxScale.TabIndex = 12; @@ -300,7 +282,7 @@ // label7 // this.label7.AutoSize = true; - this.label7.Location = new System.Drawing.Point(7, 108); + this.label7.Location = new System.Drawing.Point(7, 64); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(54, 13); this.label7.TabIndex = 11; @@ -308,7 +290,7 @@ // // txtMinScale // - this.txtMinScale.Location = new System.Drawing.Point(92, 105); + this.txtMinScale.Location = new System.Drawing.Point(92, 61); this.txtMinScale.Name = "txtMinScale"; this.txtMinScale.Size = new System.Drawing.Size(77, 20); this.txtMinScale.TabIndex = 10; @@ -338,30 +320,6 @@ this.lblReadTemp.Text = "? °C"; this.lblReadTemp.TextAlign = System.Drawing.ContentAlignment.TopRight; // - // chkRevProc - // - this.chkRevProc.AutoSize = true; - this.chkRevProc.Checked = true; - this.chkRevProc.CheckState = System.Windows.Forms.CheckState.Checked; - this.chkRevProc.Location = new System.Drawing.Point(8, 514); - this.chkRevProc.Name = "chkRevProc"; - this.chkRevProc.Size = new System.Drawing.Size(100, 17); - this.chkRevProc.TabIndex = 11; - this.chkRevProc.Text = "Rev processing"; - this.chkRevProc.UseVisualStyleBackColor = true; - // - // chkParallel - // - this.chkParallel.AutoSize = true; - this.chkParallel.Checked = true; - this.chkParallel.CheckState = System.Windows.Forms.CheckState.Checked; - this.chkParallel.Location = new System.Drawing.Point(8, 533); - this.chkParallel.Name = "chkParallel"; - this.chkParallel.Size = new System.Drawing.Size(112, 17); - this.chkParallel.TabIndex = 10; - this.chkParallel.Text = "Bitmap Marshalled"; - this.chkParallel.UseVisualStyleBackColor = true; - // // groupBox2 // this.groupBox2.Controls.Add(this.label5); @@ -590,6 +548,7 @@ this.chkShowOrig.TabIndex = 12; this.chkShowOrig.Text = "Show Original"; this.chkShowOrig.UseVisualStyleBackColor = true; + this.chkShowOrig.CheckedChanged += new System.EventHandler(this.chkShowOrig_CheckedChanged); // // MainForm // @@ -669,15 +628,12 @@ private System.Windows.Forms.Label lblImgC; private System.Windows.Forms.ToolStripProgressBar progBar; private System.Windows.Forms.ToolStripStatusLabel lblStats; - private System.Windows.Forms.CheckBox chkParallel; - private System.Windows.Forms.CheckBox chkRevProc; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox txtMaxScale; private System.Windows.Forms.Label label7; private System.Windows.Forms.TextBox txtMinScale; private System.Windows.Forms.Label lblPoint; - private System.Windows.Forms.Label lblTempRGB; private System.Windows.Forms.CheckBox chkShowOrig; private System.Windows.Forms.Button btnReset; private System.Windows.Forms.Button btnLoad; diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 9676beb5..2fa55e1f 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -22,29 +22,24 @@ namespace ThermalImageStreamerDemo private readonly Timer _timerRefreshUi = new Timer(); -#if false - private Camera IRCam.ThermoCamera; -#endif - - private RecorderForm _recorder; - #endregion Private Fields +#if false + private RecorderForm _recorder; +#endif + #region Protected Fields protected const string colorPath = "images\\Color"; protected const string confFileName = "ThermoConf.json"; +#if false protected const string currImgFile = "ThermalData.jpg"; +#endif protected const string thermPath = "images\\Therm"; - /// - /// Ultimo range di temperature osservato - /// - protected Range _lastTempRange = new Range(-999, 5000); - protected int currPoint = -1; /// @@ -52,8 +47,6 @@ namespace ThermalImageStreamerDemo /// protected ImageData ImgData = new ImageData(); - protected double msLastCam = 0; - protected Stopwatch sw = new Stopwatch(); #endregion Protected Fields @@ -72,6 +65,11 @@ namespace ThermalImageStreamerDemo InitializeComponent(); _timerRefreshUi.Interval = 100; _timerRefreshUi.Tick += _timerRefreshUi_Tick; + _timerRefreshUi.Start(); + // collego eventi ImgData + ImgData.eh_CameraConnected += ImgData_eh_CameraConnected; + ImgData.eh_CameraDisposed += ImgData_eh_CameraDisposed; + ImgData.eh_CameraConnStatusChanged += ImgData_eh_CameraConnStatusChanged; // cerco se ho un set di parametri già impostati... tryReloadConf(); // sistemo le conf temp @@ -84,8 +82,6 @@ namespace ThermalImageStreamerDemo #region Private Properties - private bool IsDirty { get; set; } - private bool liveView { get @@ -251,7 +247,7 @@ namespace ThermalImageStreamerDemo // se è in live view --> continuo if (liveView) { - takePicture(saveEnabled); + ImgData.takePicture(saveEnabled); processImage(); refreshDisplay(); } @@ -281,23 +277,15 @@ namespace ThermalImageStreamerDemo private void btnSave_Click(object sender, EventArgs e) { - takePicture(true); + ImgData.takePicture(true); processImage(); refreshDisplay(); } - private void Camera_ConnectionStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) - { - BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); - BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); - // se si disconnette --> NUOVA richiesta connessione alla CHILD... - - // TODO FARE!!! - } - private void checkLive_CheckedChanged(object sender, EventArgs e) { - // non serve fare nulla + // cambio periodo timer! + _timerRefreshUi.Interval = checkLive.Checked ? 100 : 500; } private void chkPointSetup_CheckedChanged(object sender, EventArgs e) @@ -319,53 +307,17 @@ namespace ThermalImageStreamerDemo if (!readTemp) { lblReadTemp.Text = "? °C"; - lblTempRGB.Text = "? °C"; } } - private void ConnectCamera(CameraDeviceInfo cameraDeviceInfo) + private void chkShowOrig_CheckedChanged(object sender, EventArgs e) { - DisposeCamera(); - switch (cameraDeviceInfo.SelectedStreamingFormat) - { - case ImageFormat.FlirFileFormat: - IRCam.ThermoCamera = new ThermalCamera(); - break; - - case ImageFormat.Argb: - IRCam.ThermoCamera = new VideoOverlayCamera(); - break; - - default: - throw new ArgumentOutOfRangeException(); - } - IRCam.ThermoCamera.ConnectionStatusChanged += Camera_ConnectionStatusChanged; - IRCam.ThermoCamera.GetImage().Changed += Image_Changed; - IRCam.ThermoCamera.Connect(cameraDeviceInfo); - if (IRCam.ThermoCamera.Recorder == null && _recorder != null) - { - _recorder.Dispose(); - _recorder = null; - } - if (_recorder != null) - { - if (!_recorder.IsDisposed) - _recorder.Initialize(IRCam.ThermoCamera); - } - recorderToolStripMenuItem.Enabled = IRCam.ThermoCamera.Recorder != null; - _timerRefreshUi.Start(); - } - - private void DisconnectCamera() - { - if (IRCam.ThermoCamera == null) return; - - IRCam.ThermoCamera.Disconnect(); + refreshDisplay(); } private void disconnectToolStripMenuItem_Click(object sender, EventArgs e) { - DisconnectCamera(); + ImgData.DisconnectCamera(); } private void discoveryToolStripMenuItem_Click(object sender, EventArgs e) @@ -373,7 +325,7 @@ namespace ThermalImageStreamerDemo var discoveryDlg = new DiscoveryForm(); if (discoveryDlg.ShowDialog() == DialogResult.OK) { - ConnectCamera(discoveryDlg.SelectedCameraDevice); + ImgData.ConnectCamera(discoveryDlg.SelectedCameraDevice); // salvo nome camera in conf attuale! currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; saveConf(); @@ -393,6 +345,50 @@ namespace ThermalImageStreamerDemo } } + private void ImgData_eh_CameraConnected(object sender, EventArgs e) + { +#if false + _timerRefreshUi.Start(); +#endif + _timerRefreshUi.Interval = 100; + } + + private void ImgData_eh_CameraConnStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) + { + BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); + BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); + // se si disconnette --> NUOVA richiesta connessione alla CHILD... + + // TODO FARE!!! + } + + private void ImgData_eh_CameraDisposed(object sender, EventArgs e) + { +#if false + _timerRefreshUi.Stop(); +#endif + _timerRefreshUi.Interval = 500; + } + +#if false + private void Camera_ConnectionStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) + { + BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); + BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); + // se si disconnette --> NUOVA richiesta connessione alla CHILD... + + // TODO FARE!!! + } +#endif +#if false + private void DisconnectCamera() + { + if (IRCam.ThermoCamera == null) return; + + IRCam.ThermoCamera.Disconnect(); + } +#endif +#if false private void DisposeCamera() { _timerRefreshUi.Stop(); @@ -406,11 +402,14 @@ namespace ThermalImageStreamerDemo IRCam.ThermoCamera.GetImage().Changed -= Image_Changed; IRCam.ThermoCamera.Dispose(); } +#endif +#if false private void Image_Changed(object sender, Flir.Atlas.Image.ImageChangedEventArgs e) { IsDirty = true; } +#endif private void lblOrigA_Click(object sender, EventArgs e) { @@ -434,12 +433,14 @@ namespace ThermalImageStreamerDemo private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { +#if false if (_recorder != null && _recorder.IsDisposed == false) { _recorder.Dispose(); } +#endif - DisposeCamera(); + ImgData.DisposeCamera(); } private void MainForm_Load(object sender, EventArgs e) @@ -530,11 +531,12 @@ namespace ThermalImageStreamerDemo { // disegno immagine ImgData.getTemperatures(readTemp); - ImgData.calculateTarget(chkParallel.Checked, chkRevProc.Checked); + ImgData.calculateTarget(); } private void recorderToolStripMenuItem_Click(object sender, EventArgs e) { +#if false if (_recorder == null || _recorder.IsDisposed) { _recorder = new RecorderForm(); @@ -543,6 +545,7 @@ namespace ThermalImageStreamerDemo } _recorder.Show(); _recorder.Focus(); +#endif } private void refreshDisplay() @@ -581,6 +584,7 @@ namespace ThermalImageStreamerDemo currConf.TargetRange.Max = maxRangeTemp; } +#if false /// /// recupera immagine effettuando eventuale salvataggio /// @@ -622,6 +626,7 @@ namespace ThermalImageStreamerDemo sw.Stop(); msLastCam = sw.ElapsedMilliseconds; } +#endif /// /// Verifica se il punto era in edit, altrimenti segnala e lo attiva... restituendo colore x il controllo @@ -728,7 +733,7 @@ namespace ThermalImageStreamerDemo if (currConf.OrigPoints.Coords.Count > 3) { lblOrigD.Text = $"D: ({currConf.OrigPoints.Coords[3].X},{currConf.OrigPoints.Coords[3].Y})"; - ImgData.calculateTarget(chkParallel.Checked, chkRevProc.Checked); + ImgData.calculateTarget(); } } @@ -738,7 +743,7 @@ namespace ThermalImageStreamerDemo { try { - lblStats.Text = $"Camera: {msLastCam}ms | Persp {ImgData.lastStatTime("ImageTransf")}ms | Color {ImgData.lastStatTime("ImageColor")}ms | Points {ImgData.lastStatTime("AddPoints")}ms | Measures {ImgData.lastStatTime("GetAllTemperatures")}ms"; + lblStats.Text = $"Camera: {ImgData.lastStatTime("ImageAcquisition")}ms | Persp {ImgData.lastStatTime("ImageTransf")}ms | Color {ImgData.lastStatTime("ImageColor")}ms | Points {ImgData.lastStatTime("AddPoints")}ms | Measures {ImgData.lastStatTime("GetAllTemperatures")}ms"; } catch { } @@ -754,27 +759,6 @@ namespace ThermalImageStreamerDemo // mostro temp da FLIR lblReadTemp.Text = $"{ImgData.lastReadTemp:N2} °C"; - //calcolo da immagine B/N - lblTempRGB.Text = $"{ImgData.lastCalcTemp:N2} °C"; - // cambio colore se > 1 grado... - double delta = Math.Abs(ImgData.lastReadTemp - ImgData.lastCalcTemp); - if (delta < 1) - { - lblTempRGB.ForeColor = Color.Black; - } - else if (delta < 2) - { - lblTempRGB.ForeColor = Color.Blue; - } - else if (delta < 3) - { - lblTempRGB.ForeColor = Color.Orange; - } - else - { - lblTempRGB.ForeColor = Color.Red; - } - try { // mostro minimo / massimo @@ -800,7 +784,7 @@ namespace ThermalImageStreamerDemo //discoveryDialog.WindowState = FormWindowState.Minimized; if (discoveryDialog.ShowDialog() == DialogResult.OK) { - ConnectCamera(discoveryDialog.SelectedCameraDevice); + ImgData.ConnectCamera(discoveryDialog.SelectedCameraDevice); } } } diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index e28cea2d..b4cf98a7 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -1,4 +1,6 @@ using Flir.Atlas.Image; +using Flir.Atlas.Live.Device; +using Flir.Atlas.Live.Discovery; using Newtonsoft.Json; using System; using System.Collections.Generic; @@ -65,11 +67,6 @@ namespace ThermoCamUtils /// public ExecTime ExTime = new ExecTime(); - /// - /// Ultima temp calcolata da immagine B/N - /// - public double lastCalcTemp = 0; - /// /// Ultimo punto acquisito /// @@ -104,6 +101,22 @@ namespace ThermoCamUtils #endregion Public Constructors + #region Public Events + + public event EventHandler eh_CameraConnected; + + public event EventHandler eh_CameraConnStatusChanged; + + public event EventHandler eh_CameraDisposed; + + #endregion Public Events + + #region Private Properties + + private bool IsDirty { get; set; } + + #endregion Private Properties + #region Protected Properties protected Point[] _reticolo { get; set; } @@ -146,6 +159,14 @@ namespace ThermoCamUtils #region Private Methods + private void Camera_ConnectionStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) + { + if (eh_CameraConnStatusChanged != null) + { + eh_CameraConnStatusChanged(this, e); + } + } + private void checkLocadOutDir() { // verifico esistenza directory @@ -197,6 +218,11 @@ namespace ThermoCamUtils { } } + private void Image_Changed(object sender, Flir.Atlas.Image.ImageChangedEventArgs e) + { + IsDirty = true; + } + #endregion Private Methods #region Protected Methods @@ -267,49 +293,27 @@ namespace ThermoCamUtils /// /// Effettua calcolo immagini target /// - /// Indica se processare bitmap in memoria (true) o con metodi standard (false) - /// Indica se prima fare falsi colori poi trasformazione proiettiva - public void calculateTarget(bool fastBitmap, bool colorizeFirst) + public void calculateTarget() { if (Thermal != null) { try { -#if false - //lastTempRange = new Range(lastThermalImage.GetValueFromSignal(lastThermalImage.MinSignalValue), lastThermalImage.GetValueFromSignal(lastThermalImage.MaxSignalValue)); - lastTempRange = new Range(Thermal.Scale.Range.Minimum, Thermal.Scale.Range.Maximum); -#endif - + // genero immagine BN sw.Restart(); var pTransf = new PerspectiveTransform(currConf.OrigPoints.Coords, currConf.DestPoints.Coords); - var rTrasf = new ReColorize(currConf.TargetRange.Min, currConf.TargetRange.Max); -#if false - var rTrasf = new ReColorize(lastTempRange.Minimum, lastTempRange.Maximum, currConf.TargetRange.Min, currConf.TargetRange.Max); -#endif var transfImg = pTransf.convertImage(Origin, currConf.TargetSize.X, currConf.TargetSize.Y); GrayTransf = transfImg; sw.Stop(); ExTime.recordData("ImageTransf", sw.ElapsedMilliseconds); sw.Restart(); - if (colorizeFirst) - { - // ora calcolo ricolorazione da immagine originale - var colImg = rTrasf.process(Origin, lastFlirData.Values); -#if false - var colImg = rTrasf.process(Origin, fastBitmap); -#endif - // e faccio la stessa trasformazione di riscalatura - var transfColImg = pTransf.convertImage(colImg, currConf.TargetSize.X, currConf.TargetSize.Y); - ColorTransf = transfColImg; - } -#if false - else - { - // old way da immagine BN full size - ColorTransf = rTrasf.process(GrayTransf, fastBitmap); - } -#endif + var rTrasf = new ReColorize(currConf.TargetRange.Min, currConf.TargetRange.Max); + // ora calcolo ricolorazione da immagine originale + var colImg = rTrasf.process(Origin, lastFlirData.Values); + // e faccio la stessa trasformazione di riscalatura + var transfColImg = pTransf.convertImage(colImg, currConf.TargetSize.X, currConf.TargetSize.Y); + ColorTransf = transfColImg; sw.Stop(); ExTime.recordData("ImageColor", sw.ElapsedMilliseconds); } @@ -319,10 +323,70 @@ namespace ThermoCamUtils } } + public void ConnectCamera(CameraDeviceInfo cameraDeviceInfo) + { + DisposeCamera(); + switch (cameraDeviceInfo.SelectedStreamingFormat) + { + case ImageFormat.FlirFileFormat: + IRCam.ThermoCamera = new ThermalCamera(); + break; + + case ImageFormat.Argb: + IRCam.ThermoCamera = new VideoOverlayCamera(); + break; + + default: + throw new ArgumentOutOfRangeException(); + } + IRCam.ThermoCamera.ConnectionStatusChanged += Camera_ConnectionStatusChanged; + IRCam.ThermoCamera.GetImage().Changed += Image_Changed; + IRCam.ThermoCamera.Connect(cameraDeviceInfo); +#if false + if (IRCam.ThermoCamera.Recorder == null && _recorder != null) + { + _recorder.Dispose(); + _recorder = null; + } + if (_recorder != null) + { + if (!_recorder.IsDisposed) + _recorder.Initialize(IRCam.ThermoCamera); + } + recorderToolStripMenuItem.Enabled = IRCam.ThermoCamera.Recorder != null; +#endif + if (eh_CameraConnected != null) + { + eh_CameraConnected(this, new EventArgs()); + } + } + + public void DisconnectCamera() + { + if (IRCam.ThermoCamera == null) return; + + IRCam.ThermoCamera.Disconnect(); + } + + public void DisposeCamera() + { + if (eh_CameraDisposed != null) + { + eh_CameraDisposed(this, new EventArgs()); + } + if (IRCam.ThermoCamera == null) return; + + IRCam.ThermoCamera.ConnectionStatusChanged -= Camera_ConnectionStatusChanged; + IRCam.ThermoCamera.GetImage().Changed -= Image_Changed; + IRCam.ThermoCamera.Dispose(); + } + public void drawCrossAtPoints() { if (Thermal != null) { + // ricopio immagine "Pulita" + initImageFromFile(); sw.Restart(); // se ho dei punti x trasformazione --> disegno if (currConf.OrigPoints.curr > 0) @@ -375,7 +439,7 @@ namespace ThermoCamUtils // carico oggetto FLIR using (var flirImg = new ThermalImageFile(fileOrigiPath)) { - //ImgData.Thermal = new ThermalImageFile(filePath); + //Thermal = new ThermalImageFile(filePath); Thermal = (ThermalImage)flirImg; Thermal.TemperatureUnit = TemperatureUnit.Celsius; Thermal.Scale.IsAutoAdjustEnabled = true; @@ -388,11 +452,6 @@ namespace ThermoCamUtils Decorated = (Bitmap)loadedImg.Clone(); } - using (Image loadedImg = Image.FromFile(fileColorPath)) - { - ColorTransf = (Bitmap)loadedImg.Clone(); - } - // carico il file delle temperature string rawData = File.ReadAllText(fileDataPath); if (!string.IsNullOrEmpty(rawData)) @@ -480,13 +539,11 @@ namespace ThermoCamUtils foreach (var item in currConf.MeasPoints) { // recupero da ARRAY in memoria delle ultime letture fatte... - lastCalcTemp = lastFlirData.Values[item.Coords.X + Thermal.Size.Width * item.Coords.Y]; - - // recupero temp da FLIR - lastReadTemp = Thermal.GetValueAt(item.Coords).Value; + lastReadTemp = lastFlirData.Values[item.Coords.X + Thermal.Size.Width * item.Coords.Y]; + //lastReadTemp = Thermal.GetValueAt(item.Coords).Value; } sw.Stop(); - ExTime.recordData("GetTemperatures", sw.ElapsedMilliseconds); + ExTime.recordData("GetPoints", sw.ElapsedMilliseconds); } catch (Exception exc) { } @@ -583,6 +640,51 @@ namespace ThermoCamUtils currConf.MeasPoints.Add(newPoint); } + /// + /// recupera immagine effettuando eventuale salvataggio + /// + /// + public string takePicture(bool doSave) + { + string answ = ""; + sw.Restart(); + if (!IsDirty) return answ; + IsDirty = false; + if (IRCam.ThermoCamera == null) return answ; + + IRCam.ThermoCamera.GetImage().EnterLock(); + try + { + Thermal = (ThermalImage)IRCam.ThermoCamera.GetImage(); + Thermal.TemperatureUnit = TemperatureUnit.Celsius; + Thermal.Scale.IsAutoAdjustEnabled = true; + lastTempRange = new Range(Thermal.Scale.Range.Minimum, Thermal.Scale.Range.Maximum); + // salvo img locale + Origin = Thermal.Image; + Decorated = Thermal.Image; + // recupero le temperature... + readAllTemperatures(); + //verifico se devo salvare... + if (doSave) + { + answ = fileSave(); + } + } + catch (Exception exception) + { + Trace.TraceError(exception.Message); + } + finally + { + IRCam.ThermoCamera.GetImage().ExitLock(); + } + + sw.Stop(); + ExTime.recordData("ImageAcquisition", sw.ElapsedMilliseconds); + + return answ; + } + #endregion Public Methods } } \ No newline at end of file diff --git a/ThermoCamUtils/ReColorize.cs b/ThermoCamUtils/ReColorize.cs index b5bd7d1c..0b28f64c 100644 --- a/ThermoCamUtils/ReColorize.cs +++ b/ThermoCamUtils/ReColorize.cs @@ -209,7 +209,7 @@ namespace ThermoCamUtils #if true currVal = pixels[currentLine + x + 2]; #endif - var newCol = Rescale(ref tempVal[x + original.Width * y]); + var newCol = Rescale(ref tempVal[x / bytesPerPixel + original.Width * y]); pixels[currentLine + x] = (byte)newCol.B; pixels[currentLine + x + 1] = (byte)newCol.G; pixels[currentLine + x + 2] = (byte)newCol.R; From dc8f2d6b8d125e53ca421230e257376a1ae01bf2 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 18:23:38 +0100 Subject: [PATCH 07/15] pulizia metodi commentati --- ThermalImageStreamerDemo/MainForm.Designer.cs | 11 -- ThermalImageStreamerDemo/MainForm.cs | 121 +----------------- ThermoCamUtils/ImageData.cs | 14 +- ThermoCamUtils/ReColorize.cs | 84 ------------ 4 files changed, 2 insertions(+), 228 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.Designer.cs b/ThermalImageStreamerDemo/MainForm.Designer.cs index ac334c4f..3b95093c 100644 --- a/ThermalImageStreamerDemo/MainForm.Designer.cs +++ b/ThermalImageStreamerDemo/MainForm.Designer.cs @@ -34,7 +34,6 @@ this.disconnectToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cameraToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.recorderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripConnectionStatus = new System.Windows.Forms.ToolStripStatusLabel(); this.progBar = new System.Windows.Forms.ToolStripProgressBar(); @@ -129,20 +128,11 @@ // // cameraToolStripMenuItem // - this.cameraToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.recorderToolStripMenuItem}); this.cameraToolStripMenuItem.Enabled = false; this.cameraToolStripMenuItem.Name = "cameraToolStripMenuItem"; this.cameraToolStripMenuItem.Size = new System.Drawing.Size(60, 20); this.cameraToolStripMenuItem.Text = "Camera"; // - // recorderToolStripMenuItem - // - this.recorderToolStripMenuItem.Name = "recorderToolStripMenuItem"; - this.recorderToolStripMenuItem.Size = new System.Drawing.Size(130, 22); - this.recorderToolStripMenuItem.Text = "Recorder..."; - this.recorderToolStripMenuItem.Click += new System.EventHandler(this.recorderToolStripMenuItem_Click); - // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { @@ -598,7 +588,6 @@ private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem discoveryToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem cameraToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem recorderToolStripMenuItem; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripStatusLabel toolStripConnectionStatus; private System.Windows.Forms.ToolStripMenuItem disconnectToolStripMenuItem; diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 2fa55e1f..e263c28a 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -24,20 +24,12 @@ namespace ThermalImageStreamerDemo #endregion Private Fields -#if false - private RecorderForm _recorder; -#endif - #region Protected Fields protected const string colorPath = "images\\Color"; protected const string confFileName = "ThermoConf.json"; -#if false - protected const string currImgFile = "ThermalData.jpg"; -#endif - protected const string thermPath = "images\\Therm"; protected int currPoint = -1; @@ -347,9 +339,6 @@ namespace ThermalImageStreamerDemo private void ImgData_eh_CameraConnected(object sender, EventArgs e) { -#if false - _timerRefreshUi.Start(); -#endif _timerRefreshUi.Interval = 100; } @@ -364,53 +353,9 @@ namespace ThermalImageStreamerDemo private void ImgData_eh_CameraDisposed(object sender, EventArgs e) { -#if false - _timerRefreshUi.Stop(); -#endif _timerRefreshUi.Interval = 500; } -#if false - private void Camera_ConnectionStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) - { - BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); - BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); - // se si disconnette --> NUOVA richiesta connessione alla CHILD... - - // TODO FARE!!! - } -#endif -#if false - private void DisconnectCamera() - { - if (IRCam.ThermoCamera == null) return; - - IRCam.ThermoCamera.Disconnect(); - } -#endif -#if false - private void DisposeCamera() - { - _timerRefreshUi.Stop(); - if (IRCam.ThermoCamera == null) return; - if (_recorder != null) - { - _recorder.UnInitialize(); - _recorder.Dispose(); - } - IRCam.ThermoCamera.ConnectionStatusChanged -= Camera_ConnectionStatusChanged; - IRCam.ThermoCamera.GetImage().Changed -= Image_Changed; - IRCam.ThermoCamera.Dispose(); - } -#endif - -#if false - private void Image_Changed(object sender, Flir.Atlas.Image.ImageChangedEventArgs e) - { - IsDirty = true; - } -#endif - private void lblOrigA_Click(object sender, EventArgs e) { lblOrigA.ForeColor = toggleEditPoint(0); @@ -433,13 +378,7 @@ namespace ThermalImageStreamerDemo private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { -#if false - if (_recorder != null && _recorder.IsDisposed == false) - { - _recorder.Dispose(); - } -#endif - + _timerRefreshUi.Stop(); ImgData.DisposeCamera(); } @@ -534,20 +473,6 @@ namespace ThermalImageStreamerDemo ImgData.calculateTarget(); } - private void recorderToolStripMenuItem_Click(object sender, EventArgs e) - { -#if false - if (_recorder == null || _recorder.IsDisposed) - { - _recorder = new RecorderForm(); - _recorder.Initialize(IRCam.ThermoCamera); - _recorder.SelectedFileMouseDoubleClick += _recorder_SelectedFileMouseDoubleClick; - } - _recorder.Show(); - _recorder.Focus(); -#endif - } - private void refreshDisplay() { ImgData.drawCrossAtPoints(); @@ -584,50 +509,6 @@ namespace ThermalImageStreamerDemo currConf.TargetRange.Max = maxRangeTemp; } -#if false - /// - /// recupera immagine effettuando eventuale salvataggio - /// - /// - private void takePicture(bool doSave) - { - sw.Restart(); - if (!IsDirty) return; - IsDirty = false; - if (IRCam.ThermoCamera == null) return; - - IRCam.ThermoCamera.GetImage().EnterLock(); - try - { - ImgData.Thermal = (ThermalImage)IRCam.ThermoCamera.GetImage(); - ImgData.Thermal.TemperatureUnit = TemperatureUnit.Celsius; - ImgData.Thermal.Scale.IsAutoAdjustEnabled = true; - ImgData.lastTempRange = new Range(ImgData.Thermal.Scale.Range.Minimum, ImgData.Thermal.Scale.Range.Maximum); - // salvo img locale - ImgData.Origin = ImgData.Thermal.Image; - ImgData.Decorated = ImgData.Thermal.Image; - // recupero le temperature... - ImgData.readAllTemperatures(); - //verifico se devo salvare... - if (doSave) - { - ImgData.fileSave(); - } - } - catch (Exception exception) - { - Trace.TraceError(exception.Message); - } - finally - { - IRCam.ThermoCamera.GetImage().ExitLock(); - } - - sw.Stop(); - msLastCam = sw.ElapsedMilliseconds; - } -#endif - /// /// Verifica se il punto era in edit, altrimenti segnala e lo attiva... restituendo colore x il controllo /// diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index b4cf98a7..ae85c396 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -342,19 +342,7 @@ namespace ThermoCamUtils IRCam.ThermoCamera.ConnectionStatusChanged += Camera_ConnectionStatusChanged; IRCam.ThermoCamera.GetImage().Changed += Image_Changed; IRCam.ThermoCamera.Connect(cameraDeviceInfo); -#if false - if (IRCam.ThermoCamera.Recorder == null && _recorder != null) - { - _recorder.Dispose(); - _recorder = null; - } - if (_recorder != null) - { - if (!_recorder.IsDisposed) - _recorder.Initialize(IRCam.ThermoCamera); - } - recorderToolStripMenuItem.Enabled = IRCam.ThermoCamera.Recorder != null; -#endif + if (eh_CameraConnected != null) { eh_CameraConnected(this, new EventArgs()); diff --git a/ThermoCamUtils/ReColorize.cs b/ThermoCamUtils/ReColorize.cs index 0b28f64c..9474a7a3 100644 --- a/ThermoCamUtils/ReColorize.cs +++ b/ThermoCamUtils/ReColorize.cs @@ -18,12 +18,6 @@ namespace ThermoCamUtils #endregion Protected Fields -#if false - protected double delta = 0; - protected double maxVal = 5000; - protected double minVal = -999; -#endif - #region Public Constructors //public ReColorize(double minValue, double maxValue, double minScale, double maxScale) @@ -31,11 +25,6 @@ namespace ThermoCamUtils { minSca = minScale; maxSca = maxScale; -#if false - minVal = minValue; - maxVal = maxValue; - delta = minVal - minSca; -#endif } #endregion Public Constructors @@ -105,72 +94,6 @@ namespace ThermoCamUtils #endregion Protected Methods -#if false - /// - /// Calcola colore su scala dato rapporto valore B/N su min/max - /// - /// - /// - protected Color Rescale(ref int ValRGB) - { - int R = 0; - int G = 0; - int B = 0; - int ValScal = 0; - - // calcolo retta interpolazione per il valore in gradi...Y = M * X + DELTA - double M = (maxVal - minVal) / 255; - double currTemp = M * ValRGB + delta; - // ora calcolo valore scalare - ValScal = (int)(255 * (currTemp - minSca) / (maxSca - minSca)); - - if (ValScal < 0) - { - R = 0; - G = 0; - B = 0; - } - else if (ValScal <= 51) - { - R = 0; - G = 0; - B = (int)(ValScal * 5); - } - else if (ValScal <= 102) - { - R = (int)((ValScal - 51) * 5); - G = 0; - B = 255; - } - else if (ValScal <= 153) - { - R = 255; - G = 0; - B = (int)(255 - ((ValScal - 102) * 5)); - } - else if (ValScal <= 204) - { - R = 255; - G = (int)((ValScal - 153) * 5); - B = 0; - } - else if (ValScal <= 255) - { - R = 255; - G = 255; - B = (int)((ValScal - 204) * 5); - } - else - { - R = 255; - G = 255; - B = 255; - } - - return Color.FromArgb(R, G, B); - } -#endif - #region Public Methods /// @@ -187,10 +110,6 @@ namespace ThermoCamUtils -----------------------------------------------*/ Bitmap imgColor = original.Clone(new Rectangle(0, 0, original.Width, original.Height), original.PixelFormat); -#if true - int currVal = 0; -#endif - BitmapData bitmapData = imgColor.LockBits(new Rectangle(0, 0, imgColor.Width, imgColor.Height), ImageLockMode.ReadWrite, imgColor.PixelFormat); int bytesPerPixel = Bitmap.GetPixelFormatSize(imgColor.PixelFormat) / 8; @@ -206,9 +125,6 @@ namespace ThermoCamUtils int currentLine = y * bitmapData.Stride; for (int x = 0; x < widthInBytes; x = x + bytesPerPixel) { -#if true - currVal = pixels[currentLine + x + 2]; -#endif var newCol = Rescale(ref tempVal[x / bytesPerPixel + original.Width * y]); pixels[currentLine + x] = (byte)newCol.B; pixels[currentLine + x + 1] = (byte)newCol.G; From b69927bc703a41c9dcce680674e47cb8bc66e5c0 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 18:49:47 +0100 Subject: [PATCH 08/15] ancora spostamento metodi init in libreria --- ThermalImageStreamerDemo/MainForm.Designer.cs | 10 +- ThermalImageStreamerDemo/MainForm.cs | 125 +++++++----------- ThermoCamUtils/ImageData.cs | 52 +++++++- ThermoCamUtils/ThermoCamConf.cs | 5 + 4 files changed, 107 insertions(+), 85 deletions(-) diff --git a/ThermalImageStreamerDemo/MainForm.Designer.cs b/ThermalImageStreamerDemo/MainForm.Designer.cs index 3b95093c..1a3ac970 100644 --- a/ThermalImageStreamerDemo/MainForm.Designer.cs +++ b/ThermalImageStreamerDemo/MainForm.Designer.cs @@ -220,7 +220,7 @@ this.groupBox3.Controls.Add(this.txtMinScale); this.groupBox3.Controls.Add(this.chkReadTemp); this.groupBox3.Controls.Add(this.lblReadTemp); - this.groupBox3.Location = new System.Drawing.Point(8, 333); + this.groupBox3.Location = new System.Drawing.Point(8, 269); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(175, 119); this.groupBox3.TabIndex = 5; @@ -316,12 +316,12 @@ this.groupBox2.Controls.Add(this.txtBC); this.groupBox2.Controls.Add(this.label1); this.groupBox2.Controls.Add(this.txtAB); - this.groupBox2.Location = new System.Drawing.Point(8, 214); + this.groupBox2.Location = new System.Drawing.Point(8, 187); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(175, 76); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; - this.groupBox2.Text = "target"; + this.groupBox2.Text = "Target"; // // label5 // @@ -369,12 +369,12 @@ this.groupBox1.Controls.Add(this.lblOrigC); this.groupBox1.Controls.Add(this.lblOrigB); this.groupBox1.Controls.Add(this.chkPointSetup); - this.groupBox1.Location = new System.Drawing.Point(8, 122); + this.groupBox1.Location = new System.Drawing.Point(8, 91); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(175, 90); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; - this.groupBox1.Text = "origin"; + this.groupBox1.Text = "Origin"; // // btnReset // diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index e263c28a..253b5e55 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -24,13 +24,15 @@ namespace ThermalImageStreamerDemo #endregion Private Fields - #region Protected Fields - +#if false protected const string colorPath = "images\\Color"; protected const string confFileName = "ThermoConf.json"; protected const string thermPath = "images\\Therm"; +#endif + + #region Protected Fields protected int currPoint = -1; @@ -39,16 +41,12 @@ namespace ThermalImageStreamerDemo /// protected ImageData ImgData = new ImageData(); - protected Stopwatch sw = new Stopwatch(); - #endregion Protected Fields - #region Public Fields - +#if false // Config File Names public static readonly string BASE_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); - - #endregion Public Fields +#endif #region Public Constructors @@ -63,7 +61,7 @@ namespace ThermalImageStreamerDemo ImgData.eh_CameraDisposed += ImgData_eh_CameraDisposed; ImgData.eh_CameraConnStatusChanged += ImgData_eh_CameraConnStatusChanged; // cerco se ho un set di parametri già impostati... - tryReloadConf(); + ImgData.tryReloadConf(); // sistemo le conf temp setRangeTemp(); // calcolo i currConf.destPoints @@ -88,8 +86,7 @@ namespace ThermalImageStreamerDemo #endregion Private Properties - #region Protected Properties - +#if false protected string confPath { get @@ -103,18 +100,9 @@ namespace ThermalImageStreamerDemo return answ; } } +#endif - protected ThermoCamConf currConf - { - get - { - return ImgData.currConf; - } - set - { - ImgData.currConf = value; - } - } + #region Protected Properties protected int dimX { @@ -122,12 +110,12 @@ namespace ThermalImageStreamerDemo { int answ = 100; int.TryParse(txtAB.Text, out answ); - currConf.TargetSize.X = answ; + ImgData.currConf.TargetSize.X = answ; return answ; } set { - currConf.TargetSize.X = value; + ImgData.currConf.TargetSize.X = value; txtAB.Text = $"{value}"; } } @@ -138,12 +126,12 @@ namespace ThermalImageStreamerDemo { int answ = 100; int.TryParse(txtBC.Text, out answ); - currConf.TargetSize.Y = answ; + ImgData.currConf.TargetSize.Y = answ; return answ; } set { - currConf.TargetSize.Y = value; + ImgData.currConf.TargetSize.Y = value; txtBC.Text = $"{value}"; } } @@ -228,12 +216,6 @@ namespace ThermalImageStreamerDemo #region Private Methods - private void _recorder_SelectedFileMouseDoubleClick(object sender, SelectedFileEventArgs e) - { - var playback = new PlaybackForm(e.FilePath); - playback.Show(); - } - private void _timerRefreshUi_Tick(object sender, EventArgs e) { // se è in live view --> continuo @@ -264,7 +246,7 @@ namespace ThermalImageStreamerDemo private void btnReset_Click(object sender, EventArgs e) { pointSetup = true; - currConf.OrigPoints = new SetPoints(); + ImgData.currConf.OrigPoints = new SetPoints(); } private void btnSave_Click(object sender, EventArgs e) @@ -319,8 +301,9 @@ namespace ThermalImageStreamerDemo { ImgData.ConnectCamera(discoveryDlg.SelectedCameraDevice); // salvo nome camera in conf attuale! - currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; - saveConf(); + ImgData.currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; + ImgData.currConf.CameraAddress = discoveryDlg.SelectedCameraDevice.IpSettings.IpAddress; ; + ImgData.saveConf(); } } @@ -389,7 +372,7 @@ namespace ThermalImageStreamerDemo private void MainForm_Shown(object sender, EventArgs e) { // avvio l'autoconnessione - if (!string.IsNullOrEmpty(currConf.CameraName)) + if (!string.IsNullOrEmpty(ImgData.currConf.CameraName)) { discoveryCamera(); } @@ -427,15 +410,15 @@ namespace ThermalImageStreamerDemo if (pointSetup) { // max 4 punti... se sono già FULL --> imposto singolo valore nuovo - if (currConf.OrigPoints.curr >= 4) + if (ImgData.currConf.OrigPoints.curr >= 4) { if (currPoint >= 0) { - currConf.OrigPoints.Coords[currPoint] = ImgData.lastPoint; + ImgData.currConf.OrigPoints.Coords[currPoint] = ImgData.lastPoint; } else { - currConf.OrigPoints = new SetPoints(); + ImgData.currConf.OrigPoints = new SetPoints(); } } else @@ -443,14 +426,14 @@ namespace ThermalImageStreamerDemo // salvo coordinate in base al num corrente... try { - currConf.OrigPoints.Coords.Add(ImgData.lastPoint); - currConf.OrigPoints.curr++; + ImgData.currConf.OrigPoints.Coords.Add(ImgData.lastPoint); + ImgData.currConf.OrigPoints.curr++; } catch { } } // salvo conf - saveConf(); + ImgData.saveConf(); // aggiorno visualizzazione processImage(); @@ -482,31 +465,13 @@ namespace ThermalImageStreamerDemo updateStatDisplay(); } - /// - /// Salva su file il file di conf corrente - /// - /// - private bool saveConf() - { - bool answ = false; - try - { - string rawData = JsonConvert.SerializeObject(currConf, Formatting.Indented); - File.WriteAllText(confPath, rawData); - answ = true; - } - catch - { } - return answ; - } - /// /// Sistema le temp range min/Max /// private void setRangeTemp() { - currConf.TargetRange.Min = minRangeTemp; - currConf.TargetRange.Max = maxRangeTemp; + ImgData.currConf.TargetRange.Min = minRangeTemp; + ImgData.currConf.TargetRange.Max = maxRangeTemp; } /// @@ -536,6 +501,7 @@ namespace ThermalImageStreamerDemo return answ; } +#if false private void tryReloadConf() { if (File.Exists(confPath)) @@ -546,13 +512,14 @@ namespace ThermalImageStreamerDemo { try { - currConf = JsonConvert.DeserializeObject(rawData); + ImgData.currConf = JsonConvert.DeserializeObject(rawData); } catch (Exception exc) { } } } } +#endif private void txtAB_TextChanged(object sender, EventArgs e) { @@ -582,14 +549,14 @@ namespace ThermalImageStreamerDemo private void updateDestPt() { - currConf.DestPoints.Coords = new List(); + ImgData.currConf.DestPoints.Coords = new List(); // ciclo i punti A-B-C-D... - currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = 0 }); - currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); - currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); - currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = dimY }); + ImgData.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = 0 }); + ImgData.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); + ImgData.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); + ImgData.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = dimY }); // salvo conf - saveConf(); + ImgData.saveConf(); } private void updateDisplay() @@ -599,21 +566,21 @@ namespace ThermalImageStreamerDemo lblOrigC.Text = "C"; lblOrigD.Text = "D"; // popolo - if (currConf.OrigPoints.Coords.Count > 0) + if (ImgData.currConf.OrigPoints.Coords.Count > 0) { - lblOrigA.Text = $"A: ({currConf.OrigPoints.Coords[0].X},{currConf.OrigPoints.Coords[0].Y})"; + lblOrigA.Text = $"A: ({ImgData.currConf.OrigPoints.Coords[0].X},{ImgData.currConf.OrigPoints.Coords[0].Y})"; } - if (currConf.OrigPoints.Coords.Count > 1) + if (ImgData.currConf.OrigPoints.Coords.Count > 1) { - lblOrigB.Text = $"B: ({currConf.OrigPoints.Coords[1].X},{currConf.OrigPoints.Coords[1].Y})"; + lblOrigB.Text = $"B: ({ImgData.currConf.OrigPoints.Coords[1].X},{ImgData.currConf.OrigPoints.Coords[1].Y})"; } - if (currConf.OrigPoints.Coords.Count > 2) + if (ImgData.currConf.OrigPoints.Coords.Count > 2) { - lblOrigC.Text = $"C: ({currConf.OrigPoints.Coords[2].X},{currConf.OrigPoints.Coords[2].Y})"; + lblOrigC.Text = $"C: ({ImgData.currConf.OrigPoints.Coords[2].X},{ImgData.currConf.OrigPoints.Coords[2].Y})"; } - if (currConf.OrigPoints.Coords.Count > 3) + if (ImgData.currConf.OrigPoints.Coords.Count > 3) { - lblOrigD.Text = $"D: ({currConf.OrigPoints.Coords[3].X},{currConf.OrigPoints.Coords[3].Y})"; + lblOrigD.Text = $"D: ({ImgData.currConf.OrigPoints.Coords[3].X},{ImgData.currConf.OrigPoints.Coords[3].Y})"; ImgData.calculateTarget(); } } @@ -659,8 +626,8 @@ namespace ThermalImageStreamerDemo public void discoveryCamera() { var discoveryDialog = new DiscoveryForm(); - discoveryDialog.CameraName = currConf.CameraName; - if (!string.IsNullOrEmpty(currConf.CameraName)) + discoveryDialog.CameraName = ImgData.currConf.CameraName; + if (!string.IsNullOrEmpty(ImgData.currConf.CameraName)) { //discoveryDialog.WindowState = FormWindowState.Minimized; if (discoveryDialog.ShowDialog() == DialogResult.OK) diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/ImageData.cs index ae85c396..4464e9aa 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/ImageData.cs @@ -24,11 +24,11 @@ namespace ThermoCamUtils #region Protected Fields protected const string colorPath = "images\\colored"; + protected const string confFileName = "ThermoConf.json"; protected const string currName = "_last"; protected const string dataFormat = "dat"; protected const string dataPath = "images\\data"; protected const string imgFormat = "jpg"; - protected const string thermPath = "images\\original"; protected const string transPath = "images\\transformed"; @@ -121,6 +121,20 @@ namespace ThermoCamUtils protected Point[] _reticolo { get; set; } + protected string confPath + { + get + { + // se esiste il file... path assoluto + string answ = confFileName; + if (!Path.IsPathRooted(answ)) + { + answ = BASE_PATH + "\\" + confFileName; + } + return answ; + } + } + #endregion Protected Properties #region Public Properties @@ -608,6 +622,24 @@ namespace ThermoCamUtils ExTime.recordData("GetAllTemperatures", sw.ElapsedMilliseconds); } + /// + /// Salva su file il file di conf corrente + /// + /// + public bool saveConf() + { + bool answ = false; + try + { + string rawData = JsonConvert.SerializeObject(currConf, Formatting.Indented); + File.WriteAllText(confPath, rawData); + answ = true; + } + catch + { } + return answ; + } + /// /// Salvo il punto di misura selezionato /// @@ -673,6 +705,24 @@ namespace ThermoCamUtils return answ; } + public void tryReloadConf() + { + if (File.Exists(confPath)) + { + // se non è vuoto.... + string rawData = File.ReadAllText(confPath); + if (!string.IsNullOrEmpty(rawData)) + { + try + { + currConf = JsonConvert.DeserializeObject(rawData); + } + catch (Exception exc) + { } + } + } + } + #endregion Public Methods } } \ No newline at end of file diff --git a/ThermoCamUtils/ThermoCamConf.cs b/ThermoCamUtils/ThermoCamConf.cs index b73b6d3d..b6b16945 100644 --- a/ThermoCamUtils/ThermoCamConf.cs +++ b/ThermoCamUtils/ThermoCamConf.cs @@ -56,6 +56,11 @@ namespace ThermoCamUtils #region Public Properties + /// + /// IP Address Camera selezionata x autoconnect ("" = nessun autoconnect) + /// + public string CameraAddress { get; set; } = ""; + /// /// Camera selezionata x autoconnect ("" = nessun autoconnect) /// From fe518b2ce71603a149841aee88f03b0a83aabc98 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 19:04:31 +0100 Subject: [PATCH 09/15] refactor main class + pulizia codice --- ThermalImageStreamerDemo/MainForm.cs | 179 +++++++------------- ThermoCamUtils/{ImageData.cs => TCContr.cs} | 4 +- ThermoCamUtils/ThermoCamUtils.csproj | 2 +- 3 files changed, 68 insertions(+), 117 deletions(-) rename ThermoCamUtils/{ImageData.cs => TCContr.cs} (99%) diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 253b5e55..676c7a76 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -24,30 +24,17 @@ namespace ThermalImageStreamerDemo #endregion Private Fields -#if false - protected const string colorPath = "images\\Color"; - - protected const string confFileName = "ThermoConf.json"; - - protected const string thermPath = "images\\Therm"; -#endif - #region Protected Fields protected int currPoint = -1; /// - /// Contenitore oggetti Image x FlirCam + /// Classe gestione ThermoCam (oggetti Image, metodi processing...) x FlirCam /// - protected ImageData ImgData = new ImageData(); + protected TCContr ThermoCamCont = new TCContr(); #endregion Protected Fields -#if false - // Config File Names - public static readonly string BASE_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); -#endif - #region Public Constructors public MainForm() @@ -57,11 +44,11 @@ namespace ThermalImageStreamerDemo _timerRefreshUi.Tick += _timerRefreshUi_Tick; _timerRefreshUi.Start(); // collego eventi ImgData - ImgData.eh_CameraConnected += ImgData_eh_CameraConnected; - ImgData.eh_CameraDisposed += ImgData_eh_CameraDisposed; - ImgData.eh_CameraConnStatusChanged += ImgData_eh_CameraConnStatusChanged; + ThermoCamCont.eh_CameraConnected += ImgData_eh_CameraConnected; + ThermoCamCont.eh_CameraDisposed += ImgData_eh_CameraDisposed; + ThermoCamCont.eh_CameraConnStatusChanged += ImgData_eh_CameraConnStatusChanged; // cerco se ho un set di parametri già impostati... - ImgData.tryReloadConf(); + ThermoCamCont.tryReloadConf(); // sistemo le conf temp setRangeTemp(); // calcolo i currConf.destPoints @@ -86,22 +73,6 @@ namespace ThermalImageStreamerDemo #endregion Private Properties -#if false - protected string confPath - { - get - { - // se esiste il file... path assoluto - string answ = confFileName; - if (!Path.IsPathRooted(answ)) - { - answ = BASE_PATH + "\\" + confFileName; - } - return answ; - } - } -#endif - #region Protected Properties protected int dimX @@ -110,12 +81,12 @@ namespace ThermalImageStreamerDemo { int answ = 100; int.TryParse(txtAB.Text, out answ); - ImgData.currConf.TargetSize.X = answ; + ThermoCamCont.currConf.TargetSize.X = answ; return answ; } set { - ImgData.currConf.TargetSize.X = value; + ThermoCamCont.currConf.TargetSize.X = value; txtAB.Text = $"{value}"; } } @@ -126,12 +97,12 @@ namespace ThermalImageStreamerDemo { int answ = 100; int.TryParse(txtBC.Text, out answ); - ImgData.currConf.TargetSize.Y = answ; + ThermoCamCont.currConf.TargetSize.Y = answ; return answ; } set { - ImgData.currConf.TargetSize.Y = value; + ThermoCamCont.currConf.TargetSize.Y = value; txtBC.Text = $"{value}"; } } @@ -221,7 +192,7 @@ namespace ThermalImageStreamerDemo // se è in live view --> continuo if (liveView) { - ImgData.takePicture(saveEnabled); + ThermoCamCont.takePicture(saveEnabled); processImage(); refreshDisplay(); } @@ -236,7 +207,7 @@ namespace ThermalImageStreamerDemo private void btnLoad_Click(object sender, EventArgs e) { // "" --> carica ultima scattata (altrimenti nome) - ImgData.fileLoad(""); + ThermoCamCont.fileLoad(""); // aggiorno visualizzazione processImage(); @@ -246,12 +217,12 @@ namespace ThermalImageStreamerDemo private void btnReset_Click(object sender, EventArgs e) { pointSetup = true; - ImgData.currConf.OrigPoints = new SetPoints(); + ThermoCamCont.currConf.OrigPoints = new SetPoints(); } private void btnSave_Click(object sender, EventArgs e) { - ImgData.takePicture(true); + ThermoCamCont.takePicture(true); processImage(); refreshDisplay(); } @@ -291,7 +262,7 @@ namespace ThermalImageStreamerDemo private void disconnectToolStripMenuItem_Click(object sender, EventArgs e) { - ImgData.DisconnectCamera(); + ThermoCamCont.DisconnectCamera(); } private void discoveryToolStripMenuItem_Click(object sender, EventArgs e) @@ -299,24 +270,24 @@ namespace ThermalImageStreamerDemo var discoveryDlg = new DiscoveryForm(); if (discoveryDlg.ShowDialog() == DialogResult.OK) { - ImgData.ConnectCamera(discoveryDlg.SelectedCameraDevice); + ThermoCamCont.ConnectCamera(discoveryDlg.SelectedCameraDevice); // salvo nome camera in conf attuale! - ImgData.currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; - ImgData.currConf.CameraAddress = discoveryDlg.SelectedCameraDevice.IpSettings.IpAddress; ; - ImgData.saveConf(); + ThermoCamCont.currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; + ThermoCamCont.currConf.CameraAddress = discoveryDlg.SelectedCameraDevice.IpSettings.IpAddress; ; + ThermoCamCont.saveConf(); } } private void displayImages() { - if (ImgData.Thermal != null) + if (ThermoCamCont.Thermal != null) { lblImgA.Text = showOrigBig ? "ORIGINAL image" : "FINAL image"; lblImgB.Text = showOrigBig ? "FINAL image" : "ORIGINAL image"; - pBoxA.Image = showOrigBig ? ImgData.ColorTransf : ImgData.Decorated; - pBoxB.Image = showOrigBig ? ImgData.Decorated : ImgData.ColorTransf; - pBoxC.Image = ImgData.GrayTransf; + pBoxA.Image = showOrigBig ? ThermoCamCont.ColorTransf : ThermoCamCont.Decorated; + pBoxB.Image = showOrigBig ? ThermoCamCont.Decorated : ThermoCamCont.ColorTransf; + pBoxC.Image = ThermoCamCont.GrayTransf; } } @@ -362,7 +333,7 @@ namespace ThermalImageStreamerDemo private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { _timerRefreshUi.Stop(); - ImgData.DisposeCamera(); + ThermoCamCont.DisposeCamera(); } private void MainForm_Load(object sender, EventArgs e) @@ -372,7 +343,7 @@ namespace ThermalImageStreamerDemo private void MainForm_Shown(object sender, EventArgs e) { // avvio l'autoconnessione - if (!string.IsNullOrEmpty(ImgData.currConf.CameraName)) + if (!string.IsNullOrEmpty(ThermoCamCont.currConf.CameraName)) { discoveryCamera(); } @@ -396,29 +367,29 @@ namespace ThermalImageStreamerDemo double ratio = 1; try { - if (ImgData.Origin != null && ImgData.Origin.Width > 0) + if (ThermoCamCont.Origin != null && ThermoCamCont.Origin.Width > 0) { - ratio = (double)pBoxA.Width / ImgData.Origin.Width; + ratio = (double)pBoxA.Width / ThermoCamCont.Origin.Width; } } catch { } // trasformo punto in equivalente originale var mea = (MouseEventArgs)e; - ImgData.lastPoint = new Point() { X = (int)(mea.X / ratio), Y = (int)(mea.Y / ratio) }; - lblPoint.Text = $"({mea.X},{mea.Y}) --> ({ImgData.lastPoint.X},{ImgData.lastPoint.Y})"; + ThermoCamCont.lastPoint = new Point() { X = (int)(mea.X / ratio), Y = (int)(mea.Y / ratio) }; + lblPoint.Text = $"({mea.X},{mea.Y}) --> ({ThermoCamCont.lastPoint.X},{ThermoCamCont.lastPoint.Y})"; if (pointSetup) { // max 4 punti... se sono già FULL --> imposto singolo valore nuovo - if (ImgData.currConf.OrigPoints.curr >= 4) + if (ThermoCamCont.currConf.OrigPoints.curr >= 4) { if (currPoint >= 0) { - ImgData.currConf.OrigPoints.Coords[currPoint] = ImgData.lastPoint; + ThermoCamCont.currConf.OrigPoints.Coords[currPoint] = ThermoCamCont.lastPoint; } else { - ImgData.currConf.OrigPoints = new SetPoints(); + ThermoCamCont.currConf.OrigPoints = new SetPoints(); } } else @@ -426,14 +397,14 @@ namespace ThermalImageStreamerDemo // salvo coordinate in base al num corrente... try { - ImgData.currConf.OrigPoints.Coords.Add(ImgData.lastPoint); - ImgData.currConf.OrigPoints.curr++; + ThermoCamCont.currConf.OrigPoints.Coords.Add(ThermoCamCont.lastPoint); + ThermoCamCont.currConf.OrigPoints.curr++; } catch { } } // salvo conf - ImgData.saveConf(); + ThermoCamCont.saveConf(); // aggiorno visualizzazione processImage(); @@ -442,7 +413,7 @@ namespace ThermalImageStreamerDemo else if (readTemp) { // x ora fisso 1 solo valore... - ImgData.saveMeasurePoint(false); + ThermoCamCont.saveMeasurePoint(false); // aggiorno visualizzazione processImage(); refreshDisplay(); @@ -452,13 +423,13 @@ namespace ThermalImageStreamerDemo private void processImage() { // disegno immagine - ImgData.getTemperatures(readTemp); - ImgData.calculateTarget(); + ThermoCamCont.getTemperatures(readTemp); + ThermoCamCont.calculateTarget(); } private void refreshDisplay() { - ImgData.drawCrossAtPoints(); + ThermoCamCont.drawCrossAtPoints(); displayImages(); updateDisplay(); updateTempDisplay(); @@ -470,8 +441,8 @@ namespace ThermalImageStreamerDemo /// private void setRangeTemp() { - ImgData.currConf.TargetRange.Min = minRangeTemp; - ImgData.currConf.TargetRange.Max = maxRangeTemp; + ThermoCamCont.currConf.TargetRange.Min = minRangeTemp; + ThermoCamCont.currConf.TargetRange.Max = maxRangeTemp; } /// @@ -501,26 +472,6 @@ namespace ThermalImageStreamerDemo return answ; } -#if false - private void tryReloadConf() - { - if (File.Exists(confPath)) - { - // se non è vuoto.... - string rawData = File.ReadAllText(confPath); - if (!string.IsNullOrEmpty(rawData)) - { - try - { - ImgData.currConf = JsonConvert.DeserializeObject(rawData); - } - catch (Exception exc) - { } - } - } - } -#endif - private void txtAB_TextChanged(object sender, EventArgs e) { // ricalcolo in proporzione altro valore... @@ -549,14 +500,14 @@ namespace ThermalImageStreamerDemo private void updateDestPt() { - ImgData.currConf.DestPoints.Coords = new List(); + ThermoCamCont.currConf.DestPoints.Coords = new List(); // ciclo i punti A-B-C-D... - ImgData.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = 0 }); - ImgData.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); - ImgData.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); - ImgData.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = dimY }); + ThermoCamCont.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = 0 }); + ThermoCamCont.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = 0 }); + ThermoCamCont.currConf.DestPoints.Coords.Add(new Point() { X = dimX, Y = dimY }); + ThermoCamCont.currConf.DestPoints.Coords.Add(new Point() { X = 0, Y = dimY }); // salvo conf - ImgData.saveConf(); + ThermoCamCont.saveConf(); } private void updateDisplay() @@ -566,32 +517,32 @@ namespace ThermalImageStreamerDemo lblOrigC.Text = "C"; lblOrigD.Text = "D"; // popolo - if (ImgData.currConf.OrigPoints.Coords.Count > 0) + if (ThermoCamCont.currConf.OrigPoints.Coords.Count > 0) { - lblOrigA.Text = $"A: ({ImgData.currConf.OrigPoints.Coords[0].X},{ImgData.currConf.OrigPoints.Coords[0].Y})"; + lblOrigA.Text = $"A: ({ThermoCamCont.currConf.OrigPoints.Coords[0].X},{ThermoCamCont.currConf.OrigPoints.Coords[0].Y})"; } - if (ImgData.currConf.OrigPoints.Coords.Count > 1) + if (ThermoCamCont.currConf.OrigPoints.Coords.Count > 1) { - lblOrigB.Text = $"B: ({ImgData.currConf.OrigPoints.Coords[1].X},{ImgData.currConf.OrigPoints.Coords[1].Y})"; + lblOrigB.Text = $"B: ({ThermoCamCont.currConf.OrigPoints.Coords[1].X},{ThermoCamCont.currConf.OrigPoints.Coords[1].Y})"; } - if (ImgData.currConf.OrigPoints.Coords.Count > 2) + if (ThermoCamCont.currConf.OrigPoints.Coords.Count > 2) { - lblOrigC.Text = $"C: ({ImgData.currConf.OrigPoints.Coords[2].X},{ImgData.currConf.OrigPoints.Coords[2].Y})"; + lblOrigC.Text = $"C: ({ThermoCamCont.currConf.OrigPoints.Coords[2].X},{ThermoCamCont.currConf.OrigPoints.Coords[2].Y})"; } - if (ImgData.currConf.OrigPoints.Coords.Count > 3) + if (ThermoCamCont.currConf.OrigPoints.Coords.Count > 3) { - lblOrigD.Text = $"D: ({ImgData.currConf.OrigPoints.Coords[3].X},{ImgData.currConf.OrigPoints.Coords[3].Y})"; - ImgData.calculateTarget(); + lblOrigD.Text = $"D: ({ThermoCamCont.currConf.OrigPoints.Coords[3].X},{ThermoCamCont.currConf.OrigPoints.Coords[3].Y})"; + ThermoCamCont.calculateTarget(); } } private void updateStatDisplay() { - if (ImgData.ExTime.Stats.Count > 0) + if (ThermoCamCont.ExTime.Stats.Count > 0) { try { - lblStats.Text = $"Camera: {ImgData.lastStatTime("ImageAcquisition")}ms | Persp {ImgData.lastStatTime("ImageTransf")}ms | Color {ImgData.lastStatTime("ImageColor")}ms | Points {ImgData.lastStatTime("AddPoints")}ms | Measures {ImgData.lastStatTime("GetAllTemperatures")}ms"; + lblStats.Text = $"Camera: {ThermoCamCont.lastStatTime("ImageAcquisition")}ms | Persp {ThermoCamCont.lastStatTime("ImageTransf")}ms | Color {ThermoCamCont.lastStatTime("ImageColor")}ms | Points {ThermoCamCont.lastStatTime("AddPoints")}ms | Measures {ThermoCamCont.lastStatTime("GetAllTemperatures")}ms"; } catch { } @@ -600,18 +551,18 @@ namespace ThermalImageStreamerDemo private void updateTempDisplay() { - if (ImgData.Thermal != null) + if (ThermoCamCont.Thermal != null) { if (readTemp) { // mostro temp da FLIR - lblReadTemp.Text = $"{ImgData.lastReadTemp:N2} °C"; + lblReadTemp.Text = $"{ThermoCamCont.lastReadTemp:N2} °C"; try { // mostro minimo / massimo - lblMinTemp.Text = $"{ImgData.lastTempRange.Minimum:N2}"; - lblMaxTemp.Text = $"{ImgData.lastTempRange.Maximum:N2}"; + lblMinTemp.Text = $"{ThermoCamCont.lastTempRange.Minimum:N2}"; + lblMaxTemp.Text = $"{ThermoCamCont.lastTempRange.Maximum:N2}"; } catch { } @@ -626,13 +577,13 @@ namespace ThermalImageStreamerDemo public void discoveryCamera() { var discoveryDialog = new DiscoveryForm(); - discoveryDialog.CameraName = ImgData.currConf.CameraName; - if (!string.IsNullOrEmpty(ImgData.currConf.CameraName)) + discoveryDialog.CameraName = ThermoCamCont.currConf.CameraName; + if (!string.IsNullOrEmpty(ThermoCamCont.currConf.CameraName)) { //discoveryDialog.WindowState = FormWindowState.Minimized; if (discoveryDialog.ShowDialog() == DialogResult.OK) { - ImgData.ConnectCamera(discoveryDialog.SelectedCameraDevice); + ThermoCamCont.ConnectCamera(discoveryDialog.SelectedCameraDevice); } } } diff --git a/ThermoCamUtils/ImageData.cs b/ThermoCamUtils/TCContr.cs similarity index 99% rename from ThermoCamUtils/ImageData.cs rename to ThermoCamUtils/TCContr.cs index 4464e9aa..b9c82d15 100644 --- a/ThermoCamUtils/ImageData.cs +++ b/ThermoCamUtils/TCContr.cs @@ -19,7 +19,7 @@ namespace ThermoCamUtils /// /// Classe gestione aree di memoria immagini (thermo, trasformate, ...) /// - public class ImageData + public class TCContr { #region Protected Fields @@ -89,7 +89,7 @@ namespace ThermoCamUtils /// /// Setup oggetto e variabili /// - public ImageData() + public TCContr() { // setup folder varie dirDataTemp = $"{BASE_PATH}\\{dataPath}"; diff --git a/ThermoCamUtils/ThermoCamUtils.csproj b/ThermoCamUtils/ThermoCamUtils.csproj index 5639ab6b..6eee308d 100644 --- a/ThermoCamUtils/ThermoCamUtils.csproj +++ b/ThermoCamUtils/ThermoCamUtils.csproj @@ -90,7 +90,7 @@ - + From 0b47c548f8f55dd389621a2ea334a18c762f6d28 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Tue, 16 Feb 2021 19:28:01 +0100 Subject: [PATCH 10/15] tentativo setup camera da IP (fallito...) da rivedere --- ThermalImageStreamerDemo/DiscoveryForm.cs | 160 ++++++++++-------- ThermalImageStreamerDemo/MainForm.cs | 44 +++-- .../ThermalImageStreamerDemo.csproj | 3 + ThermalImageStreamerDemo/ThermoConf-AX5.json | 112 ++++++------ ThermalImageStreamerDemo/ThermoConf.json | 65 +++++++ ThermoCamUtils/ThermoCamConf.cs | 10 +- 6 files changed, 249 insertions(+), 145 deletions(-) create mode 100644 ThermalImageStreamerDemo/ThermoConf.json diff --git a/ThermalImageStreamerDemo/DiscoveryForm.cs b/ThermalImageStreamerDemo/DiscoveryForm.cs index 0dcb5507..a9cf26ac 100644 --- a/ThermalImageStreamerDemo/DiscoveryForm.cs +++ b/ThermalImageStreamerDemo/DiscoveryForm.cs @@ -8,7 +8,25 @@ namespace ThermalImageStreamerDemo { public partial class DiscoveryForm : Form { + #region Private Fields + + private Discovery _discovery; + + #endregion Private Fields + + #region Public Constructors + + public DiscoveryForm() + { + InitializeComponent(); + } + + #endregion Public Constructors + + #region Public Properties + public string CameraName { get; set; } = ""; + public bool doAutoConnect { get @@ -17,33 +35,19 @@ namespace ThermalImageStreamerDemo } } - private Discovery _discovery; - public DiscoveryForm() - { - InitializeComponent(); - } + /// + /// Camera selezionata + /// + public CameraDeviceInfo SelectedCameraDevice { get; set; } - private void DiscoveryForm_Load(object sender, EventArgs e) - { - Start(); - timerAutoconnect.Start(); - } + #endregion Public Properties - private void DiscoveryForm_FormClosing(object sender, FormClosingEventArgs e) - { - Stop(); - } + #region Private Methods - private void listViewDevices_MouseDoubleClick(object sender, MouseEventArgs e) + private static void DisposeDiscovery(Object context) { - SelectCameraFromListCtrl(); - DialogResult = DialogResult.OK; - Close(); - } - - void _discovery_DeviceError(object sender, DeviceErrorEventArgs e) - { - BeginInvoke((Action)(() => ShowError(e.ErrorMessage))); + var discovery = (Discovery)context; + discovery.Dispose(); } private static void ShowError(string message) @@ -51,26 +55,19 @@ namespace ThermalImageStreamerDemo MessageBox.Show(message); } - void _discovery_DeviceLost(object sender, CameraDeviceInfoEventArgs e) + private void _discovery_DeviceError(object sender, DeviceErrorEventArgs e) { - BeginInvoke((Action)(() => RemoveDevice(e.CameraDevice))); + BeginInvoke((Action)(() => ShowError(e.ErrorMessage))); } - void _discovery_DeviceFound(object sender, CameraDeviceInfoEventArgs e) + private void _discovery_DeviceFound(object sender, CameraDeviceInfoEventArgs e) { BeginInvoke((Action)(() => AddDevice(e.CameraDevice))); } - private void RemoveDevice(CameraDeviceInfo cameraDeviceInfo) + private void _discovery_DeviceLost(object sender, CameraDeviceInfoEventArgs e) { - foreach (ListViewItem item in listViewDevices.Items) - { - var device = item.Tag as CameraDeviceInfo; - if (device != null && device.DeviceIdentifier == cameraDeviceInfo.DeviceIdentifier) - { - listViewDevices.Items.Remove(item); - } - } + BeginInvoke((Action)(() => RemoveDevice(e.CameraDevice))); } private void AddDevice(CameraDeviceInfo cameraDeviceInfo) @@ -103,18 +100,60 @@ namespace ThermalImageStreamerDemo item.Tag = info; listViewDevices.Items.Add(item); } - } - /// - /// Camera selezionata - /// - public CameraDeviceInfo SelectedCameraDevice { get; set; } - - static void DisposeDiscovery(Object context) + private void buttonSelect_Click(object sender, EventArgs e) { - var discovery = (Discovery)context; - discovery.Dispose(); + SelectCameraFromListCtrl(); + DialogResult = DialogResult.OK; + Close(); + } + + private void DiscoveryForm_FormClosing(object sender, FormClosingEventArgs e) + { + Stop(); + } + + private void DiscoveryForm_Load(object sender, EventArgs e) + { + Start(); + timerAutoconnect.Start(); + } + + private void listViewDevices_MouseDoubleClick(object sender, MouseEventArgs e) + { + SelectCameraFromListCtrl(); + DialogResult = DialogResult.OK; + Close(); + } + + private void listViewDevices_SelectedIndexChanged(object sender, EventArgs e) + { + var items = listViewDevices.SelectedItems; + buttonSelect.Enabled = items.Count != 0; + } + + private void RemoveDevice(CameraDeviceInfo cameraDeviceInfo) + { + foreach (ListViewItem item in listViewDevices.Items) + { + var device = item.Tag as CameraDeviceInfo; + if (device != null && device.DeviceIdentifier == cameraDeviceInfo.DeviceIdentifier) + { + listViewDevices.Items.Remove(item); + } + } + } + + private void SelectCameraFromListCtrl() + { + var items = listViewDevices.SelectedItems; + if (items.Count <= 0) return; + var lv = items[0]; + var device = lv.Tag as CameraDeviceInfo; + SelectedCameraDevice = device; + DialogResult = DialogResult.OK; + Close(); } private void Start() @@ -131,9 +170,9 @@ namespace ThermalImageStreamerDemo // _discovery.Start(Interface.Usb); // or with a combination - // _discovery.Start(Interface.Network | Interface.Usb); + // _discovery.Start(Interface.Network | Interface.Usb); - // Start discovery, scan on all interfaces. + // Start discovery, scan on all interfaces. // This requires that Bonjour and the Pleora drivers are installed, see the Atlas web page for more information. _discovery.Start(); } @@ -149,30 +188,6 @@ namespace ThermalImageStreamerDemo _discovery = null; } - private void buttonSelect_Click(object sender, EventArgs e) - { - SelectCameraFromListCtrl(); - DialogResult = DialogResult.OK; - Close(); - } - - void SelectCameraFromListCtrl() - { - var items = listViewDevices.SelectedItems; - if (items.Count <= 0) return; - var lv = items[0]; - var device = lv.Tag as CameraDeviceInfo; - SelectedCameraDevice = device; - DialogResult = DialogResult.OK; - Close(); - } - - private void listViewDevices_SelectedIndexChanged(object sender, EventArgs e) - { - var items = listViewDevices.SelectedItems; - buttonSelect.Enabled = items.Count != 0; - } - private void timerAutoconnect_Tick(object sender, EventArgs e) { timerAutoconnect.Stop(); @@ -181,7 +196,7 @@ namespace ThermalImageStreamerDemo { foreach (ListViewItem item in listViewDevices.Items) { - if(item.Text == CameraName) + if (item.Text == CameraName) { item.Selected = true; SelectCameraFromListCtrl(); @@ -192,5 +207,6 @@ namespace ThermalImageStreamerDemo timerAutoconnect.Start(); } + #endregion Private Methods } -} +} \ No newline at end of file diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 676c7a76..331f4937 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -49,6 +49,11 @@ namespace ThermalImageStreamerDemo ThermoCamCont.eh_CameraConnStatusChanged += ImgData_eh_CameraConnStatusChanged; // cerco se ho un set di parametri già impostati... ThermoCamCont.tryReloadConf(); + // avvio l'autoconnessione + if (!string.IsNullOrEmpty(ThermoCamCont.currConf.CameraName)) + { + discoveryCamera(); + } // sistemo le conf temp setRangeTemp(); // calcolo i currConf.destPoints @@ -273,7 +278,7 @@ namespace ThermalImageStreamerDemo ThermoCamCont.ConnectCamera(discoveryDlg.SelectedCameraDevice); // salvo nome camera in conf attuale! ThermoCamCont.currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; - ThermoCamCont.currConf.CameraAddress = discoveryDlg.SelectedCameraDevice.IpSettings.IpAddress; ; + ThermoCamCont.currConf.SelectedCameraDevice = discoveryDlg.SelectedCameraDevice; ThermoCamCont.saveConf(); } } @@ -300,9 +305,6 @@ namespace ThermalImageStreamerDemo { BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); - // se si disconnette --> NUOVA richiesta connessione alla CHILD... - - // TODO FARE!!! } private void ImgData_eh_CameraDisposed(object sender, EventArgs e) @@ -342,11 +344,6 @@ namespace ThermalImageStreamerDemo private void MainForm_Shown(object sender, EventArgs e) { - // avvio l'autoconnessione - if (!string.IsNullOrEmpty(ThermoCamCont.currConf.CameraName)) - { - discoveryCamera(); - } } private void openToolStripMenuItem_Click(object sender, EventArgs e) @@ -555,11 +552,10 @@ namespace ThermalImageStreamerDemo { if (readTemp) { - // mostro temp da FLIR - lblReadTemp.Text = $"{ThermoCamCont.lastReadTemp:N2} °C"; - try { + // mostro temp da FLIR + lblReadTemp.Text = $"{ThermoCamCont.lastReadTemp:N2} °C"; // mostro minimo / massimo lblMinTemp.Text = $"{ThermoCamCont.lastTempRange.Minimum:N2}"; lblMaxTemp.Text = $"{ThermoCamCont.lastTempRange.Maximum:N2}"; @@ -577,13 +573,27 @@ namespace ThermalImageStreamerDemo public void discoveryCamera() { var discoveryDialog = new DiscoveryForm(); - discoveryDialog.CameraName = ThermoCamCont.currConf.CameraName; - if (!string.IsNullOrEmpty(ThermoCamCont.currConf.CameraName)) + if (ThermoCamCont.currConf.SelectedCameraDevice != null) { - //discoveryDialog.WindowState = FormWindowState.Minimized; - if (discoveryDialog.ShowDialog() == DialogResult.OK) + try { - ThermoCamCont.ConnectCamera(discoveryDialog.SelectedCameraDevice); + ThermoCamCont.ConnectCamera(ThermoCamCont.currConf.SelectedCameraDevice); + } + catch + { } + } + // se no connesso così prosegue... + if (!IRCam.ThermoCamera.IsConnected) + { + discoveryDialog.SelectedCameraDevice = ThermoCamCont.currConf.SelectedCameraDevice; + discoveryDialog.CameraName = ThermoCamCont.currConf.CameraName; + if (discoveryDialog.doAutoConnect) + { + //discoveryDialog.WindowState = FormWindowState.Minimized; + if (discoveryDialog.ShowDialog() == DialogResult.OK) + { + ThermoCamCont.ConnectCamera(discoveryDialog.SelectedCameraDevice); + } } } } diff --git a/ThermalImageStreamerDemo/ThermalImageStreamerDemo.csproj b/ThermalImageStreamerDemo/ThermalImageStreamerDemo.csproj index 226415c6..3b2694ad 100644 --- a/ThermalImageStreamerDemo/ThermalImageStreamerDemo.csproj +++ b/ThermalImageStreamerDemo/ThermalImageStreamerDemo.csproj @@ -140,6 +140,9 @@ Settings.settings True + + PreserveNewest + diff --git a/ThermalImageStreamerDemo/ThermoConf-AX5.json b/ThermalImageStreamerDemo/ThermoConf-AX5.json index 1952568d..79ab6528 100644 --- a/ThermalImageStreamerDemo/ThermoConf-AX5.json +++ b/ThermalImageStreamerDemo/ThermoConf-AX5.json @@ -1,55 +1,65 @@ { - "ConfCameraDevice": { - "IpConfiguration": { - "Error": 1, - "IsDhcpValid": false, - "IsDhcpEnabled": false, - "DefaultGateway": "", - "SubnetMask": "" + "MeasPoints": [], + "CameraName": "FLIR AX5", + "DestPoints": { + "Coords": [ + "0, 0", + "1500, 0", + "1500, 1200", + "0, 1200" + ], + "curr": 0 }, - "IsFlirCamera": true, - "CameraDeviceType": 32, - "Name": "FLIR AX5", - "IpSettings": { - "IpAddress": "10.74.82.110", - "Hostname": "", - "Mac": "00:11:1c:04:3d:32", - "SubnetMask": "255.255.255.0", - "DefaultGateway": "", - "IsWireless": false, - "Adapter": "{0EFF8137-F8BD-4A44-A77B-BAACF4C4A8D7}", - "AdapterMac": "00:15:5d:e9:dd:16", - "IsValid": true + "OrigPoints": { + "Coords": [ + "55, 214", + "49, 68", + "218, 80", + "197, 226" + ], + "curr": 4 }, - "StreamingFormats": [ - 0 - ], - "SelectedStreamingFormat": 0, - "DeviceIdentifier": "00:11:1c:04:3d:32", - "SerialNumber": "83202739", - "OsImagekitName": "N/A", - "SwCombinationVersion": "Version 1.0 (02.05.15)", - "ConfigurationKitName": "N/A", - "Article": "FLIR AX5", - "VideoQuality": 0, - "IsRecorderEnabled": true - }, - "origPoints": { - "curr": 4, - "Coords": [ - "66, 223", - "20, 84", - "188, 51", - "205, 197" - ] - }, - "destPoints": { - "curr": 0, - "Coords": [ - "0, 0", - "640, 0", - "640, 512", - "0, 512" - ] - } + "SelectedCameraDevice": { + "IpConfiguration": { + "Error": 1, + "IsDhcpValid": false, + "IsDhcpEnabled": false, + "DefaultGateway": "", + "SubnetMask": "" + }, + "IsFlirCamera": true, + "CameraDeviceType": 32, + "Name": "FLIR AX5", + "IpSettings": { + "IpAddress": "10.74.82.110", + "Hostname": "", + "Mac": "00:11:1c:04:3d:32", + "SubnetMask": "255.255.255.0", + "DefaultGateway": "", + "IsWireless": false, + "Adapter": "{0EFF8137-F8BD-4A44-A77B-BAACF4C4A8D7}", + "AdapterMac": "00:15:5d:e9:dd:16", + "IsValid": true + }, + "StreamingFormats": [ + 0 + ], + "SelectedStreamingFormat": 0, + "DeviceIdentifier": "00:11:1c:04:3d:32", + "SerialNumber": "83202739", + "OsImagekitName": "N/A", + "SwCombinationVersion": "Version 1.0 (02.05.15)", + "ConfigurationKitName": "N/A", + "Article": "FLIR AX5", + "VideoQuality": 0, + "IsRecorderEnabled": true + }, + "TargetRange": { + "Max": 60.0, + "Min": 0.0 + }, + "TargetSize": { + "X": 1500, + "Y": 1200 + } } \ No newline at end of file diff --git a/ThermalImageStreamerDemo/ThermoConf.json b/ThermalImageStreamerDemo/ThermoConf.json new file mode 100644 index 00000000..79ab6528 --- /dev/null +++ b/ThermalImageStreamerDemo/ThermoConf.json @@ -0,0 +1,65 @@ +{ + "MeasPoints": [], + "CameraName": "FLIR AX5", + "DestPoints": { + "Coords": [ + "0, 0", + "1500, 0", + "1500, 1200", + "0, 1200" + ], + "curr": 0 + }, + "OrigPoints": { + "Coords": [ + "55, 214", + "49, 68", + "218, 80", + "197, 226" + ], + "curr": 4 + }, + "SelectedCameraDevice": { + "IpConfiguration": { + "Error": 1, + "IsDhcpValid": false, + "IsDhcpEnabled": false, + "DefaultGateway": "", + "SubnetMask": "" + }, + "IsFlirCamera": true, + "CameraDeviceType": 32, + "Name": "FLIR AX5", + "IpSettings": { + "IpAddress": "10.74.82.110", + "Hostname": "", + "Mac": "00:11:1c:04:3d:32", + "SubnetMask": "255.255.255.0", + "DefaultGateway": "", + "IsWireless": false, + "Adapter": "{0EFF8137-F8BD-4A44-A77B-BAACF4C4A8D7}", + "AdapterMac": "00:15:5d:e9:dd:16", + "IsValid": true + }, + "StreamingFormats": [ + 0 + ], + "SelectedStreamingFormat": 0, + "DeviceIdentifier": "00:11:1c:04:3d:32", + "SerialNumber": "83202739", + "OsImagekitName": "N/A", + "SwCombinationVersion": "Version 1.0 (02.05.15)", + "ConfigurationKitName": "N/A", + "Article": "FLIR AX5", + "VideoQuality": 0, + "IsRecorderEnabled": true + }, + "TargetRange": { + "Max": 60.0, + "Min": 0.0 + }, + "TargetSize": { + "X": 1500, + "Y": 1200 + } +} \ No newline at end of file diff --git a/ThermoCamUtils/ThermoCamConf.cs b/ThermoCamUtils/ThermoCamConf.cs index b6b16945..f43b2eea 100644 --- a/ThermoCamUtils/ThermoCamConf.cs +++ b/ThermoCamUtils/ThermoCamConf.cs @@ -56,11 +56,6 @@ namespace ThermoCamUtils #region Public Properties - /// - /// IP Address Camera selezionata x autoconnect ("" = nessun autoconnect) - /// - public string CameraAddress { get; set; } = ""; - /// /// Camera selezionata x autoconnect ("" = nessun autoconnect) /// @@ -76,6 +71,11 @@ namespace ThermoCamUtils /// public SetPoints OrigPoints { get; set; } = new SetPoints(); + /// + /// Camera selezionata + /// + public CameraDeviceInfo SelectedCameraDevice { get; set; } + /// /// Range scala colori desiderata /// From 4b346d8ba70c68527a3f869f9ac4e8d9ac582be2 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Wed, 17 Feb 2021 08:57:34 +0100 Subject: [PATCH 11/15] fix conf e discovery iniziale --- ThermalImageStreamerDemo/DiscoveryForm.cs | 3 +- ThermalImageStreamerDemo/MainForm.cs | 23 ++++++------- ThermalImageStreamerDemo/ThermoConf-AX5.json | 36 +------------------- ThermalImageStreamerDemo/ThermoConf.json | 36 +------------------- ThermoCamUtils/DiscoveryHelper.cs | 18 ++++++++++ ThermoCamUtils/ThermoCamConf.cs | 7 ++++ ThermoCamUtils/ThermoCamUtils.csproj | 1 + 7 files changed, 40 insertions(+), 84 deletions(-) create mode 100644 ThermoCamUtils/DiscoveryHelper.cs diff --git a/ThermalImageStreamerDemo/DiscoveryForm.cs b/ThermalImageStreamerDemo/DiscoveryForm.cs index a9cf26ac..b33717f8 100644 --- a/ThermalImageStreamerDemo/DiscoveryForm.cs +++ b/ThermalImageStreamerDemo/DiscoveryForm.cs @@ -25,13 +25,14 @@ namespace ThermalImageStreamerDemo #region Public Properties + public string CameraAddress { get; set; } = ""; public string CameraName { get; set; } = ""; public bool doAutoConnect { get { - return !string.IsNullOrEmpty(CameraName); + return (!string.IsNullOrEmpty(CameraAddress) || !string.IsNullOrEmpty(CameraName)); } } diff --git a/ThermalImageStreamerDemo/MainForm.cs b/ThermalImageStreamerDemo/MainForm.cs index 331f4937..661148d9 100644 --- a/ThermalImageStreamerDemo/MainForm.cs +++ b/ThermalImageStreamerDemo/MainForm.cs @@ -278,7 +278,7 @@ namespace ThermalImageStreamerDemo ThermoCamCont.ConnectCamera(discoveryDlg.SelectedCameraDevice); // salvo nome camera in conf attuale! ThermoCamCont.currConf.CameraName = discoveryDlg.SelectedCameraDevice.Name; - ThermoCamCont.currConf.SelectedCameraDevice = discoveryDlg.SelectedCameraDevice; + ThermoCamCont.currConf.CameraAddress = discoveryDlg.SelectedCameraDevice.IpSettings.IpAddress; ThermoCamCont.saveConf(); } } @@ -303,8 +303,14 @@ namespace ThermalImageStreamerDemo private void ImgData_eh_CameraConnStatusChanged(object sender, Flir.Atlas.Live.ConnectionStatusChangedEventArgs e) { - BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); - BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); + try + { + BeginInvoke((Action)(() => toolStripConnectionStatus.Text = e.Status.ToString())); + BeginInvoke((Action)(() => toolStripConnectionStatus.ForeColor = e.Status == ConnectionStatus.Connected ? Color.Green : Color.Gray)); + BeginInvoke((Action)(() => cameraToolStripMenuItem.Enabled = e.Status == ConnectionStatus.Connected)); + } + catch + { } } private void ImgData_eh_CameraDisposed(object sender, EventArgs e) @@ -573,19 +579,10 @@ namespace ThermalImageStreamerDemo public void discoveryCamera() { var discoveryDialog = new DiscoveryForm(); - if (ThermoCamCont.currConf.SelectedCameraDevice != null) - { - try - { - ThermoCamCont.ConnectCamera(ThermoCamCont.currConf.SelectedCameraDevice); - } - catch - { } - } // se no connesso così prosegue... if (!IRCam.ThermoCamera.IsConnected) { - discoveryDialog.SelectedCameraDevice = ThermoCamCont.currConf.SelectedCameraDevice; + discoveryDialog.CameraAddress = ThermoCamCont.currConf.CameraAddress; discoveryDialog.CameraName = ThermoCamCont.currConf.CameraName; if (discoveryDialog.doAutoConnect) { diff --git a/ThermalImageStreamerDemo/ThermoConf-AX5.json b/ThermalImageStreamerDemo/ThermoConf-AX5.json index 79ab6528..670b4221 100644 --- a/ThermalImageStreamerDemo/ThermoConf-AX5.json +++ b/ThermalImageStreamerDemo/ThermoConf-AX5.json @@ -1,6 +1,7 @@ { "MeasPoints": [], "CameraName": "FLIR AX5", + "CameraAddress": "", "DestPoints": { "Coords": [ "0, 0", @@ -19,41 +20,6 @@ ], "curr": 4 }, - "SelectedCameraDevice": { - "IpConfiguration": { - "Error": 1, - "IsDhcpValid": false, - "IsDhcpEnabled": false, - "DefaultGateway": "", - "SubnetMask": "" - }, - "IsFlirCamera": true, - "CameraDeviceType": 32, - "Name": "FLIR AX5", - "IpSettings": { - "IpAddress": "10.74.82.110", - "Hostname": "", - "Mac": "00:11:1c:04:3d:32", - "SubnetMask": "255.255.255.0", - "DefaultGateway": "", - "IsWireless": false, - "Adapter": "{0EFF8137-F8BD-4A44-A77B-BAACF4C4A8D7}", - "AdapterMac": "00:15:5d:e9:dd:16", - "IsValid": true - }, - "StreamingFormats": [ - 0 - ], - "SelectedStreamingFormat": 0, - "DeviceIdentifier": "00:11:1c:04:3d:32", - "SerialNumber": "83202739", - "OsImagekitName": "N/A", - "SwCombinationVersion": "Version 1.0 (02.05.15)", - "ConfigurationKitName": "N/A", - "Article": "FLIR AX5", - "VideoQuality": 0, - "IsRecorderEnabled": true - }, "TargetRange": { "Max": 60.0, "Min": 0.0 diff --git a/ThermalImageStreamerDemo/ThermoConf.json b/ThermalImageStreamerDemo/ThermoConf.json index 79ab6528..670b4221 100644 --- a/ThermalImageStreamerDemo/ThermoConf.json +++ b/ThermalImageStreamerDemo/ThermoConf.json @@ -1,6 +1,7 @@ { "MeasPoints": [], "CameraName": "FLIR AX5", + "CameraAddress": "", "DestPoints": { "Coords": [ "0, 0", @@ -19,41 +20,6 @@ ], "curr": 4 }, - "SelectedCameraDevice": { - "IpConfiguration": { - "Error": 1, - "IsDhcpValid": false, - "IsDhcpEnabled": false, - "DefaultGateway": "", - "SubnetMask": "" - }, - "IsFlirCamera": true, - "CameraDeviceType": 32, - "Name": "FLIR AX5", - "IpSettings": { - "IpAddress": "10.74.82.110", - "Hostname": "", - "Mac": "00:11:1c:04:3d:32", - "SubnetMask": "255.255.255.0", - "DefaultGateway": "", - "IsWireless": false, - "Adapter": "{0EFF8137-F8BD-4A44-A77B-BAACF4C4A8D7}", - "AdapterMac": "00:15:5d:e9:dd:16", - "IsValid": true - }, - "StreamingFormats": [ - 0 - ], - "SelectedStreamingFormat": 0, - "DeviceIdentifier": "00:11:1c:04:3d:32", - "SerialNumber": "83202739", - "OsImagekitName": "N/A", - "SwCombinationVersion": "Version 1.0 (02.05.15)", - "ConfigurationKitName": "N/A", - "Article": "FLIR AX5", - "VideoQuality": 0, - "IsRecorderEnabled": true - }, "TargetRange": { "Max": 60.0, "Min": 0.0 diff --git a/ThermoCamUtils/DiscoveryHelper.cs b/ThermoCamUtils/DiscoveryHelper.cs new file mode 100644 index 00000000..cabddf70 --- /dev/null +++ b/ThermoCamUtils/DiscoveryHelper.cs @@ -0,0 +1,18 @@ +using Flir.Atlas.Live.Discovery; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace ThermoCamUtils +{ + public class DiscoveryHelper + { + #region Private Fields + + private Discovery _discovery; + + #endregion Private Fields + } +} \ No newline at end of file diff --git a/ThermoCamUtils/ThermoCamConf.cs b/ThermoCamUtils/ThermoCamConf.cs index f43b2eea..b6eb0e0e 100644 --- a/ThermoCamUtils/ThermoCamConf.cs +++ b/ThermoCamUtils/ThermoCamConf.cs @@ -56,6 +56,11 @@ namespace ThermoCamUtils #region Public Properties + /// + /// Indirizzo Camera selezionata x autoconnect ("" = nessun autoconnect) + /// + public string CameraAddress { get; set; } = ""; + /// /// Camera selezionata x autoconnect ("" = nessun autoconnect) /// @@ -71,10 +76,12 @@ namespace ThermoCamUtils /// public SetPoints OrigPoints { get; set; } = new SetPoints(); +#if false /// /// Camera selezionata /// public CameraDeviceInfo SelectedCameraDevice { get; set; } +#endif /// /// Range scala colori desiderata diff --git a/ThermoCamUtils/ThermoCamUtils.csproj b/ThermoCamUtils/ThermoCamUtils.csproj index 6eee308d..45be7441 100644 --- a/ThermoCamUtils/ThermoCamUtils.csproj +++ b/ThermoCamUtils/ThermoCamUtils.csproj @@ -88,6 +88,7 @@ + From 9a36d1568a2b45b8acf21f0665fafc8ec8b39096 Mon Sep 17 00:00:00 2001 From: Thermo_SIM Date: Wed, 17 Feb 2021 15:05:29 +0100 Subject: [PATCH 12/15] Fix Riscaldi --- .../tables/outputTab/output-row-item.ts | 20 ++++++++----------- .../tables/riscaldi-table/riscaldi-table.ts | 4 ++-- 2 files changed, 10 insertions(+), 14 deletions(-) diff --git a/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/InputOutput/components/tables/outputTab/output-row-item.ts b/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/InputOutput/components/tables/outputTab/output-row-item.ts index 37df6a22..21550681 100644 --- a/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/InputOutput/components/tables/outputTab/output-row-item.ts +++ b/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/InputOutput/components/tables/outputTab/output-row-item.ts @@ -25,20 +25,16 @@ export default class outputRow extends Vue { } async force(value: number) { - - console.log("force",value); - await underTheHoodService.forceChannel(this.group, this.item, value); - /* - if(this.item.isForced) - await underTheHoodService.forceChannel(this.group, this.item, value); - else - { + if(!this.item.isForced && (this.item.forcedValue === undefined || value != this.item.forcedValue)) + { ModalHelper.AskConfirm( this.$options.filters.localize("modal_confirm_title", "Richiesta di conferma"), - this.$options.filters.localize("softkey_confirm", "Confirm?"), - async() => { - await underTheHoodService.forceChannel(this.group, this.item, value); + this.$options.filters.localize("softkey_confirm", "Confirm?"), + async() => { + await underTheHoodService.forceChannel(this.group, this.item, value); }, null, "modal"); - }*/ + } + else + await underTheHoodService.forceChannel(this.group, this.item, value); } async reset() { diff --git a/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/Riscaldi/components/tables/riscaldi-table/riscaldi-table.ts b/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/Riscaldi/components/tables/riscaldi-table/riscaldi-table.ts index 703f7d47..e3c74f4d 100644 --- a/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/Riscaldi/components/tables/riscaldi-table/riscaldi-table.ts +++ b/Thermo.Active/wwwroot/src/app_modules_thermo/sotto-cofano/Riscaldi/components/tables/riscaldi-table/riscaldi-table.ts @@ -18,11 +18,11 @@ export default class RiscaldiTable extends Vue { } getBoard(id) { - return Math.floor((id-1)/16); + return Math.floor((id-1)/16) +1; } getOutput(id) { - return Math.floor((id-1)%16); + return Math.floor((id-1)%16) +1; } mounted() { From 2ac7fa4361bfd1469affe12b76123b55e4db8fb1 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Wed, 17 Feb 2021 19:13:24 +0100 Subject: [PATCH 13/15] modifica DB con migrazione x gestione last image thermo --- .../Controllers/ProdInfoController.cs | 394 ++-- ...226_Added_ThermoImage_prodInfo.Designer.cs | 29 + ...102171753226_Added_ThermoImage_prodInfo.cs | 30 + ...2171753226_Added_ThermoImage_prodInfo.resx | 126 ++ .../Thermo.Active.Database.csproj | 7 + .../DTOModels/ThProd/DTOProdInfo.cs | 189 +- .../DatabaseModels/ProdInfoModel.cs | 77 +- Thermo.Active.NC/NcAdapter.cs | 1726 +++++++++-------- 8 files changed, 1414 insertions(+), 1164 deletions(-) create mode 100644 Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.Designer.cs create mode 100644 Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.cs create mode 100644 Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.resx diff --git a/Thermo.Active.Database/Controllers/ProdInfoController.cs b/Thermo.Active.Database/Controllers/ProdInfoController.cs index a806b283..cb0f063c 100644 --- a/Thermo.Active.Database/Controllers/ProdInfoController.cs +++ b/Thermo.Active.Database/Controllers/ProdInfoController.cs @@ -6,206 +6,224 @@ using Thermo.Active.Model.DatabaseModels; namespace Thermo.Active.Database.Controllers { - public class ProdInfoController : IDisposable - { - private DatabaseContext dbCtx; + public class ProdInfoController : IDisposable + { + #region Private Fields - public ProdInfoController() - { - // Initialize database context - dbCtx = new DatabaseContext(); - } + private DatabaseContext dbCtx; - public void Dispose() - { - // Clear database context - dbCtx.Dispose(); - } - /// - /// Get record by NumDone - /// - /// - /// - public ProdInfoModel FindByNumDone(int num) - { - return dbCtx - .ProdInfo - .Where(x => x.NumDone == num) - .SingleOrDefault(); - } - /// - /// Get historical paginated data from DB (DESC ordered) - /// - /// - /// - /// - public List GetPaginatedDesc(int numStart, int numRecord) - { - int numEnd = numStart - numRecord; - // check numEnd - if (numEnd < 0) - numEnd = 0; - // retrieve - return dbCtx - .ProdInfo - .Where(x => x.NumDone <= numStart) - //.Where(x => x.NumDone <= numStart && x.NumDone > numEnd) - .OrderByDescending(x => x.DtEvent) - .Take(numRecord) - .ToList(); - } - /// - /// Get historical paginated data from DB (ASC ordered) - /// - /// - /// - /// - public List GetPaginatedAsc(int numStart, int numRecord) - { - int numEnd = numStart + numRecord; - // retrieve - return dbCtx - .ProdInfo - .Where(x => x.NumDone >= numStart) - .OrderBy(x => x.DtEvent) - .Take(numRecord) - .ToList(); - } - /// - /// Create new prodInfo record on DB - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public ProdInfoModel Create(short NumTarget, short NumDone, int TimeWarm, int TimeVent, int TimeVacuum, int TimeCycleGross, int TimeCycleNet, double MaterialTempEndWarm, double MaterialTempEndVent, double MoldTemp, double VacuumReadVal, double MouldEnergyOUT, double MouldEnergyIN, bool IsScrap) - { - // Create database machine model - ProdInfoModel prodData = new ProdInfoModel() - { - DtEvent = DateTime.Now, - NumTarget = NumTarget, - NumDone = NumDone, - TimeWarm = TimeWarm, - TimeVent = TimeVent, - TimeVacuum = TimeVacuum, - TimeCycleGross = TimeCycleGross, - TimeCycleNet = TimeCycleNet, - MaterialTempEndWarm = MaterialTempEndWarm, - MaterialTempEndVent = MaterialTempEndVent, - MoldTemp = MoldTemp, - VacuumReadVal = VacuumReadVal, - MouldEnergyOUT = MouldEnergyOUT, - MouldEnergyIN = MouldEnergyIN, - IsScrap = IsScrap - }; - try - { - // Add to database - dbCtx.ProdInfo.AddOrUpdate(prodData); - //dbCtx.ProdInfo.Add(prodData); - // Commit changes - dbCtx.SaveChanges(); - } - catch - { } + #endregion Private Fields - return prodData; - } - /// - /// Process table and set as scrap by num value - /// - /// - /// - public bool SetScrap(int num, bool isScrap) - { - bool answ = false; + #region Public Constructors - var currRecord = dbCtx - .ProdInfo - .Where(x => x.NumDone == num) - .SingleOrDefault(); - try - { - if (currRecord != null) + public ProdInfoController() { - currRecord.IsScrap = isScrap; + // Initialize database context + dbCtx = new DatabaseContext(); } - // save! - dbCtx.SaveChanges(); - answ = true; - } - catch - { } - return answ; - } - /// - /// Process table and keep only maxKeep most recent ones - /// - /// - /// - public bool PurgeOldest(int maxKeep) - { - bool answ = false; + #endregion Public Constructors - // check if purge needed - int numRec = dbCtx.ProdInfo.Count(); - if (numRec > maxKeep) - { - ProdInfoModel firstToDelete = (ProdInfoModel)(from p in dbCtx.ProdInfo - orderby p.DtEvent descending - select p).Skip(maxKeep).Take(1); + #region Public Methods - // call deletion - dbCtx - .ProdInfo - .RemoveRange( - dbCtx + /// + /// Create new prodInfo record on DB + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + public ProdInfoModel Create(short NumTarget, short NumDone, int TimeWarm, int TimeVent, int TimeVacuum, int TimeCycleGross, int TimeCycleNet, float MaterialTempEndWarm, float MaterialTempEndVent, float MoldTemp, float VacuumReadVal, float MouldEnergyOUT, float MouldEnergyIN, bool IsScrap, string ThermoImage) + { + // Create database machine model + ProdInfoModel prodData = new ProdInfoModel() + { + DtEvent = DateTime.Now, + NumTarget = NumTarget, + NumDone = NumDone, + TimeWarm = TimeWarm, + TimeVent = TimeVent, + TimeVacuum = TimeVacuum, + TimeCycleGross = TimeCycleGross, + TimeCycleNet = TimeCycleNet, + MaterialTempEndWarm = MaterialTempEndWarm, + MaterialTempEndVent = MaterialTempEndVent, + MoldTemp = MoldTemp, + VacuumReadVal = VacuumReadVal, + MouldEnergyOUT = MouldEnergyOUT, + MouldEnergyIN = MouldEnergyIN, + IsScrap = IsScrap, + ThermoImage = ThermoImage + }; + try + { + // Add to database + dbCtx.ProdInfo.AddOrUpdate(prodData); + //dbCtx.ProdInfo.Add(prodData); + // Commit changes + dbCtx.SaveChanges(); + } + catch + { } + + return prodData; + } + + public void Dispose() + { + // Clear database context + dbCtx.Dispose(); + } + + /// + /// Get record by NumDone + /// + /// + /// + public ProdInfoModel FindByNumDone(int num) + { + return dbCtx .ProdInfo - .Where(x => x.DtEvent <= firstToDelete.DtEvent) - ); - - try - { - // save! - dbCtx.SaveChanges(); - answ = true; + .Where(x => x.NumDone == num) + .SingleOrDefault(); } - catch - { } - } - return answ; - } - /// - /// Process table and delete all record (truncate) - /// - /// - public bool PurgeAll() - { - bool answ = false; + /// + /// Get historical paginated data from DB (ASC ordered) + /// + /// + /// + /// + public List GetPaginatedAsc(int numStart, int numRecord) + { + int numEnd = numStart + numRecord; + // retrieve + return dbCtx + .ProdInfo + .Where(x => x.NumDone >= numStart) + .OrderBy(x => x.DtEvent) + .Take(numRecord) + .ToList(); + } - try - { - dbCtx - .Database - .ExecuteSqlCommand("TRUNCATE TABLE prodInfo"); - } - catch - { } - return answ; + /// + /// Get historical paginated data from DB (DESC ordered) + /// + /// + /// + /// + public List GetPaginatedDesc(int numStart, int numRecord) + { + int numEnd = numStart - numRecord; + // check numEnd + if (numEnd < 0) + numEnd = 0; + // retrieve + return dbCtx + .ProdInfo + .Where(x => x.NumDone <= numStart) + //.Where(x => x.NumDone <= numStart && x.NumDone > numEnd) + .OrderByDescending(x => x.DtEvent) + .Take(numRecord) + .ToList(); + } + + /// + /// Process table and delete all record (truncate) + /// + /// + public bool PurgeAll() + { + bool answ = false; + + try + { + dbCtx + .Database + .ExecuteSqlCommand("TRUNCATE TABLE prodInfo"); + } + catch + { } + return answ; + } + + /// + /// Process table and keep only maxKeep most recent ones + /// + /// + /// + public bool PurgeOldest(int maxKeep) + { + bool answ = false; + + // check if purge needed + int numRec = dbCtx.ProdInfo.Count(); + if (numRec > maxKeep) + { + ProdInfoModel firstToDelete = (ProdInfoModel)(from p in dbCtx.ProdInfo + orderby p.DtEvent descending + select p).Skip(maxKeep).Take(1); + + // call deletion + dbCtx + .ProdInfo + .RemoveRange( + dbCtx + .ProdInfo + .Where(x => x.DtEvent <= firstToDelete.DtEvent) + ); + + try + { + // save! + dbCtx.SaveChanges(); + answ = true; + } + catch + { } + } + return answ; + } + + /// + /// Process table and set as scrap by num value + /// + /// + /// + public bool SetScrap(int num, bool isScrap) + { + bool answ = false; + + var currRecord = dbCtx + .ProdInfo + .Where(x => x.NumDone == num) + .SingleOrDefault(); + try + { + if (currRecord != null) + { + currRecord.IsScrap = isScrap; + } + // save! + dbCtx.SaveChanges(); + answ = true; + } + catch + { } + return answ; + } + + #endregion Public Methods } - } } \ No newline at end of file diff --git a/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.Designer.cs b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.Designer.cs new file mode 100644 index 00000000..b9127f4d --- /dev/null +++ b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.Designer.cs @@ -0,0 +1,29 @@ +// +namespace Thermo.Active.Database.Migrations +{ + using System.CodeDom.Compiler; + using System.Data.Entity.Migrations; + using System.Data.Entity.Migrations.Infrastructure; + using System.Resources; + + [GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")] + public sealed partial class Added_ThermoImage_prodInfo : IMigrationMetadata + { + private readonly ResourceManager Resources = new ResourceManager(typeof(Added_ThermoImage_prodInfo)); + + string IMigrationMetadata.Id + { + get { return "202102171753226_Added_ThermoImage_prodInfo"; } + } + + string IMigrationMetadata.Source + { + get { return null; } + } + + string IMigrationMetadata.Target + { + get { return Resources.GetString("Target"); } + } + } +} diff --git a/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.cs b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.cs new file mode 100644 index 00000000..dddad0d0 --- /dev/null +++ b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.cs @@ -0,0 +1,30 @@ +namespace Thermo.Active.Database.Migrations +{ + using System; + using System.Data.Entity.Migrations; + + public partial class Added_ThermoImage_prodInfo : DbMigration + { + public override void Up() + { + AddColumn("dbo.ProdInfo", "ThermoImage", c => c.String(unicode: false)); + AlterColumn("dbo.ProdInfo", "MaterialTempEndWarm", c => c.Single(nullable: false)); + AlterColumn("dbo.ProdInfo", "MaterialTempEndVent", c => c.Single(nullable: false)); + AlterColumn("dbo.ProdInfo", "MoldTemp", c => c.Single(nullable: false)); + AlterColumn("dbo.ProdInfo", "VacuumReadVal", c => c.Single(nullable: false)); + AlterColumn("dbo.ProdInfo", "MouldEnergyOUT", c => c.Single(nullable: false)); + AlterColumn("dbo.ProdInfo", "MouldEnergyIN", c => c.Single(nullable: false)); + } + + public override void Down() + { + AlterColumn("dbo.ProdInfo", "MouldEnergyIN", c => c.Double(nullable: false)); + AlterColumn("dbo.ProdInfo", "MouldEnergyOUT", c => c.Double(nullable: false)); + AlterColumn("dbo.ProdInfo", "VacuumReadVal", c => c.Double(nullable: false)); + AlterColumn("dbo.ProdInfo", "MoldTemp", c => c.Double(nullable: false)); + AlterColumn("dbo.ProdInfo", "MaterialTempEndVent", c => c.Double(nullable: false)); + AlterColumn("dbo.ProdInfo", "MaterialTempEndWarm", c => c.Double(nullable: false)); + DropColumn("dbo.ProdInfo", "ThermoImage"); + } + } +} diff --git a/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.resx b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.resx new file mode 100644 index 00000000..54494a85 --- /dev/null +++ b/Thermo.Active.Database/Migrations/202102171753226_Added_ThermoImage_prodInfo.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 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 + + + dbo + + \ No newline at end of file diff --git a/Thermo.Active.Database/Thermo.Active.Database.csproj b/Thermo.Active.Database/Thermo.Active.Database.csproj index 4c6523b7..8608f3ea 100644 --- a/Thermo.Active.Database/Thermo.Active.Database.csproj +++ b/Thermo.Active.Database/Thermo.Active.Database.csproj @@ -154,6 +154,10 @@ 202011051531133_AddedKeyboaSoftkey.cs + + + 202102171753226_Added_ThermoImage_prodInfo.cs + @@ -205,6 +209,9 @@ 202011051531133_AddedKeyboaSoftkey.cs + + 202102171753226_Added_ThermoImage_prodInfo.cs + \ No newline at end of file diff --git a/Thermo.Active.Model/DTOModels/ThProd/DTOProdInfo.cs b/Thermo.Active.Model/DTOModels/ThProd/DTOProdInfo.cs index dd1bb2e5..c5bd1450 100644 --- a/Thermo.Active.Model/DTOModels/ThProd/DTOProdInfo.cs +++ b/Thermo.Active.Model/DTOModels/ThProd/DTOProdInfo.cs @@ -7,95 +7,112 @@ using System.Threading.Tasks; namespace Thermo.Active.Model.DTOModels.ThProd { - public class DTOProdInfo - { - public DateTime DtEvent { get; set; } - public short NumTarget { get; set; } = 0; - public short NumDone { get; set; } = 0; - public double TimeWarm { get; set; } = 0; - public double TimeVent { get; set; } = 0; - public double TimeVacuum { get; set; } = 0; - public double TimeCycleGross { get; set; } = 0; - public double TimeCycleNet { get; set; } = 0; - public int NumDec { get; set; } = 1; - public int ScaleFactor { get; set; } = 1000; - public double MaterialTempEndWarm { get; set; } = 0; - public double MaterialTempEndVent { get; set; } = 0; - public double MoldTemp { get; set; } = 0; - public double VacuumReadVal { get; set; } = 0; - public double MouldEnergyOUT { get; set; } = 0; - public double MouldEnergyIN { get; set; } = 0; - public bool IsScrap { get; set; } = false; - public short NumPreHot { get; set; } = 0; - - public override bool Equals(object obj) + public class DTOProdInfo { - // Object is not a GaugeModel instance - if (!(obj is DTOProdInfo item)) - return false; + #region Public Constructors - if (DtEvent != item.DtEvent) - return false; - if (NumTarget != item.NumTarget) - return false; - if (NumDone != item.NumDone) - return false; - if (Math.Round(Math.Abs(TimeWarm - item.TimeWarm), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(TimeVent - item.TimeVent), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(TimeVacuum - item.TimeVacuum), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(TimeCycleGross - item.TimeCycleGross), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(TimeCycleNet - item.TimeCycleNet), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(MaterialTempEndWarm - item.MaterialTempEndWarm), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(MaterialTempEndVent - item.MaterialTempEndVent), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(MoldTemp - item.MoldTemp), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(VacuumReadVal - item.VacuumReadVal), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(MouldEnergyOUT - item.MouldEnergyOUT), 1) >= Constants.EPSILON) - return false; - if (Math.Round(Math.Abs(MouldEnergyIN - item.MouldEnergyIN), 1) >= Constants.EPSILON) - return false; - if (IsScrap != item.IsScrap) - return false; - if (NumPreHot != item.NumPreHot) - return false; + public DTOProdInfo() + { + } - return true; - } - public override int GetHashCode() - { - return base.GetHashCode(); - } + public DTOProdInfo(ThermoModels.ProdInfoModel pimRawData) + { + this.DtEvent = pimRawData.DtEvent; + this.NumDone = pimRawData.NumDone; + this.NumTarget = pimRawData.NumTarget; + this.ThermoImage = pimRawData.ThermoImage; + this.TimeCycleGross = Math.Round((double)pimRawData.TimeCycleGross / this.ScaleFactor, 2); + this.TimeCycleNet = Math.Round((double)pimRawData.TimeCycleNet / this.ScaleFactor, 2); + this.TimeVacuum = Math.Round((double)pimRawData.TimeVacuum / this.ScaleFactor, 2); + this.TimeVent = Math.Round((double)pimRawData.TimeVent / this.ScaleFactor, 2); + this.TimeWarm = Math.Round((double)pimRawData.TimeWarm / this.ScaleFactor, 2); + this.MaterialTempEndWarm = pimRawData.MaterialTempEndWarm; + this.MaterialTempEndVent = pimRawData.MaterialTempEndVent; + this.MoldTemp = pimRawData.MoldTemp; + this.VacuumReadVal = pimRawData.VacuumReadVal; + this.MouldEnergyIN = pimRawData.MouldEnergyIN; + this.MouldEnergyOUT = pimRawData.MouldEnergyOUT; + this.IsScrap = pimRawData.IsScrap; + this.NumPreHot = pimRawData.NumPreHot; + } - public DTOProdInfo() - { - } + #endregion Public Constructors - public DTOProdInfo(ThermoModels.ProdInfoModel pimRawData) - { - this.DtEvent = pimRawData.DtEvent; - this.NumDone = pimRawData.NumDone; - this.NumTarget = pimRawData.NumTarget; - this.TimeCycleGross = Math.Round((double)pimRawData.TimeCycleGross / this.ScaleFactor, 2); - this.TimeCycleNet = Math.Round((double)pimRawData.TimeCycleNet / this.ScaleFactor, 2); - this.TimeVacuum = Math.Round((double)pimRawData.TimeVacuum / this.ScaleFactor, 2); - this.TimeVent = Math.Round((double)pimRawData.TimeVent / this.ScaleFactor, 2); - this.TimeWarm = Math.Round((double)pimRawData.TimeWarm / this.ScaleFactor, 2); - this.MaterialTempEndWarm = pimRawData.MaterialTempEndWarm; - this.MaterialTempEndVent = pimRawData.MaterialTempEndVent; - this.MoldTemp = pimRawData.MoldTemp; - this.VacuumReadVal = pimRawData.VacuumReadVal; - this.MouldEnergyIN = pimRawData.MouldEnergyIN; - this.MouldEnergyOUT = pimRawData.MouldEnergyOUT; - this.IsScrap = pimRawData.IsScrap; - this.NumPreHot = pimRawData.NumPreHot; + #region Public Properties + + public DateTime DtEvent { get; set; } + public bool IsScrap { get; set; } = false; + public double MaterialTempEndVent { get; set; } = 0; + public double MaterialTempEndWarm { get; set; } = 0; + public double MoldTemp { get; set; } = 0; + public double MouldEnergyIN { get; set; } = 0; + public double MouldEnergyOUT { get; set; } = 0; + public int NumDec { get; set; } = 1; + public short NumDone { get; set; } = 0; + public short NumPreHot { get; set; } = 0; + public short NumTarget { get; set; } = 0; + public int ScaleFactor { get; set; } = 1000; + public string ThermoImage { get; set; } = ""; + public double TimeCycleGross { get; set; } = 0; + public double TimeCycleNet { get; set; } = 0; + public double TimeVacuum { get; set; } = 0; + public double TimeVent { get; set; } = 0; + public double TimeWarm { get; set; } = 0; + public double VacuumReadVal { get; set; } = 0; + + #endregion Public Properties + + #region Public Methods + + public override bool Equals(object obj) + { + // Object is not a GaugeModel instance + if (!(obj is DTOProdInfo item)) + return false; + + if (DtEvent != item.DtEvent) + return false; + if (NumTarget != item.NumTarget) + return false; + if (NumDone != item.NumDone) + return false; + if (ThermoImage != item.ThermoImage) + return false; + if (Math.Round(Math.Abs(TimeWarm - item.TimeWarm), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(TimeVent - item.TimeVent), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(TimeVacuum - item.TimeVacuum), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(TimeCycleGross - item.TimeCycleGross), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(TimeCycleNet - item.TimeCycleNet), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(MaterialTempEndWarm - item.MaterialTempEndWarm), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(MaterialTempEndVent - item.MaterialTempEndVent), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(MoldTemp - item.MoldTemp), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(VacuumReadVal - item.VacuumReadVal), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(MouldEnergyOUT - item.MouldEnergyOUT), 1) >= Constants.EPSILON) + return false; + if (Math.Round(Math.Abs(MouldEnergyIN - item.MouldEnergyIN), 1) >= Constants.EPSILON) + return false; + if (IsScrap != item.IsScrap) + return false; + if (NumPreHot != item.NumPreHot) + return false; + + return true; + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + + #endregion Public Methods } - } -} +} \ No newline at end of file diff --git a/Thermo.Active.Model/DatabaseModels/ProdInfoModel.cs b/Thermo.Active.Model/DatabaseModels/ProdInfoModel.cs index a2cf5e1d..85d78cd8 100644 --- a/Thermo.Active.Model/DatabaseModels/ProdInfoModel.cs +++ b/Thermo.Active.Model/DatabaseModels/ProdInfoModel.cs @@ -7,43 +7,58 @@ namespace Thermo.Active.Model.DatabaseModels [Table("ProdInfo")] public class ProdInfoModel { + #region Public Properties + [Key] [DatabaseGenerated(DatabaseGeneratedOption.None)] [Column("DtEvent", Order = 0)] public DateTime DtEvent { get; set; } - [Column("NumTarget")] - public short NumTarget { get; set; } - [Column("NumDone")] - public short NumDone { get; set; } - - [Column("TimeWarm")] - public int TimeWarm { get; set; } - [Column("TimeVent")] - public int TimeVent { get; set; } - [Column("TimeVacuum")] - public int TimeVacuum { get; set; } - [Column("TimeCycleGross")] - public int TimeCycleGross { get; set; } - [Column("TimeCycleNet")] - public int TimeCycleNet { get; set; } - - [Column("MaterialTempEndWarm")] - public double MaterialTempEndWarm { get; set; } - [Column("MaterialTempEndVent")] - public double MaterialTempEndVent { get; set; } - [Column("MoldTemp")] - public double MoldTemp { get; set; } - - [Column("VacuumReadVal")] - public double VacuumReadVal { get; set; } - - [Column("MouldEnergyOUT")] - public double MouldEnergyOUT { get; set; } - [Column("MouldEnergyIN")] - public double MouldEnergyIN { get; set; } [Column("IsScrap")] public bool IsScrap { get; set; } + [Column("MaterialTempEndVent")] + public float MaterialTempEndVent { get; set; } + + [Column("MaterialTempEndWarm")] + public float MaterialTempEndWarm { get; set; } + + [Column("MoldTemp")] + public float MoldTemp { get; set; } + + [Column("MouldEnergyIN")] + public float MouldEnergyIN { get; set; } + + [Column("MouldEnergyOUT")] + public float MouldEnergyOUT { get; set; } + + [Column("NumDone")] + public short NumDone { get; set; } + + [Column("NumTarget")] + public short NumTarget { get; set; } + + [Column("ThermoImage")] + public string ThermoImage { get; set; } + + [Column("TimeCycleGross")] + public int TimeCycleGross { get; set; } + + [Column("TimeCycleNet")] + public int TimeCycleNet { get; set; } + + [Column("TimeVacuum")] + public int TimeVacuum { get; set; } + + [Column("TimeVent")] + public int TimeVent { get; set; } + + [Column("TimeWarm")] + public int TimeWarm { get; set; } + + [Column("VacuumReadVal")] + public float VacuumReadVal { get; set; } + + #endregion Public Properties } -} +} \ No newline at end of file diff --git a/Thermo.Active.NC/NcAdapter.cs b/Thermo.Active.NC/NcAdapter.cs index e484a923..a1e6f44e 100644 --- a/Thermo.Active.NC/NcAdapter.cs +++ b/Thermo.Active.NC/NcAdapter.cs @@ -36,6 +36,11 @@ namespace Thermo.Active.NC /// private readonly static object connectLock = new object(); + /// + /// variabili delle richieste da PLC: tutte nella status command + /// + private static List statusCmd = new List(); + #endregion Private Fields #region Protected Fields @@ -45,6 +50,36 @@ namespace Thermo.Active.NC /// protected static bool forceProdPanelDbReload = false; + /// + /// Last recipe data from PLC + /// + protected static Dictionary lastAxisData = new Dictionary(); + + /// + /// Last recipe data from PLCINFO data from PLC + /// + protected static Dictionary lastAxisInfoReadData = new Dictionary(); + + /// + /// Last prod info from PLC + /// + protected static ThermoModels.ProdInfoModel lastProdInfoData = new ThermoModels.ProdInfoModel(); + + /// + /// Ultimi dati prodPanel + /// + protected static DTOThermoPanelProd LastProdPanelData = new DTOThermoPanelProd(); + + /// + /// Last recipe data from PLC + /// + protected static Dictionary lastRecipe = new Dictionary(); + + /// + /// Immagine corrente dalla thermocam (FISSA) + /// + protected string currThermoImage = "_last.jpg"; + /// /// Ultimo ciclo registrato (secondi) /// @@ -65,6 +100,11 @@ namespace Thermo.Active.NC /// protected DateTime lastProdStart; + /// + /// ultima immagine scattata dalla thermocam x salvataggio in PROD + /// + protected string lastThermoImage = "_last.jpg"; + #endregion Protected Fields #region Public Fields @@ -99,221 +139,7 @@ namespace Thermo.Active.NC #endregion Public Constructors - #region Public Properties - - /// - /// Delay between single param write operation - /// - public int delayParamWrite - { - get - { - int answ = 5; - int.TryParse(ConfigurationManager.AppSettings["delayParamWrite"], out answ); - return answ; - } - } - - /// - /// Parametro lambda per EWMA smoothing - /// - public double ewmaLambda - { - get - { - int answ = 50; - int.TryParse(ConfigurationManager.AppSettings["ewmaPar100"], out answ); - return (double)answ / 100; - } - } - - /// - /// Max number of param writable as single operation - /// - public int nMaxParamWrite - { - get - { - int answ = 5; - int.TryParse(ConfigurationManager.AppSettings["nMaxParamWrite"], out answ); - return answ; - } - } - - #endregion Public Properties - - #region Private Methods - - private int GetMaxCountBetweenLayerComponents(ScadaSchemaLayerModel layer) - { - // Choose which list contains the maximum number of elements - int max = layer.Buttons.Count(); - - if (layer.Labels.Count() > max) - max = layer.Labels.Count(); - - if (layer.Images.Count() > max) - max = layer.Images.Count(); - - if (layer.Inputs.Count() > max) - max = layer.Inputs.Count(); - - if (layer.ProgressBars.Count() > max) - max = layer.ProgressBars.Count(); - - return max; - } - - #endregion Private Methods - - #region Public Methods - - public CmsError Connect() - { - lock (connectLock) - { - // Connect NC - if (!numericalControl.NC_IsConnected()) - return numericalControl.NC_Connect(); - } - lastProdStart = DateTime.Now; - return NO_ERROR; - } - - public void Disconnect() - { - numericalControl.NC_Disconnect(); - } - - public void Dispose() - { - if (NcConfig.NcVendor != NC_VENDOR.SIEMENS) - numericalControl.NC_Disconnect(); - } - - public CmsError GetActiveClient(out int clientId) - { - clientId = 0; - return numericalControl.PLC_RActiveClient(ref clientId); - } - - public CmsError ManageCandies() - { - // Check if i have to Manage it - if (!CandiesController.IsTimeToMangeCandies()) - return NO_ERROR; - - // Read Machine ID - string strMachNumber = "0"; - CmsError libraryError = numericalControl.NC_RMachineNumber(NcConfig.MachineNumberHasLetters, ref strMachNumber); - if (libraryError.IsError()) - return libraryError; - - SupportFunctions.ConvertStringMachineNumberIntoNumber(strMachNumber, out bool containsLetters, out int machNumber); - - // Read Data from NC & elaborate it - long NcCandy = 0; - libraryError = numericalControl.PLC_RCandy(ref NcCandy); - if (libraryError.IsError()) - return libraryError; - - bool bNC_OK = CandiesController.GetDataFromLincense(NcCandy, containsLetters, out long NCLic, out int NCMatr, out long NCParam); - bool bNC_VALID = machNumber == NCMatr && bNC_OK; - - // Read Data from PC - bool bPC_OK = CandiesController.GetPCLincense(containsLetters, out long PcPLic, out int PCMatr, out long PCParam); - bool bPC_VALID = machNumber == PCMatr && bPC_OK; - - // Elaborate Licence and write it - CandiesController.ElaborateLincense(bPC_VALID, bNC_VALID, PCParam, NCParam, PcPLic, NCLic, out DateTime newDate, out bool bRewrite); - if (bRewrite) - WriteCandy(newDate, machNumber); - - // Read Expired Lincense Bit on NC - bool bNcCandy = false; - libraryError = numericalControl.PLC_RExpiredCandy(ref bNcCandy); - if (libraryError.IsError()) - return libraryError; - - // Manage Expired Lincense Bit - if (CandiesController.ElaborateExpiredBit(newDate, bNcCandy, out bool bNewCandy)) - { - //Write Expired Lincense Bit on NC - libraryError = numericalControl.PLC_WExpiredCandy(bNewCandy); - if (libraryError.IsError()) - return libraryError; - } - - return NO_ERROR; - } - - public bool ReadHeadWTime(int Head, out uint hour) - { - hour = 0; - CmsError libraryError = numericalControl.PLC_RWorkedTimeHead(Head, ref hour); - if (libraryError.IsError()) - return false; - - return true; - } - - public bool ReadMachineWTime(out uint hour) - { - hour = 0; - CmsError libraryError = numericalControl.PLC_RWorkedTimeMachine(ref hour); - if (libraryError.IsError()) - return false; - - return true; - } - - public bool ResetHeadWTime(int Head) - { - CmsError libraryError = numericalControl.PLC_WResetWorkedTimeHead(Head); - if (libraryError.IsError()) - return false; - - return true; - } - - public bool ResetMachineWTime(uint hour) - { - CmsError libraryError = numericalControl.PLC_WResetWorkedTimeMachine(hour); - if (libraryError.IsError()) - return false; - - return true; - } - - public bool ResetMaintenanceCounter(uint counter) - { - CmsError libraryError = numericalControl.PLC_WResetMachineCounters(counter); - if (libraryError.IsError()) - return false; - - return true; - } - - public NcThermo SetNumericalControl() - { - // Return new Numerical control instance choosed from the configuration - switch (NcConfig.NcVendor) - { - case NC_VENDOR.S7NET: - return new Nc_S7Net(NcConfig.NcIpAddress, NcConfig.NcPort, 2000); - } - - return null; - } - - #endregion Public Methods - - #region StatusCommand words - - /// - /// variabili delle richieste da PLC: tutte nella status command - /// - private static List statusCmd = new List(); + #region Private Properties private static bool ThermoCameraReqImage { @@ -477,6 +303,77 @@ namespace Thermo.Active.NC } } + #endregion Private Properties + + #region Public Properties + + /// + /// Delay between single param write operation + /// + public int delayParamWrite + { + get + { + int answ = 5; + int.TryParse(ConfigurationManager.AppSettings["delayParamWrite"], out answ); + return answ; + } + } + + /// + /// Parametro lambda per EWMA smoothing + /// + public double ewmaLambda + { + get + { + int answ = 50; + int.TryParse(ConfigurationManager.AppSettings["ewmaPar100"], out answ); + return (double)answ / 100; + } + } + + /// + /// Max number of param writable as single operation + /// + public int nMaxParamWrite + { + get + { + int answ = 5; + int.TryParse(ConfigurationManager.AppSettings["nMaxParamWrite"], out answ); + return answ; + } + } + + #endregion Public Properties + + #region Private Methods + + private int GetMaxCountBetweenLayerComponents(ScadaSchemaLayerModel layer) + { + // Choose which list contains the maximum number of elements + int max = layer.Buttons.Count(); + + if (layer.Labels.Count() > max) + max = layer.Labels.Count(); + + if (layer.Images.Count() > max) + max = layer.Images.Count(); + + if (layer.Inputs.Count() > max) + max = layer.Inputs.Count(); + + if (layer.ProgressBars.Count() > max) + max = layer.ProgressBars.Count(); + + return max; + } + + #endregion Private Methods + + #region Protected Methods + /// /// Check bit on word /// @@ -496,135 +393,6 @@ namespace Thermo.Active.NC return answ; } - #endregion StatusCommand words - - #region cached data - - /// - /// Last recipe data from PLC - /// - protected static Dictionary lastAxisData = new Dictionary(); - - /// - /// Last recipe data from PLCINFO data from PLC - /// - protected static Dictionary lastAxisInfoReadData = new Dictionary(); - - /// - /// Last prod info from PLC - /// - protected static ThermoModels.ProdInfoModel lastProdInfoData = new ThermoModels.ProdInfoModel(); - - /// - /// Ultimi dati prodPanel - /// - protected static DTOThermoPanelProd LastProdPanelData = new DTOThermoPanelProd(); - - /// - /// Last recipe data from PLC - /// - protected static Dictionary lastRecipe = new Dictionary(); - - #endregion cached data - - #region Read Data - - #region Axes - - /// - /// Dati assi da CONF + letture PLC - /// - /// - /// - public CmsError ReadAxisData(bool refreshOnlyRT, out Dictionary axisData) - { - CmsError libraryError = NO_ERROR; - // initi della config ricetta (x poter poi ciclare...) - var axisConfig = AxesConfig.Select(x => new DTOAxisInfoModel() - { - ID = x.Id, - name = x.Name, - type = x.Type.ToString() - }).ToDictionary(x => x.ID, x => x); - - // se ho valori in cache uso quelli, altrimenti init obj - if (lastAxisData != null && lastAxisData.Count > 0) - { - axisData = lastAxisData; - } - else - { - // conversione al volo a dictionary - axisData = AxesConfig.Select(x => new DTOAxisInfoModel() - { - ID = x.Id, - name = x.Name, - type = x.Type.ToString() - }).ToDictionary(x => x.ID, x => x); - } - - // solo x S7Net... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - Dictionary currAxisRtData = new Dictionary(); - Dictionary currAxisInfoData = new Dictionary(); - - if (lastAxisInfoReadData == null) - { - // init! - lastAxisInfoReadData = currAxisInfoData; - } - - // leggo SICURAMENTE i dati RT - libraryError = numericalControl.PLC_RAxisRTList(ref currAxisRtData); - if (libraryError.IsError()) - return libraryError; - - // se NON solo RT leggo tutti! - if (!refreshOnlyRT) - { - libraryError = numericalControl.PLC_RAxisInfoList(ref currAxisInfoData); - if (libraryError.IsError()) - return libraryError; - - // salvo valori acquisiti - lastAxisInfoReadData = currAxisInfoData; - } - else - { - currAxisInfoData = lastAxisInfoReadData; - } - - // ora completo i mancanti - foreach (var item in axisConfig) - { - // aggiorno (se c'è) il dato RT - if (currAxisRtData.ContainsKey(item.Key)) - { - axisData[item.Key].position = currAxisRtData[item.Key].Position; - axisData[item.Key].speed = currAxisRtData[item.Key].Speed; - axisData[item.Key].load = currAxisRtData[item.Key].Load; - } - - // aggiorno (se c'è) il dato INFO - if (currAxisInfoData.ContainsKey(item.Key)) - { - axisData[item.Key].errorCode = currAxisInfoData[item.Key].ErrorCode; - axisData[item.Key].movPhase = currAxisInfoData[item.Key].MovPhase; - axisData[item.Key].statusCode = currAxisInfoData[item.Key].StatusWord; - } - } - lastAxisData = axisData; - } - else - { - lastAxisData = axisData; - } - return libraryError; - } - - #endregion Axes - protected double getDimRatio(DTORecipeParam singlePar) { double ratio = 1; @@ -665,6 +433,10 @@ namespace Thermo.Active.NC return answ; } + #endregion Protected Methods + + #region Public Methods + public CmsError checkFlirImageRequest(out bool flirImageRequest) { flirImageRequest = ThermoCameraReqImage; @@ -700,12 +472,168 @@ namespace Thermo.Active.NC return NO_ERROR; } + public CmsError Connect() + { + lock (connectLock) + { + // Connect NC + if (!numericalControl.NC_IsConnected()) + return numericalControl.NC_Connect(); + } + lastProdStart = DateTime.Now; + return NO_ERROR; + } + + public void Disconnect() + { + numericalControl.NC_Disconnect(); + } + + public void Dispose() + { + if (NcConfig.NcVendor != NC_VENDOR.SIEMENS) + numericalControl.NC_Disconnect(); + } + public CmsError doAckSetpointInvalidated() { numericalControl.PLC_WAckSetpointInvalidated(); return NO_ERROR; } + public CmsError GetActiveClient(out int clientId) + { + clientId = 0; + return numericalControl.PLC_RActiveClient(ref clientId); + } + + /// + /// Legge dal PLC elenco di eventi LOG del ciclo e li presenta + /// + /// Oggetto elenco elementi LOG registrati da macchina + /// + public CmsError GetCycleLog(out Dictionary machineLog) + { + CmsError libraryError = NO_ERROR; + machineLog = new Dictionary(); + + if (false) + { + // recupero l'oggetto dall'NC + + // effettuo traduzione +#if false + // overview di base: ultima salvata... + var err2fix = new Dictionary(); + + // leggo la ricetta dal PLC! + var currRecipe = new Dictionary(); + libraryError = ReadFullRecipe(out currRecipe); + if (libraryError.IsError()) + return libraryError; + + // leggo l'intero array delle DB... QUI FAKE sulle DB configurate... + List recipeConfig = RecipeConfig.Select(x => new DTORecipeConfigModel() + { + Id = x.Id, + ScaleFactor = x.ScaleFactor, + NumDec = x.NumDec, + Category = x.Category.ToString(), + SubCategory_1 = x.SubCategory_1, + SubCategory_2 = x.SubCategory_2, + Name = x.Name, + Description = x.Description, + Format = x.Format, + Label = $"{x.Category}_{x.SubCategory_1}_{x.SubCategory_2}_{x.Name}".Replace("__", "_").Replace("__", "_").ToLower(), + EnumVal = x.EnumVal + }).ToList(); + + RecipeCatStatus currStatus = RecipeCatStatus.Unchanged; + + // da conf ricetta --> se ci sono li leggo da li... + if (NcFileAdapter.RecipeLiveData.RecipeOverview != null) + { + currOverview = NcFileAdapter.RecipeLiveData.RecipeOverview; + } + + // verifico eventualmente se mancasse qualcosa... + bool changed = false; + foreach (var item in recipeConfig) + { + if (!currOverview.ContainsKey(getRecipeSection(item.Category))) + { + currOverview.Add(getRecipeSection(item.Category), RecipeCatStatus.Unchanged); + changed = true; + } + } + + // ricerco SE co fossero errori --> reset come changedOK + foreach (var item in currOverview) + { + if (item.Value == RecipeCatStatus.HasError) + err2fix.Add(item.Key, RecipeCatStatus.ChangedOk); + } + foreach (var item in err2fix) + { + currOverview[item.Key] = item.Value; + changed = true; + } + + // se cambiato --> salvo in live data... + if (changed) + { + NcFileAdapter.RecipeLiveData.RecipeOverview = currOverview; + } + + // ORA percorro conf ricetta x cercare eventuali ERRORI...... + foreach (var item in recipeConfig) + { + currStatus = currOverview[getRecipeSection(item.Category)]; + + // se lo stato è errore --> esco... + if (currStatus == RecipeCatStatus.HasError) + { + continue; + } + // altrimenti controllo + else + { + // se in errore AND visibile --> registro... + bool checkCondition = false; + checkCondition = (currRecipe[item.Label].Status.HasError); + // 2020.07.29 - controllo condizione secondo status debug/release... + if (checkCondition) + { + currOverview[getRecipeSection(item.Category)] = RecipeCatStatus.HasError; + } + } + } +#endif + } + // altrimenti genero FAKE data + else + { + int eventVal = 0; + DateTime eventDate = DateTime.Now; + // genero random eventi da 1..maxEvent + Random rndGen = new Random(); + int maxEvent = 16; + int maxDelay = 30000; + for (int i = 0; i < 1024; i++) + { + // calcolo nuovo evento + eventVal = rndGen.Next(maxEvent); + // calcolo tempo anticipato + eventDate = eventDate.AddMilliseconds(-rndGen.Next(maxDelay)); + //salvo + machineLog.Add(eventDate, eventVal); + } + } + + // restituisco cod errore se trovato + return libraryError; + } + public CmsError GetExpiredMaintenances(out List expiredMaintenance) { // Return value @@ -943,6 +871,8 @@ namespace Thermo.Active.NC DtEvent = x.DtEvent, NumTarget = x.NumTarget, NumDone = x.NumDone, + // FIXME TODO: eliminare caso vuoto con immagine "_last" + ThermoImage = !string.IsNullOrEmpty(x.ThermoImage) ? x.ThermoImage : "_last.jpg", TimeWarm = x.TimeWarm, TimeVent = x.TimeVent, TimeVacuum = x.TimeVacuum, @@ -982,6 +912,8 @@ namespace Thermo.Active.NC DtEvent = x.DtEvent, NumTarget = x.NumTarget, NumDone = x.NumDone, + // FIXME TODO: eliminare caso vuoto con immagine "_last" + ThermoImage = !string.IsNullOrEmpty(x.ThermoImage) ? x.ThermoImage : "_last.jpg", TimeWarm = x.TimeWarm, TimeVent = x.TimeVent, TimeVacuum = x.TimeVacuum, @@ -1457,134 +1389,6 @@ namespace Thermo.Active.NC return libraryError; } - - /// - /// Legge dal PLC elenco di eventi LOG del ciclo e li presenta - /// - /// Oggetto elenco elementi LOG registrati da macchina - /// - public CmsError GetCycleLog(out Dictionary machineLog) - { - CmsError libraryError = NO_ERROR; - machineLog = new Dictionary(); - - if (false) - { - // recupero l'oggetto dall'NC - - // effettuo traduzione -#if false - // overview di base: ultima salvata... - var err2fix = new Dictionary(); - - // leggo la ricetta dal PLC! - var currRecipe = new Dictionary(); - libraryError = ReadFullRecipe(out currRecipe); - if (libraryError.IsError()) - return libraryError; - - // leggo l'intero array delle DB... QUI FAKE sulle DB configurate... - List recipeConfig = RecipeConfig.Select(x => new DTORecipeConfigModel() - { - Id = x.Id, - ScaleFactor = x.ScaleFactor, - NumDec = x.NumDec, - Category = x.Category.ToString(), - SubCategory_1 = x.SubCategory_1, - SubCategory_2 = x.SubCategory_2, - Name = x.Name, - Description = x.Description, - Format = x.Format, - Label = $"{x.Category}_{x.SubCategory_1}_{x.SubCategory_2}_{x.Name}".Replace("__", "_").Replace("__", "_").ToLower(), - EnumVal = x.EnumVal - }).ToList(); - - RecipeCatStatus currStatus = RecipeCatStatus.Unchanged; - - // da conf ricetta --> se ci sono li leggo da li... - if (NcFileAdapter.RecipeLiveData.RecipeOverview != null) - { - currOverview = NcFileAdapter.RecipeLiveData.RecipeOverview; - } - - // verifico eventualmente se mancasse qualcosa... - bool changed = false; - foreach (var item in recipeConfig) - { - if (!currOverview.ContainsKey(getRecipeSection(item.Category))) - { - currOverview.Add(getRecipeSection(item.Category), RecipeCatStatus.Unchanged); - changed = true; - } - } - - // ricerco SE co fossero errori --> reset come changedOK - foreach (var item in currOverview) - { - if (item.Value == RecipeCatStatus.HasError) - err2fix.Add(item.Key, RecipeCatStatus.ChangedOk); - } - foreach (var item in err2fix) - { - currOverview[item.Key] = item.Value; - changed = true; - } - - // se cambiato --> salvo in live data... - if (changed) - { - NcFileAdapter.RecipeLiveData.RecipeOverview = currOverview; - } - - // ORA percorro conf ricetta x cercare eventuali ERRORI...... - foreach (var item in recipeConfig) - { - currStatus = currOverview[getRecipeSection(item.Category)]; - - // se lo stato è errore --> esco... - if (currStatus == RecipeCatStatus.HasError) - { - continue; - } - // altrimenti controllo - else - { - // se in errore AND visibile --> registro... - bool checkCondition = false; - checkCondition = (currRecipe[item.Label].Status.HasError); - // 2020.07.29 - controllo condizione secondo status debug/release... - if (checkCondition) - { - currOverview[getRecipeSection(item.Category)] = RecipeCatStatus.HasError; - } - } - } -#endif - } - // altrimenti genero FAKE data - else - { - int eventVal = 0; - DateTime eventDate = DateTime.Now; - // genero random eventi da 1..maxEvent - Random rndGen = new Random(); - int maxEvent = 16; - int maxDelay = 30000; - for (int i = 0; i < 1024; i++) - { - // calcolo nuovo evento - eventVal = rndGen.Next(maxEvent); - // calcolo tempo anticipato - eventDate = eventDate.AddMilliseconds(-rndGen.Next(maxDelay)); - //salvo - machineLog.Add(eventDate, eventVal); - } - } - - // restituisco cod errore se trovato - return libraryError; - } - /// /// Legge tutti i parametri della ricetta e calcolo la overview dei vari steps /// @@ -1882,6 +1686,56 @@ namespace Thermo.Active.NC return libraryError; } + public CmsError ManageCandies() + { + // Check if i have to Manage it + if (!CandiesController.IsTimeToMangeCandies()) + return NO_ERROR; + + // Read Machine ID + string strMachNumber = "0"; + CmsError libraryError = numericalControl.NC_RMachineNumber(NcConfig.MachineNumberHasLetters, ref strMachNumber); + if (libraryError.IsError()) + return libraryError; + + SupportFunctions.ConvertStringMachineNumberIntoNumber(strMachNumber, out bool containsLetters, out int machNumber); + + // Read Data from NC & elaborate it + long NcCandy = 0; + libraryError = numericalControl.PLC_RCandy(ref NcCandy); + if (libraryError.IsError()) + return libraryError; + + bool bNC_OK = CandiesController.GetDataFromLincense(NcCandy, containsLetters, out long NCLic, out int NCMatr, out long NCParam); + bool bNC_VALID = machNumber == NCMatr && bNC_OK; + + // Read Data from PC + bool bPC_OK = CandiesController.GetPCLincense(containsLetters, out long PcPLic, out int PCMatr, out long PCParam); + bool bPC_VALID = machNumber == PCMatr && bPC_OK; + + // Elaborate Licence and write it + CandiesController.ElaborateLincense(bPC_VALID, bNC_VALID, PCParam, NCParam, PcPLic, NCLic, out DateTime newDate, out bool bRewrite); + if (bRewrite) + WriteCandy(newDate, machNumber); + + // Read Expired Lincense Bit on NC + bool bNcCandy = false; + libraryError = numericalControl.PLC_RExpiredCandy(ref bNcCandy); + if (libraryError.IsError()) + return libraryError; + + // Manage Expired Lincense Bit + if (CandiesController.ElaborateExpiredBit(newDate, bNcCandy, out bool bNewCandy)) + { + //Write Expired Lincense Bit on NC + libraryError = numericalControl.PLC_WExpiredCandy(bNewCandy); + if (libraryError.IsError()) + return libraryError; + } + + return NO_ERROR; + } + public CmsError ManageConfRequest() { CmsError libraryError = NO_ERROR; @@ -1934,7 +1788,6 @@ namespace Thermo.Active.NC return libraryError; } - // process ch load setup... Dictionary newRisk = new Dictionary(); foreach (var item in NcAdapter.RecipeLiveData.ChannelSetpoints) @@ -1947,7 +1800,6 @@ namespace Thermo.Active.NC if (libraryError.IsError()) return libraryError; - // Ack ! libraryError = numericalControl.PLC_WAckConfRecipeRequest(); if (libraryError.IsError()) @@ -1964,6 +1816,11 @@ namespace Thermo.Active.NC return libraryError; } + public CmsError ManageFlirStrobe() + { + return numericalControl.PLC_WAckFlirRequest(); + } + public CmsError ManageStatusCommand() { CmsError libraryError = NO_ERROR; @@ -2021,6 +1878,221 @@ namespace Thermo.Active.NC return libraryError; } + public CmsError PutOverride(uint id, string action) + { + HEAD_OVERRIDE_SIGN sign = HEAD_OVERRIDE_SIGN.MINUS; + if (action == "plus") + sign = HEAD_OVERRIDE_SIGN.PLUS; + + return numericalControl.PLC_WHeadOverride(id, sign); + } + + public CmsError PutPowerOnData(uint id) + { + // Set to true power on data by id + return numericalControl.PLC_WPowerOnData(id, true); + } + + public CmsError PutSelectAxis(byte axisId) + { + return numericalControl.AXES_WSelectAxis(axisId); + } + + public CmsError PutSelectProcess(ushort procNumber) + { + return numericalControl.PROC_WSelectProcess(procNumber); + } + + public CmsError PutUserSoftKeyClick(uint id) + { + // Write user softkey press to plc + return numericalControl.PLC_WUserSoftKey(id); + } + + /// + /// Dati assi da CONF + letture PLC + /// + /// + /// + public CmsError ReadAxisData(bool refreshOnlyRT, out Dictionary axisData) + { + CmsError libraryError = NO_ERROR; + // initi della config ricetta (x poter poi ciclare...) + var axisConfig = AxesConfig.Select(x => new DTOAxisInfoModel() + { + ID = x.Id, + name = x.Name, + type = x.Type.ToString() + }).ToDictionary(x => x.ID, x => x); + + // se ho valori in cache uso quelli, altrimenti init obj + if (lastAxisData != null && lastAxisData.Count > 0) + { + axisData = lastAxisData; + } + else + { + // conversione al volo a dictionary + axisData = AxesConfig.Select(x => new DTOAxisInfoModel() + { + ID = x.Id, + name = x.Name, + type = x.Type.ToString() + }).ToDictionary(x => x.ID, x => x); + } + + // solo x S7Net... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + Dictionary currAxisRtData = new Dictionary(); + Dictionary currAxisInfoData = new Dictionary(); + + if (lastAxisInfoReadData == null) + { + // init! + lastAxisInfoReadData = currAxisInfoData; + } + + // leggo SICURAMENTE i dati RT + libraryError = numericalControl.PLC_RAxisRTList(ref currAxisRtData); + if (libraryError.IsError()) + return libraryError; + + // se NON solo RT leggo tutti! + if (!refreshOnlyRT) + { + libraryError = numericalControl.PLC_RAxisInfoList(ref currAxisInfoData); + if (libraryError.IsError()) + return libraryError; + + // salvo valori acquisiti + lastAxisInfoReadData = currAxisInfoData; + } + else + { + currAxisInfoData = lastAxisInfoReadData; + } + + // ora completo i mancanti + foreach (var item in axisConfig) + { + // aggiorno (se c'è) il dato RT + if (currAxisRtData.ContainsKey(item.Key)) + { + axisData[item.Key].position = currAxisRtData[item.Key].Position; + axisData[item.Key].speed = currAxisRtData[item.Key].Speed; + axisData[item.Key].load = currAxisRtData[item.Key].Load; + } + + // aggiorno (se c'è) il dato INFO + if (currAxisInfoData.ContainsKey(item.Key)) + { + axisData[item.Key].errorCode = currAxisInfoData[item.Key].ErrorCode; + axisData[item.Key].movPhase = currAxisInfoData[item.Key].MovPhase; + axisData[item.Key].statusCode = currAxisInfoData[item.Key].StatusWord; + } + } + lastAxisData = axisData; + } + else + { + lastAxisData = axisData; + } + return libraryError; + } + + /// + /// Restituisce intero set dati IO Channels (conf + valori) + /// + /// + /// + public CmsError ReadFullIO(out DTOChannelsIO currChannelsIO) + { + CmsError libraryError = NO_ERROR; + currChannelsIO = new DTOChannelsIO(); + + // read and return channel IO data + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + // lettura da PLC + Dictionary currModBlock = new Dictionary(); + ThermoModels.ChanIOVis currThermoIOVis = new ThermoModels.ChanIOVis(); + ThermoModels.ChanIOVal currThermoIOVal = new ThermoModels.ChanIOVal(); + ThermoModels.ChanIOFor currThermoIOFor = new ThermoModels.ChanIOFor(); + ThermoModels.ChanIOValFor currThermoIOValFor = new ThermoModels.ChanIOValFor(); + libraryError = numericalControl.PLC_RIOChannelsConf(ref currThermoIOVis); + libraryError = numericalControl.PLC_RIOChannelsVal(ref currThermoIOVal, ref currThermoIOFor, ref currThermoIOValFor); + + // setup da config + List listDI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DI).Select(x => new DigitalIN() + { + Id = x.Id, + Bank = x.Bank, + Position = x.Position, + //Page = x.Category.ToString(), + Page = x.Page, + Wire = x.Wire, + Profinet = x.Profinet, + Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), + Visible = currThermoIOVis.DI.ContainsKey(x.Id) ? currThermoIOVis.DI[x.Id] : false, + Value = currThermoIOVal.DI.ContainsKey(x.Id) ? currThermoIOVal.DI[x.Id] : false + }).ToList(); + List listDO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DO).Select(x => new DigitalOUT() + { + Id = x.Id, + Bank = x.Bank, + Position = x.Position, + //Page = x.Category.ToString(), + Page = x.Page, + Wire = x.Wire, + Profinet = x.Profinet, + Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), + ForceEnabled = !x.DisableForce, + Visible = currThermoIOVis.DO.ContainsKey(x.Id) ? currThermoIOVis.DO[x.Id] : false, + Value = currThermoIOVal.DO.ContainsKey(x.Id) ? currThermoIOVal.DO[x.Id] : false, + IsForced = currThermoIOFor.DO.ContainsKey(x.Id) ? currThermoIOFor.DO[x.Id] : false, + ForceOne = currThermoIOValFor.DO.ContainsKey(x.Id) ? currThermoIOValFor.DO[x.Id] : false, + ForceZero = currThermoIOValFor.DO.ContainsKey(x.Id) ? !currThermoIOValFor.DO[x.Id] : false + }).ToList(); + List listAI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AI).Select(x => new AnalogIN() + { + Id = x.Id, + Bank = x.Bank, + Position = x.Position, + //Page = x.Category.ToString(), + Page = x.Page, + Wire = x.Wire, + Profinet = x.Profinet, + Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), + Visible = currThermoIOVis.AI.ContainsKey(x.Id) ? currThermoIOVis.AI[x.Id] : false, + Value = currThermoIOVal.AI.ContainsKey(x.Id) ? currThermoIOVal.AI[x.Id] : 0 + }).ToList(); + List listAO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AO).Select(x => new AnalogOUT() + { + Id = x.Id, + Bank = x.Bank, + Position = x.Position, + //Page = x.Category.ToString(), + Page = x.Page, + Wire = x.Wire, + Profinet = x.Profinet, + Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), + ForceEnabled = !x.DisableForce, + Visible = currThermoIOVis.AO.ContainsKey(x.Id) ? currThermoIOVis.AO[x.Id] : false, + Value = currThermoIOVal.AO.ContainsKey(x.Id) ? currThermoIOVal.AO[x.Id] : 0, + IsForced = currThermoIOFor.AO.ContainsKey(x.Id) ? currThermoIOFor.AO[x.Id] : false, + ForcedValue = currThermoIOValFor.AO.ContainsKey(x.Id) ? currThermoIOValFor.AO[x.Id] : 0 + }).ToList(); + + // assegno! + currChannelsIO.DI = listDI; + currChannelsIO.DO = listDO; + currChannelsIO.AI = listAI; + currChannelsIO.AO = listAO; + } + return libraryError; + } + /// /// Legge tutti i parametri della ricetta /// @@ -2118,6 +2190,26 @@ namespace Thermo.Active.NC return libraryError; } + public bool ReadHeadWTime(int Head, out uint hour) + { + hour = 0; + CmsError libraryError = numericalControl.PLC_RWorkedTimeHead(Head, ref hour); + if (libraryError.IsError()) + return false; + + return true; + } + + public bool ReadMachineWTime(out uint hour) + { + hour = 0; + CmsError libraryError = numericalControl.PLC_RWorkedTimeMachine(ref hour); + if (libraryError.IsError()) + return false; + + return true; + } + public CmsError ReadModBlock(out Dictionary currModules) { CmsError libraryError = NO_ERROR; @@ -2167,154 +2259,6 @@ namespace Thermo.Active.NC } return libraryError; } - /// - /// Restituisce intero set dati IO Channels (conf + valori) - /// - /// - /// - public CmsError ReadFullIO(out DTOChannelsIO currChannelsIO) - { - CmsError libraryError = NO_ERROR; - currChannelsIO = new DTOChannelsIO(); - - // read and return channel IO data - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - // lettura da PLC - Dictionary currModBlock = new Dictionary(); - ThermoModels.ChanIOVis currThermoIOVis = new ThermoModels.ChanIOVis(); - ThermoModels.ChanIOVal currThermoIOVal = new ThermoModels.ChanIOVal(); - ThermoModels.ChanIOFor currThermoIOFor = new ThermoModels.ChanIOFor(); - ThermoModels.ChanIOValFor currThermoIOValFor = new ThermoModels.ChanIOValFor(); - libraryError = numericalControl.PLC_RIOChannelsConf(ref currThermoIOVis); - libraryError = numericalControl.PLC_RIOChannelsVal(ref currThermoIOVal, ref currThermoIOFor, ref currThermoIOValFor); - - // setup da config - List listDI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DI).Select(x => new DigitalIN() - { - Id = x.Id, - Bank = x.Bank, - Position = x.Position, - //Page = x.Category.ToString(), - Page = x.Page, - Wire = x.Wire, - Profinet = x.Profinet, - Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), - Visible = currThermoIOVis.DI.ContainsKey(x.Id)? currThermoIOVis.DI[x.Id]:false, - Value = currThermoIOVal.DI.ContainsKey(x.Id) ? currThermoIOVal.DI[x.Id] : false - }).ToList(); - List listDO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DO).Select(x => new DigitalOUT() - { - Id = x.Id, - Bank = x.Bank, - Position = x.Position, - //Page = x.Category.ToString(), - Page = x.Page, - Wire = x.Wire, - Profinet = x.Profinet, - Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), - ForceEnabled=!x.DisableForce, - Visible = currThermoIOVis.DO.ContainsKey(x.Id) ? currThermoIOVis.DO[x.Id] : false, - Value = currThermoIOVal.DO.ContainsKey(x.Id) ? currThermoIOVal.DO[x.Id] : false, - IsForced = currThermoIOFor.DO.ContainsKey(x.Id) ? currThermoIOFor.DO[x.Id] : false, - ForceOne = currThermoIOValFor.DO.ContainsKey(x.Id) ? currThermoIOValFor.DO[x.Id] : false, - ForceZero = currThermoIOValFor.DO.ContainsKey(x.Id) ? !currThermoIOValFor.DO[x.Id] : false - }).ToList(); - List listAI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AI).Select(x => new AnalogIN() - { - Id = x.Id, - Bank = x.Bank, - Position = x.Position, - //Page = x.Category.ToString(), - Page = x.Page, - Wire = x.Wire, - Profinet = x.Profinet, - Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), - Visible = currThermoIOVis.AI.ContainsKey(x.Id) ? currThermoIOVis.AI[x.Id] : false, - Value = currThermoIOVal.AI.ContainsKey(x.Id) ? currThermoIOVal.AI[x.Id] : 0 - }).ToList(); - List listAO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AO).Select(x => new AnalogOUT() - { - Id = x.Id, - Bank = x.Bank, - Position = x.Position, - //Page = x.Category.ToString(), - Page = x.Page, - Wire = x.Wire, - Profinet = x.Profinet, - Label = x.Label.Replace("__", "_").Replace("__", "_").ToLower(), - ForceEnabled = !x.DisableForce, - Visible = currThermoIOVis.AO.ContainsKey(x.Id) ? currThermoIOVis.AO[x.Id] : false, - Value = currThermoIOVal.AO.ContainsKey(x.Id) ? currThermoIOVal.AO[x.Id] : 0, - IsForced = currThermoIOFor.AO.ContainsKey(x.Id) ? currThermoIOFor.AO[x.Id] : false, - ForcedValue = currThermoIOValFor.AO.ContainsKey(x.Id) ? currThermoIOValFor.AO[x.Id] : 0 - }).ToList(); - - // assegno! - currChannelsIO.DI = listDI; - currChannelsIO.DO = listDO; - currChannelsIO.AI = listAI; - currChannelsIO.AO = listAO; - } - return libraryError; - } - /// - /// Restitusice SOLO VALORI IO Channels - /// - /// - /// - public CmsError ReadValIO(out DTOChannelsIOVal currChannelsIoVal) - { - CmsError libraryError = NO_ERROR; - currChannelsIoVal = new DTOChannelsIOVal(); - // read and return channel IO data - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - // lettura da PLC - Dictionary currModBlock = new Dictionary(); - ThermoModels.ChanIOVal currThermoIOVal = new ThermoModels.ChanIOVal(); - ThermoModels.ChanIOFor currThermoIOFor = new ThermoModels.ChanIOFor(); - ThermoModels.ChanIOValFor currThermoIOValFor = new ThermoModels.ChanIOValFor(); - libraryError = numericalControl.PLC_RIOChannelsVal(ref currThermoIOVal, ref currThermoIOFor, ref currThermoIOValFor); - - // setup da config - List listDI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DI).Select(x => new DigInVal() - { - Id = x.Id, - Value = currThermoIOVal.DI.ContainsKey(x.Id) ? currThermoIOVal.DI[x.Id] : false - }).ToList(); - List listDO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DO).Select(x => new DigOutVal() - { - Id = x.Id, - ForceEnabled = !x.DisableForce, - Value = currThermoIOVal.DO.ContainsKey(x.Id) ? currThermoIOVal.DO[x.Id] : false, - IsForced = currThermoIOFor.DO.ContainsKey(x.Id) ? currThermoIOFor.DO[x.Id] : false, - ForceOne = currThermoIOValFor.DO.ContainsKey(x.Id) ? currThermoIOValFor.DO[x.Id] : false, - ForceZero = currThermoIOValFor.DO.ContainsKey(x.Id) ? !currThermoIOValFor.DO[x.Id] : false - }).ToList(); - List listAI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AI).Select(x => new AnalInVal() - { - Id = x.Id, - Value = currThermoIOVal.AI.ContainsKey(x.Id) ? currThermoIOVal.AI[x.Id] : 0 - }).ToList(); - List listAO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AO).Select(x => new AnalOutVal() - { - Id = x.Id, - ForceEnabled = !x.DisableForce, - Value = currThermoIOVal.AO.ContainsKey(x.Id) ? currThermoIOVal.AO[x.Id] : 0, - IsForced = currThermoIOFor.AO.ContainsKey(x.Id) ? currThermoIOFor.AO[x.Id] : false, - ForcedValue = currThermoIOValFor.AO.ContainsKey(x.Id) ? currThermoIOValFor.AO[x.Id] : 0 - }).ToList(); - - // assegno! - currChannelsIoVal.DI = listDI; - currChannelsIoVal.DO = listDO; - currChannelsIoVal.AI = listAI; - currChannelsIoVal.AO = listAO; - } - return libraryError; - - } /// /// Legge tutti i parametri della ricetta @@ -2508,13 +2452,18 @@ namespace Thermo.Active.NC public CmsError ReadProdInfoData(out DTOProdInfo prodInfoData) { prodInfoData = new DTOProdInfo(); - ThermoModels.ProdInfoModel prodInfoRawData = new ThermoModels.ProdInfoModel(); - CmsError libraryError = numericalControl.PLC_RProdInfo(ref prodInfoRawData); + ThermoModels.ProdInfoModel pInfoRaw = new ThermoModels.ProdInfoModel(); + CmsError libraryError = numericalControl.PLC_RProdInfo(ref pInfoRaw); if (libraryError.IsError()) return libraryError; + // DI DEFAULT aggiungo ULTIMA immagine scattata da thermocamera... x salvataggio su DB + pInfoRaw.ThermoImage = lastThermoImage; + // converto 1:1 dati da ThermoModels.ProdInfoModel --> DTOProdInfo - prodInfoData = new DTOProdInfo(prodInfoRawData); + prodInfoData = new DTOProdInfo(pInfoRaw); + // a livello di dato current invio SEMPRE il valore "_last.jpg che è immagine costante" + prodInfoData.ThermoImage = currThermoImage; // 2020.09.02: incremento di 1 il NUMERO dei pezzi, in modo che mostro il pezzo corrente (n=fatti + 1) prodInfoData.NumDone++; @@ -2522,18 +2471,18 @@ namespace Thermo.Active.NC // se nullo lo popolo if (lastProdInfoData == null) { - lastProdInfoData = prodInfoRawData; + lastProdInfoData = pInfoRaw; } // do comparison with old record and if changed --> persist on DB! - if (!prodInfoRawData.Equals(lastProdInfoData)) + if (!pInfoRaw.Equals(lastProdInfoData)) { // update last info data - lastProdInfoData = prodInfoRawData; + lastProdInfoData = pInfoRaw; } else { - prodInfoRawData = lastProdInfoData; + pInfoRaw = lastProdInfoData; } // se ho update da strobe... sennò restituisco ultima lettura... @@ -2542,7 +2491,7 @@ namespace Thermo.Active.NC // save on DB! attenzione: RAW DATA perché salvo pezzo PRECEDENTE... using (ProdInfoController prodInfoController = new ProdInfoController()) { - prodInfoController.Create(prodInfoRawData.NumTarget, prodInfoRawData.NumDone, prodInfoRawData.TimeWarm, prodInfoRawData.TimeVent, prodInfoRawData.TimeVacuum, prodInfoRawData.TimeCycleGross, prodInfoRawData.TimeCycleNet, prodInfoRawData.MaterialTempEndWarm, prodInfoRawData.MaterialTempEndVent, prodInfoRawData.MoldTemp, prodInfoRawData.VacuumReadVal, prodInfoRawData.MouldEnergyOUT, prodInfoRawData.MouldEnergyIN, false); + prodInfoController.Create(pInfoRaw.NumTarget, pInfoRaw.NumDone, pInfoRaw.TimeWarm, pInfoRaw.TimeVent, pInfoRaw.TimeVacuum, pInfoRaw.TimeCycleGross, pInfoRaw.TimeCycleNet, pInfoRaw.MaterialTempEndWarm, pInfoRaw.MaterialTempEndVent, pInfoRaw.MoldTemp, pInfoRaw.VacuumReadVal, pInfoRaw.MouldEnergyOUT, pInfoRaw.MouldEnergyIN, false, pInfoRaw.ThermoImage); // indico di rileggere il DB... forceProdPanelDbReload = true; } @@ -3172,6 +3121,63 @@ namespace Thermo.Active.NC return libraryError; } + /// + /// Restitusice SOLO VALORI IO Channels + /// + /// + /// + public CmsError ReadValIO(out DTOChannelsIOVal currChannelsIoVal) + { + CmsError libraryError = NO_ERROR; + currChannelsIoVal = new DTOChannelsIOVal(); + // read and return channel IO data + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + // lettura da PLC + Dictionary currModBlock = new Dictionary(); + ThermoModels.ChanIOVal currThermoIOVal = new ThermoModels.ChanIOVal(); + ThermoModels.ChanIOFor currThermoIOFor = new ThermoModels.ChanIOFor(); + ThermoModels.ChanIOValFor currThermoIOValFor = new ThermoModels.ChanIOValFor(); + libraryError = numericalControl.PLC_RIOChannelsVal(ref currThermoIOVal, ref currThermoIOFor, ref currThermoIOValFor); + + // setup da config + List listDI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DI).Select(x => new DigInVal() + { + Id = x.Id, + Value = currThermoIOVal.DI.ContainsKey(x.Id) ? currThermoIOVal.DI[x.Id] : false + }).ToList(); + List listDO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.DO).Select(x => new DigOutVal() + { + Id = x.Id, + ForceEnabled = !x.DisableForce, + Value = currThermoIOVal.DO.ContainsKey(x.Id) ? currThermoIOVal.DO[x.Id] : false, + IsForced = currThermoIOFor.DO.ContainsKey(x.Id) ? currThermoIOFor.DO[x.Id] : false, + ForceOne = currThermoIOValFor.DO.ContainsKey(x.Id) ? currThermoIOValFor.DO[x.Id] : false, + ForceZero = currThermoIOValFor.DO.ContainsKey(x.Id) ? !currThermoIOValFor.DO[x.Id] : false + }).ToList(); + List listAI = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AI).Select(x => new AnalInVal() + { + Id = x.Id, + Value = currThermoIOVal.AI.ContainsKey(x.Id) ? currThermoIOVal.AI[x.Id] : 0 + }).ToList(); + List listAO = IOConfig.Where(x => x.Category == Model.Constants.TACT_IO_TYPE.AO).Select(x => new AnalOutVal() + { + Id = x.Id, + ForceEnabled = !x.DisableForce, + Value = currThermoIOVal.AO.ContainsKey(x.Id) ? currThermoIOVal.AO[x.Id] : 0, + IsForced = currThermoIOFor.AO.ContainsKey(x.Id) ? currThermoIOFor.AO[x.Id] : false, + ForcedValue = currThermoIOValFor.AO.ContainsKey(x.Id) ? currThermoIOValFor.AO[x.Id] : 0 + }).ToList(); + + // assegno! + currChannelsIoVal.DI = listDI; + currChannelsIoVal.DO = listDO; + currChannelsIoVal.AI = listAI; + currChannelsIoVal.AO = listAO; + } + return libraryError; + } + /// /// Get all warmers data by channel /// @@ -3231,6 +3237,82 @@ namespace Thermo.Active.NC return libraryError; } + public CmsError RefreshAlarm(uint id) + { + // Write in memory the request to refresh the alarm + return numericalControl.PLC_WRefreshMessage(id); + } + + public CmsError RefreshAllAlarms() + { + return numericalControl.PLC_WRefreshAllMessages(); + } + + public bool ResetHeadWTime(int Head) + { + CmsError libraryError = numericalControl.PLC_WResetWorkedTimeHead(Head); + if (libraryError.IsError()) + return false; + + return true; + } + + public bool ResetMachineWTime(uint hour) + { + CmsError libraryError = numericalControl.PLC_WResetWorkedTimeMachine(hour); + if (libraryError.IsError()) + return false; + + return true; + } + + public bool ResetMaintenanceCounter(uint counter) + { + CmsError libraryError = numericalControl.PLC_WResetMachineCounters(counter); + if (libraryError.IsError()) + return false; + + return true; + } + + public CmsError RestoreAlarm(uint id) + { + // Write in memory the request to restore the alarm + return numericalControl.PLC_WRestoreMessage(id); + } + + public CmsError SendTCamImageReadyStrb() + { + return numericalControl.PLC_WStrFlirAcquired(); + } + + public CmsError SetActiveLanguage(CultureInfo language) + { + //if(NC_VENDOR.OSAI) + //// Set to true power on data by id + //return numericalControl.NC_WLanguage(language); + + return NO_ERROR; + } + + public CmsError SetActiveScreen(short screen) + { + // Set to true power on data by id + return numericalControl.NC_SetScreenVisible((NcThermo.SCREEN_PAGE)screen); + } + + public NcThermo SetNumericalControl() + { + // Return new Numerical control instance choosed from the configuration + switch (NcConfig.NcVendor) + { + case NC_VENDOR.S7NET: + return new Nc_S7Net(NcConfig.NcIpAddress, NcConfig.NcPort, 2000); + } + + return null; + } + /// /// Get historical prodinfo data from DB /// @@ -3323,11 +3405,97 @@ namespace Thermo.Active.NC return libraryError; } + /// + /// ChannelsID: write AO to PLC (values + setForce) + /// + /// Oggetto parametri da aggiornare (from HMI) + /// + public CmsError Write_IO_AO_ToPLC(Dictionary newValues) + { + // solo x S7... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + // scrivo! + CmsError libraryError = numericalControl.PLC_W_IO_AO_Val(newValues); + if (libraryError.IsError()) + return libraryError; + } + else + { + return FUNCTION_NOT_ALLOWED_ERROR; + } + return NO_ERROR; + } + + /// + /// ChannelsID: write DO to PLC (values + setForce) + /// + /// Oggetto parametri da aggiornare (from HMI) + /// + public CmsError Write_IO_DO_ToPLC(Dictionary newValues) + { + // solo x S7... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + // scrivo! + CmsError libraryError = numericalControl.PLC_W_IO_DO_Val(newValues); + if (libraryError.IsError()) + return libraryError; + } + else + { + return FUNCTION_NOT_ALLOWED_ERROR; + } + return NO_ERROR; + } + + public void WriteCandy(DateTime value, int machNumber) + { + long nDays; + long Lic = 0; + nDays = (value.Ticks / TimeSpan.TicksPerDay); + + //Imposto nel registro + CandiesController.SetPCLincense(machNumber, nDays); + + //Imposto nel CN + Lic = long.Parse(CandiesController.SetLincenseFromData(machNumber, nDays)); + numericalControl.PLC_WCandy(Lic); + } + + /// + /// Scrive le softkey star + /// + /// Softkey ID of the first button + /// Softkey ID of the second button + /// + public CmsError WriteKeyboardStarSoftkey(int idkey1, int idkey2) + { + int val1 = 0; + int val2 = 0; + + UserSoftKeyConfigModel userSoftkey1 = SoftKeysConfig.Where(X => X.Id == idkey1).FirstOrDefault(); + UserSoftKeyConfigModel userSoftkey2 = SoftKeysConfig.Where(X => X.Id == idkey2).FirstOrDefault(); + if (userSoftkey1 != null) + val1 = userSoftkey1.PlcId; + if (userSoftkey2 != null) + val2 = userSoftkey2.PlcId; + + CmsError libraryError = numericalControl.PLC_WKeyboardSoftkey((ushort)val1, (ushort)val2); + + return libraryError; + } + public CmsError WriteM154Ack(int processId) { return numericalControl.PLC_W154ManageAck(processId); } + public CmsError WriteM155Data(int process, double responseValue) + { + return numericalControl.PLC_WOperatorInputResponse(process, responseValue); + } + public CmsError WriteM156Data(int process, double responseValue) { return numericalControl.PLC_WM156Response(process, responseValue); @@ -3377,148 +3545,6 @@ namespace Thermo.Active.NC return libraryError; } - - /// - /// ChannelsID: write DO to PLC (values + setForce) - /// - /// Oggetto parametri da aggiornare (from HMI) - /// - public CmsError Write_IO_DO_ToPLC(Dictionary newValues) - { - // solo x S7... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - // scrivo! - CmsError libraryError = numericalControl.PLC_W_IO_DO_Val(newValues); - if (libraryError.IsError()) - return libraryError; - } - else - { - return FUNCTION_NOT_ALLOWED_ERROR; - } - return NO_ERROR; - } - /// - /// ChannelsID: write AO to PLC (values + setForce) - /// - /// Oggetto parametri da aggiornare (from HMI) - /// - public CmsError Write_IO_AO_ToPLC(Dictionary newValues) - { - // solo x S7... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - // scrivo! - CmsError libraryError = numericalControl.PLC_W_IO_AO_Val(newValues); - if (libraryError.IsError()) - return libraryError; - } - else - { - return FUNCTION_NOT_ALLOWED_ERROR; - } - return NO_ERROR; - } - /// - /// ChannelsID: Write RESET (not forced) for DO to PLC (setForce = false) - /// - /// Oggetto parametri da aggiornare (from HMI) - /// - public CmsError WriteReset_IO_DO_ToPLC(List channels) - { - // solo x S7... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - Dictionary newForced = new Dictionary(); - foreach (var item in channels) - { - newForced.Add(item, false); - } - // scrivo! - CmsError libraryError = numericalControl.PLC_W_IO_DO_Reset(newForced); - if (libraryError.IsError()) - return libraryError; - } - else - { - return FUNCTION_NOT_ALLOWED_ERROR; - } - return NO_ERROR; - } - /// - /// ChannelsID: Write RESET (not forced) for AO to PLC (setForce = false) - /// - /// Oggetto parametri da aggiornare (from HMI) - /// - public CmsError WriteReset_IO_AO_ToPLC(List channels) - { - // solo x S7... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - Dictionary newForced = new Dictionary(); - foreach (var item in channels) - { - newForced.Add(item, false); - } - // scrivo! - CmsError libraryError = numericalControl.PLC_W_IO_AO_Reset(newForced); - if (libraryError.IsError()) - return libraryError; - } - else - { - return FUNCTION_NOT_ALLOWED_ERROR; - } - return NO_ERROR; - } - /// - /// ChannelsID: Write RESET (not forced) for DO + AO to PLC (setForce = false) - /// - /// Oggetto parametri da aggiornare (from HMI) - /// num max parametri da scrivere singolarmente - /// delay in scrittura multi parametri singoli - /// - public CmsError WriteReset_IO_ALL_ToPLC() - { - // solo x S7... - if (NcConfig.NcVendor == NC_VENDOR.S7NET) - { - // scrivo! - CmsError libraryError = numericalControl.PLC_W_IO_ResetAll(); - if (libraryError.IsError()) - return libraryError; - } - else - { - return FUNCTION_NOT_ALLOWED_ERROR; - } - return NO_ERROR; - } - - /// - /// Scrive le softkey star - /// - /// Softkey ID of the first button - /// Softkey ID of the second button - /// - public CmsError WriteKeyboardStarSoftkey(int idkey1, int idkey2) - { - int val1 = 0; - int val2 = 0; - - UserSoftKeyConfigModel userSoftkey1 = SoftKeysConfig.Where(X => X.Id == idkey1).FirstOrDefault(); - UserSoftKeyConfigModel userSoftkey2 = SoftKeysConfig.Where(X => X.Id == idkey2).FirstOrDefault(); - if (userSoftkey1 != null) - val1 = userSoftkey1.PlcId; - if (userSoftkey2 != null) - val2 = userSoftkey2.PlcId; - - CmsError libraryError = numericalControl.PLC_WKeyboardSoftkey((ushort)val1, (ushort)val2); - - return libraryError; - } - /// /// Write all warmers load for recipe /// @@ -3642,86 +3668,82 @@ namespace Thermo.Active.NC return libraryError; } - #endregion Read Data - - #region Write data - - public CmsError ManageFlirStrobe() + /// + /// ChannelsID: Write RESET (not forced) for DO + AO to PLC (setForce = false) + /// + /// Oggetto parametri da aggiornare (from HMI) + /// num max parametri da scrivere singolarmente + /// delay in scrittura multi parametri singoli + /// + public CmsError WriteReset_IO_ALL_ToPLC() { - return numericalControl.PLC_WAckFlirRequest(); - } - - public CmsError PutOverride(uint id, string action) - { - HEAD_OVERRIDE_SIGN sign = HEAD_OVERRIDE_SIGN.MINUS; - if (action == "plus") - sign = HEAD_OVERRIDE_SIGN.PLUS; - - return numericalControl.PLC_WHeadOverride(id, sign); - } - - public CmsError PutPowerOnData(uint id) - { - // Set to true power on data by id - return numericalControl.PLC_WPowerOnData(id, true); - } - - public CmsError PutSelectAxis(byte axisId) - { - return numericalControl.AXES_WSelectAxis(axisId); - } - - public CmsError PutSelectProcess(ushort procNumber) - { - return numericalControl.PROC_WSelectProcess(procNumber); - } - - public CmsError PutUserSoftKeyClick(uint id) - { - // Write user softkey press to plc - return numericalControl.PLC_WUserSoftKey(id); - } - - public CmsError RefreshAlarm(uint id) - { - // Write in memory the request to refresh the alarm - return numericalControl.PLC_WRefreshMessage(id); - } - - public CmsError RefreshAllAlarms() - { - return numericalControl.PLC_WRefreshAllMessages(); - } - - public CmsError RestoreAlarm(uint id) - { - // Write in memory the request to restore the alarm - return numericalControl.PLC_WRestoreMessage(id); - } - - public CmsError SendTCamImageReadyStrb() - { - return numericalControl.PLC_WStrFlirAcquired(); - } - - public CmsError SetActiveLanguage(CultureInfo language) - { - //if(NC_VENDOR.OSAI) - //// Set to true power on data by id - //return numericalControl.NC_WLanguage(language); - + // solo x S7... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + // scrivo! + CmsError libraryError = numericalControl.PLC_W_IO_ResetAll(); + if (libraryError.IsError()) + return libraryError; + } + else + { + return FUNCTION_NOT_ALLOWED_ERROR; + } return NO_ERROR; } - public CmsError SetActiveScreen(short screen) + /// + /// ChannelsID: Write RESET (not forced) for AO to PLC (setForce = false) + /// + /// Oggetto parametri da aggiornare (from HMI) + /// + public CmsError WriteReset_IO_AO_ToPLC(List channels) { - // Set to true power on data by id - return numericalControl.NC_SetScreenVisible((NcThermo.SCREEN_PAGE)screen); + // solo x S7... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + Dictionary newForced = new Dictionary(); + foreach (var item in channels) + { + newForced.Add(item, false); + } + // scrivo! + CmsError libraryError = numericalControl.PLC_W_IO_AO_Reset(newForced); + if (libraryError.IsError()) + return libraryError; + } + else + { + return FUNCTION_NOT_ALLOWED_ERROR; + } + return NO_ERROR; } - public CmsError WriteM155Data(int process, double responseValue) + /// + /// ChannelsID: Write RESET (not forced) for DO to PLC (setForce = false) + /// + /// Oggetto parametri da aggiornare (from HMI) + /// + public CmsError WriteReset_IO_DO_ToPLC(List channels) { - return numericalControl.PLC_WOperatorInputResponse(process, responseValue); + // solo x S7... + if (NcConfig.NcVendor == NC_VENDOR.S7NET) + { + Dictionary newForced = new Dictionary(); + foreach (var item in channels) + { + newForced.Add(item, false); + } + // scrivo! + CmsError libraryError = numericalControl.PLC_W_IO_DO_Reset(newForced); + if (libraryError.IsError()) + return libraryError; + } + else + { + return FUNCTION_NOT_ALLOWED_ERROR; + } + return NO_ERROR; } public CmsError WriteScada(string memIndex, SCADA_MEM_TYPE memType, object value) @@ -3729,20 +3751,6 @@ namespace Thermo.Active.NC return numericalControl.PLC_WScadaValue(memIndex, memType, value); } - #endregion Write data - - public void WriteCandy(DateTime value, int machNumber) - { - long nDays; - long Lic = 0; - nDays = (value.Ticks / TimeSpan.TicksPerDay); - - //Imposto nel registro - CandiesController.SetPCLincense(machNumber, nDays); - - //Imposto nel CN - Lic = long.Parse(CandiesController.SetLincenseFromData(machNumber, nDays)); - numericalControl.PLC_WCandy(Lic); - } + #endregion Public Methods } } \ No newline at end of file From 72a5ff18798a1de5eb82049550247a2a5b3f8d5d Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Wed, 17 Feb 2021 19:20:22 +0100 Subject: [PATCH 14/15] new rel number --- Thermo.Active/Properties/AssemblyInfo.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Thermo.Active/Properties/AssemblyInfo.cs b/Thermo.Active/Properties/AssemblyInfo.cs index 354b939c..37bb4a3a 100644 --- a/Thermo.Active/Properties/AssemblyInfo.cs +++ b/Thermo.Active/Properties/AssemblyInfo.cs @@ -30,4 +30,4 @@ using System.Runtime.InteropServices; // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: -[assembly: AssemblyVersion("1.1.159")] +[assembly: AssemblyVersion("1.1.160")] From cffb93d09d6137354db48c2389e766b796eb4314 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Wed, 17 Feb 2021 19:51:56 +0100 Subject: [PATCH 15/15] metodo fake x recupero temp da lista punti --- .../ConfigModels/RiskConfigModel.cs | 10 +-- .../DTOModels/ThWarmers/DTOThermoCam.cs | 20 +++-- .../DTOModels/ThWarmers/ThermoPoint.cs | 28 ++++++- .../WebApi/ThermocameraController.cs | 76 +++++++++++++++---- 4 files changed, 107 insertions(+), 27 deletions(-) diff --git a/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs b/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs index 930834b4..b0d36900 100644 --- a/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs +++ b/Thermo.Active.Model/ConfigModels/RiskConfigModel.cs @@ -44,26 +44,26 @@ namespace Thermo.Active.Model.ConfigModels #region Public Fields public int Canale; - public int Riga; - public int Tipo; public int IdGruppo; + public int Riga; + public int Tipo; #endregion Public Fields } public class RiskResistModel { - #region Public Fields + #region Public Properties public int Column { get; set; } = 0; public int Dimension { get; set; } = 0; public int Id { get; set; } = 0; public int IdChannel { get; set; } = 0; - public int IdReflector { get; set; } = 0; public int IdGroup { get; set; } = 0; + public int IdReflector { get; set; } = 0; public int Row { get; set; } = 0; - #endregion Public Fields + #endregion Public Properties } public class RiskRiferimenti diff --git a/Thermo.Active.Model/DTOModels/ThWarmers/DTOThermoCam.cs b/Thermo.Active.Model/DTOModels/ThWarmers/DTOThermoCam.cs index 91c0ea01..d5272b0c 100644 --- a/Thermo.Active.Model/DTOModels/ThWarmers/DTOThermoCam.cs +++ b/Thermo.Active.Model/DTOModels/ThWarmers/DTOThermoCam.cs @@ -8,19 +8,27 @@ namespace Thermo.Active.Model.DTOModels.ThWarmers { public class DTOThermoCam { - /// - /// Opzione ThermoCamera (set by PLC) - /// - public bool ThermoOptionActive { get; set; } = false; + #region Public Properties + /// /// Modalità ThermoCamera (set by HMI) /// public bool ThermoCamMode { get; set; } = false; + /// /// Funzionamento ThermoCamera (set by HMI) /// public bool ThermoCamOnOff { get; set; } = false; + /// + /// Opzione ThermoCamera (set by PLC) + /// + public bool ThermoOptionActive { get; set; } = false; + + #endregion Public Properties + + #region Public Methods + /// /// Equality test for class object /// @@ -49,5 +57,7 @@ namespace Thermo.Active.Model.DTOModels.ThWarmers { return base.GetHashCode(); } + + #endregion Public Methods } -} +} \ No newline at end of file diff --git a/Thermo.Active.Model/DTOModels/ThWarmers/ThermoPoint.cs b/Thermo.Active.Model/DTOModels/ThWarmers/ThermoPoint.cs index 35a7e476..edc04c5e 100644 --- a/Thermo.Active.Model/DTOModels/ThWarmers/ThermoPoint.cs +++ b/Thermo.Active.Model/DTOModels/ThWarmers/ThermoPoint.cs @@ -6,16 +6,42 @@ using System.Threading.Tasks; namespace Thermo.Active.Model.DTOModels.ThWarmers { + public class PointReq + { + #region Public Properties + + public List List { get; set; } = new List(); + + #endregion Public Properties + } + public class ThermoPoint { + #region Public Properties + public int X { get; set; } = 0; public int Y { get; set; } = 0; + #endregion Public Properties + + #region Public Methods + public static int distance(ThermoPoint a, ThermoPoint b) { int answ = 0; answ = (int)Math.Sqrt(Math.Pow((a.X - b.X), 2) + Math.Pow((a.Y - b.Y), 2)); return answ; } + + #endregion Public Methods } -} + + public class ThermoPointFlir : ThermoPoint + { + #region Public Properties + + public float Temperature { get; set; } = 0; + + #endregion Public Properties + } +} \ No newline at end of file diff --git a/Thermo.Active/Controllers/WebApi/ThermocameraController.cs b/Thermo.Active/Controllers/WebApi/ThermocameraController.cs index 2738f8c9..1ad7d506 100644 --- a/Thermo.Active/Controllers/WebApi/ThermocameraController.cs +++ b/Thermo.Active/Controllers/WebApi/ThermocameraController.cs @@ -1,20 +1,13 @@ -using System; +using CMS_CORE_Library.Models; +using System; using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Security.Claims; -using System.Text; -using System.Threading.Tasks; using System.Web.Http; -using Thermo.Active.Database.Controllers; -using Thermo.Active.Listeners; -using Thermo.Active.Model.DatabaseModels; -using Thermo.Active.Model.DTOModels.AlarmModels; +using System.Web.Http.Description; +using Thermo.Active.Model.DTOModels.ThWarmers; +using Thermo.Active.NC; using Thermo.Active.Provider; using Thermo.Active.Thermocamera; +using Thermo.Active.Utils; using static Thermo.Active.Config.ServerConfig; using static Thermo.Active.Model.Constants; @@ -23,6 +16,57 @@ namespace Thermo.Active.Controllers.WebApi [RoutePrefix("api/thermocamera")] public class ThermocameraController : ApiController { + #region Protected Fields + + /// + /// Oggetto adapter condiviso da WebAPI + /// + protected static NcAdapter ncAdapter = new NcAdapter(); + + #endregion Protected Fields + + #region Public Methods + + [ResponseType(typeof(PointReq))] + [Route("getTemperatures"), HttpGet] + public IHttpActionResult GetTempAtPoints(PointReq pointRequest) + { + // Try connection + CmsError libraryError = ncAdapter.Connect(); + if (libraryError.IsError()) + { + ThermoActiveLogger.LogError($"NC Not connected! | GetTempAtPoints | {libraryError.exception}"); + return BadRequest(libraryError.localizationKey); + } + + PointReq results = new PointReq(); + // fake: genero casualmenteEsegui + Random rnd = new Random(); + int numval = pointRequest != null && pointRequest.List != null && pointRequest.List.Count > 0 ? pointRequest.List.Count : 10; + for (int i = 0; i < numval; i++) + { + ThermoPointFlir newVal = new ThermoPointFlir() + { + X = rnd.Next(0, 1500), + Y = rnd.Next(0, 1200), + Temperature = ((float)rnd.Next(100, 2000)) / 10 + }; + results.List.Add(newVal); + } +#if false + // leggo dati gauges + libraryError = ncAdapter.ReadValIO(out DTOChannelsIOVal ChannelsIOVal); + if (libraryError.IsError()) + { + ThermoActiveLogger.LogError($"GetChannelsIoVal error | {libraryError.exception}"); + return BadRequest(libraryError.localizationKey); + } +#endif + + // ritorno! + return Ok(results); + } + [Route("show"), HttpPost] public IHttpActionResult showCamera() { @@ -30,16 +74,16 @@ namespace Thermo.Active.Controllers.WebApi String ThermoCameraYpos = AdditionalParametersConfig["ThermoCameraYpos"]; String ThermoCameraXdim = AdditionalParametersConfig["ThermoCameraXdim"]; String ThermoCameraYdim = AdditionalParametersConfig["ThermoCameraYdim"]; - if(ThermoCameraXpos != null && ThermoCameraYpos != null && ThermoCameraXdim != null && ThermoCameraYdim != null) + if (ThermoCameraXpos != null && ThermoCameraYpos != null && ThermoCameraXdim != null && ThermoCameraYdim != null) { - if (ThermocameraComunicator.getInstance().showWindow(Int32.Parse(ThermoCameraXpos), Int32.Parse(ThermoCameraYpos), Int32.Parse(ThermoCameraXdim), Int32.Parse(ThermoCameraYdim), 3000)) return Ok(); else return BadRequest(); - } return BadRequest(); } + + #endregion Public Methods } } \ No newline at end of file