Compare commits

...
Author SHA1 Message Date
michal 7d15073bb5 improve logs and added try, catch blocks 2024-11-14 13:05:33 +01:00
Milan Hanajik 79be186bef Reconfigured for Bari 2023-08-09 12:36:41 +02:00
3 changed files with 301 additions and 214 deletions
+206 -145
View File
@@ -1,6 +1,7 @@
/// ///
/// Copyright (c) 2017 Sensus Slovensko a.s. /// Copyright (c) 2017 Sensus Slovensko a.s.
/// ///
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using log4net; using log4net;
@@ -11,45 +12,49 @@ using System.IO;
namespace TBF.Rig.Network.Camera.CLP1611 namespace TBF.Rig.Network.Camera.CLP1611
{ {
public class GrabImagesOp : IOperation public class GrabImagesOp : IOperation
{ {
/// TODO: Implement support for grabbing multiple images, now imgFileNames.Lenght should be 1 /// TODO: Implement support for grabbing multiple images, now imgFileNames.Lenght should be 1
private static readonly ILog log = LogManager.GetLogger(typeof(GrabImagesOp));
private static readonly ILog log = LogManager.GetLogger(typeof(GrabImagesOp)); public override string ToString()
public override string ToString() { return string.Format("GrabImageOp()"); } {
return string.Format("GrabImageOp()");
}
readonly Camera camera; readonly Camera camera;
readonly Telnet.TelnetClient telnet; readonly Telnet.TelnetClient telnet;
readonly string[] imgFileNames; readonly string[] imgFileNames;
readonly bool blackAndWhite; readonly bool blackAndWhite;
readonly bool lowResolution; readonly bool lowResolution;
readonly ImageRotation imageRotation; readonly ImageRotation imageRotation;
string command; string command;
bool grabImageCommandSent; bool grabImageCommandSent;
string response; string response;
bool grabPassed; bool grabPassed;
bool grabFailed; bool grabFailed;
bool transferringGrabbedImage; bool transferringGrabbedImage;
/// <summary> /// <summary>
/// Events: Event.None or Event.Error /// Events: Event.None or Event.Error
/// </summary> /// </summary>
/// <param name="camera">CLP1611.Camera reference</param> /// <param name="camera">CLP1611.Camera reference</param>
public GrabImagesOp(Camera camera, string[] imgFileNames, bool blackAndWhite, bool lowResolution, ImageRotation imageRotation) public GrabImagesOp(Camera camera, string[] imgFileNames, bool blackAndWhite, bool lowResolution,
{ ImageRotation imageRotation)
/// TODO: Implement support for grabbing multiple images, now imgFileNames.Lenght should be 1 {
/// TODO: Implement support for grabbing multiple images, now imgFileNames.Lenght should be 1
this.camera = camera; this.camera = camera;
this.telnet = camera.Telnet; this.telnet = camera.Telnet;
this.imgFileNames = imgFileNames; this.imgFileNames = imgFileNames;
this.blackAndWhite = blackAndWhite; this.blackAndWhite = blackAndWhite;
this.lowResolution = lowResolution; this.lowResolution = lowResolution;
this.imageRotation = imageRotation; this.imageRotation = imageRotation;
grabImageCommandSent = false; grabImageCommandSent = false;
transferringGrabbedImage = false; transferringGrabbedImage = false;
if (camera.DebugLevel == DebugMode.Normal || camera.DebugLevel == DebugMode.DetectedOn) if (camera.DebugLevel == DebugMode.Normal || camera.DebugLevel == DebugMode.DetectedOn)
{ {
@@ -58,46 +63,62 @@ namespace TBF.Rig.Network.Camera.CLP1611
OnPromptReceived(sndr, a); OnPromptReceived(sndr, a);
}; };
} }
} }
void OnPromptReceived(object sndr, PromptReceivedEventArgs a) void OnPromptReceived(object sndr, PromptReceivedEventArgs a)
{ {
response = a.Response; response = a.Response;
/// TODO /// TODO
} }
public void Start() public void Start()
{ {
grabImageCommandSent = false; grabImageCommandSent = false;
transferringGrabbedImage = false; transferringGrabbedImage = false;
if ((imgFileNames != null) && (imgFileNames.Length > 0) && File.Exists(imgFileNames[0])) if ((imgFileNames != null) && (imgFileNames.Length > 0) && File.Exists(imgFileNames[0]))
{ {
/// ///
/// An image specified, (1) delete previous image, (2) check if this is a simulation /// An image specified, (1) delete previous image, (2) check if this is a simulation
/// ///
File.Delete(imgFileNames[0]); try
{
File.Delete(imgFileNames[0]);
}
catch (Exception e)
{
log.ErrorFormat("Celan up failed! Delete file atempt {0} failed! Detail: {1}", imgFileNames[0], e.StackTrace);
}
if (camera.CameraCfg.DebugLevel == DebugMode.Simulate || camera.CameraCfg.DebugLevel == DebugMode.DetectedOff) if (camera.CameraCfg.DebugLevel == DebugMode.Simulate ||
camera.CameraCfg.DebugLevel == DebugMode.DetectedOff)
{ {
/// ///
/// Camera is in simulation mode => create a simulated image /// Camera is in simulation mode => create a simulated image
/// ///
File.Copy(string.Format("{0}\\Pictures\\sample.jpg", Program.ExecutableDir), imgFileNames[0]);
try
{
File.Copy(string.Format("{0}\\Pictures\\sample.jpg", Program.ExecutableDir), imgFileNames[0]);
}
catch (Exception e)
{
log.ErrorFormat("Simulation/DetectedOff file copy to {0} failed! Deatil: {1}", imgFileNames[0], e.StackTrace);
}
} }
} }
} }
public Event Run() public Event Run()
{ {
if ((imgFileNames == null) || (imgFileNames.Length < 1) || (imgFileNames[0] == null)) if ((imgFileNames == null) || (imgFileNames.Length < 1) || (imgFileNames[0] == null))
{ {
/// ///
/// No images to be grabbed => Done /// No images to be grabbed => Done
/// ///
return Event.GrabPassed; return Event.GrabPassed;
} }
else if (camera.CameraCfg.DebugLevel == DebugMode.Simulate || else if (camera.CameraCfg.DebugLevel == DebugMode.Simulate ||
camera.CameraCfg.DebugLevel == DebugMode.DetectedOff) camera.CameraCfg.DebugLevel == DebugMode.DetectedOff)
{ {
@@ -107,118 +128,158 @@ namespace TBF.Rig.Network.Camera.CLP1611
return Event.GrabPassed; return Event.GrabPassed;
} }
else if (!grabImageCommandSent) else if (!grabImageCommandSent)
{ {
/// ///
/// Normal operation, no command sent yet => (1) wait until telnet state = Inactive, (2) send a command /// Normal operation, no command sent yet => (1) wait until telnet state = Inactive, (2) send a command
/// ///
if (camera.Running && (telnet.State == TelnetClient.TelnetState.Inactive)) try
{ {
/// if (camera.Running && (telnet.State == TelnetClient.TelnetState.Inactive))
/// State variables {
/// ///
response = null; /// State variables
///
response = null;
/// ///
/// Prepare a command /// Prepare a command
/// ///
int rotation = 0; int rotation = 0;
if (imageRotation == ImageRotation.Deg90) if (imageRotation == ImageRotation.Deg90)
rotation = 90; rotation = 90;
else if (imageRotation == ImageRotation.Deg180) else if (imageRotation == ImageRotation.Deg180)
rotation = 180; rotation = 180;
else if (imageRotation == ImageRotation.Deg270) else if (imageRotation == ImageRotation.Deg270)
rotation = 270; rotation = 270;
command = string.Format("clp/GrabImage {0} {1} -r {2} {3} -n 1 {4}", command = string.Format("clp/GrabImage {0} {1} -r {2} {3} -n 1 {4}",
blackAndWhite ? "-bmp" : "-bmp", /// 0 ... file format and quality blackAndWhite ? "-bmp" : "-bmp", /// 0 ... file format and quality
blackAndWhite ? "-y8" : "-rgb", /// 1 ... B&W / color blackAndWhite ? "-y8" : "-rgb", /// 1 ... B&W / color
rotation.ToString(), /// 2 ... roration rotation.ToString(), /// 2 ... roration
lowResolution ? "-lr" : "-hr", /// 4 ... resolution lowResolution ? "-lr" : "-hr", /// 4 ... resolution
"grabbed.bmp"); /// 5 ... filename "grabbed.bmp"); /// 5 ... filename
// //
// Send (or enqueue) command // Send (or enqueue) command
// //
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.CLEAR_RESPONSE)); telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.CLEAR_RESPONSE));
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, command)); telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, command));
grabImageCommandSent = true; grabImageCommandSent = true;
log.WarnFormat("{0} IP={1} command={2}", camera.Name, camera.IPAddress, command); log.WarnFormat("{0} IP={1} command={2}", camera.Name, camera.IPAddress, command);
}
} }
return Event.CameraBusy; catch (Exception e)
} {
else if (grabPassed) if (camera == null)
{ {
log.Error("Failed stand up from camera inactive status! Detail: " + e.StackTrace);
}
else
{
log.ErrorFormat("Failed stand up from camera inactive status! {0} IP={1} command={2} ! Detail: {3}", camera.Name, camera.IPAddress, command, e.StackTrace);
}
return Event.CameraBusy;
}
return Event.CameraBusy;
}
else if (grabPassed)
{
/// ///
/// Normal operation, grab passed => transfer/transferring the image /// Normal operation, grab passed => transfer/transferring the image
/// ///
if (transferringGrabbedImage) try
{ {
/// Grab passed and image transfer is in progress if (transferringGrabbedImage)
return Event.GrabPassed; {
} /// Grab passed and image transfer is in progress
else if (0 == camera.DownloadFile(blackAndWhite ? "grabbed.jpg" : "grabbed.bmp", imgFileNames[0])) return Event.GrabPassed;
{ }
/// File transfer successfully started else if (0 == camera.DownloadFile(blackAndWhite ? "grabbed.jpg" : "grabbed.bmp", imgFileNames[0]))
transferringGrabbedImage = true; {
return Event.GrabPassed; /// File transfer successfully started
} transferringGrabbedImage = true;
else return Event.GrabPassed;
{ }
/// Wait until the previous image transfer completes else
return Event.CameraBusy; {
} /// Wait until the previous image transfer completes
} return Event.CameraBusy;
else if (grabFailed) }
{ }
catch (Exception e)
{
log.ErrorFormat("Somtehing get wrong with DownloadFile - grabbed.jpg or .bmp to {0}! Detials: {1}",imgFileNames[0], e.StackTrace);
return Event.CameraBusy;
}
}
else if (grabFailed)
{
/// ///
/// Normal operation, grab failed => there in no image to transfer /// Normal operation, grab failed => there in no image to transfer
/// ///
return Event.GrabFailed; return Event.GrabFailed;
} }
else if (response != null) else if (response != null)
{ {
/// ///
/// Normal operation /// Normal operation
/// ///
if (response.Contains("completed")) if (response.Contains("completed"))
{ {
grabPassed = true; grabPassed = true;
/// try
/// Start the file transfer {
/// ///
if (0 == camera.DownloadFile(blackAndWhite ? "grabbed.jpg" : "grabbed.bmp", imgFileNames[0])) /// Start the file transfer
{ ///
/// File transfer successfully started if (0 == camera.DownloadFile(blackAndWhite ? "grabbed.jpg" : "grabbed.bmp",
transferringGrabbedImage = true; imgFileNames[0]))
return Event.GrabPassed; {
} /// File transfer successfully started
else transferringGrabbedImage = true;
{ return Event.GrabPassed;
return Event.CameraBusy; /// File transfer not started yet }
} else
} {
else return Event.CameraBusy; /// File transfer not started yet
{ }
grabFailed = true; }
return Event.GrabFailed; catch (Exception e)
} {
} log.ErrorFormat("Sometihing get wrong! Detail:{0}", e.StackTrace);
else return Event.CameraBusy;
{ }
return Event.CameraBusy; }
} else
} {
grabFailed = true;
public void Stop() return Event.GrabFailed;
{ }
if (camera.CameraCfg.DebugLevel == DebugMode.Simulate) return;
if (grabImageCommandSent)
{
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, Telnet.TelnetClient.CtrlCCommand));
log.WarnFormat("{0} IP={1} command=CTRL-C", camera.Name, camera.IPAddress);
} }
} else
} {
return Event.CameraBusy;
}
}
public void Stop()
{
if (camera.CameraCfg.DebugLevel == DebugMode.Simulate) return;
if (grabImageCommandSent)
{
try
{
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, Telnet.TelnetClient.CtrlCCommand));
log.WarnFormat("{0} IP={1} command=CTRL-C", camera.Name, camera.IPAddress);
}
catch (Exception e)
{
log.ErrorFormat("Failed {0} IP={1} command=CTRL-C! Detail: {2}", camera.Name, camera.IPAddress, e.StackTrace);
}
}
}
}
} }
+89 -63
View File
@@ -92,52 +92,69 @@ namespace TBF.Rig.Network.Camera.Roi
string masks = string.Empty; string masks = string.Empty;
Roi previous = roi.PreviousRoi; Roi previous = roi.PreviousRoi;
int maskLevel = 0; int maskLevel = 0;
while (previous != null && maskLevel++ < 3)
try
{ {
if (!previous.Detected) while (previous != null && maskLevel++ < 3)
{ {
previousFailed = true; if (!previous.Detected)
return Event.RoiDetectionPreviousFailed; {
previousFailed = true;
return Event.RoiDetectionPreviousFailed;
}
masks += string.Format(" -m {0} {1} {2} {3}", previous.RoiX.Val, previous.RoiY.Val,
previous.RoiWid.Val, previous.RoiHgh.Val);
previous = previous.PreviousRoi;
} }
masks += string.Format(" -m {0} {1} {2} {3}", previous.RoiX.Val, previous.RoiY.Val, command = string.Format("clp/RoiDetection{0}{1}{2}{3}{4} {5}",
previous.RoiWid.Val, previous.RoiHgh.Val); masks,
previous = previous.PreviousRoi; string.Format(roiCfg.LoadImages ? " -l {0}" : " -n {0}", roiCfg.DetectionImagesCount),
} roiCfg.SaveImages ? " -s -jpg" : "",
command = string.Format("clp/RoiDetection{0}{1}{2}{3}{4} {5}", string.Format(" -p1 {0}", roiCfg.DetectionPeriod1),
masks, string.Format(" -p2 {0}", roiCfg.DetectionPeriod2),
string.Format(roiCfg.LoadImages ? " -l {0}" : " -n {0}", roiCfg.DetectionImagesCount), roiCfg.RoiParams);
roiCfg.SaveImages ? " -s -jpg" : "",
string.Format(" -p1 {0}", roiCfg.DetectionPeriod1),
string.Format(" -p2 {0}", roiCfg.DetectionPeriod2),
roiCfg.RoiParams);
// //
// Send (or enqueue) command // Send (or enqueue) command
// //
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.CLEAR_RESPONSE)); telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.CLEAR_RESPONSE));
telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, command)); telnet.Enqueue(new Telnet.Command(Telnet.CmdAction.SEND_COMMAND, command));
roiDetectionCommandSent = true; roiDetectionCommandSent = true;
log.WarnFormat("{0}/{1} command={2}", roiCfg.Name, camera.Name, command); log.WarnFormat("{0}/{1} command={2}", roiCfg.Name, camera.Name, command);
} }
catch (Exception e)
{
log.ErrorFormat("Something wrong in start! Command: {0} ! Details: {1}", command, e.StackTrace);
}
}
return Event.CameraBusy; return Event.CameraBusy;
} }
else if (passed) else if (passed)
{ {
if (transferringDetectedImage) try
{ {
/// ROI detection passed and image transfer is in progress if (transferringDetectedImage)
return Event.RoiDetectionPassed; {
/// ROI detection passed and image transfer is in progress
return Event.RoiDetectionPassed;
}
else if (0 == camera.DownloadFile("detected.jpg", imgFileNamePrefix + "detected.jpg"))
{
/// File transfer successfully started
transferringDetectedImage = true;
return Event.RoiDetectionPassed;
}
else
{
/// Wait until the previous image transfer completes
return Event.CameraBusy;
}
} }
else if (0 == camera.DownloadFile("detected.jpg", imgFileNamePrefix + "detected.jpg")) catch (Exception e)
{ {
/// File transfer successfully started log.ErrorFormat("Someting wrong with DownloadFile(detected.jpg), imgFileNamePrefix: {0}! Details: {1}", imgFileNamePrefix, e.StackTrace);
transferringDetectedImage = true;
return Event.RoiDetectionPassed;
}
else
{
/// Wait until the previous image transfer completes
return Event.CameraBusy; return Event.CameraBusy;
} }
} }
@@ -152,49 +169,58 @@ namespace TBF.Rig.Network.Camera.Roi
} }
else if (response != null) else if (response != null)
{ {
int from = response.IndexOf('['); try
int to = response.IndexOf(']');
if (!response.Contains("RESULT=0\r\n") || from < 0 || to < 0 || to < from)
{ {
roi.ClearRoi(); int from = response.IndexOf('[');
failed = true; int to = response.IndexOf(']');
log.WarnFormat("{0}/{1} Detection failed: {2}", roiCfg.Name, camera.Name, response); if (!response.Contains("RESULT=0\r\n") || from < 0 || to < 0 || to < from)
return Event.RoiDetectionFailed;
}
else
{
string oroiStr = response.Substring(from + 1, to - from - 1);
string[] terms = oroiStr.Split(new char[] { ',' });
int x, y, w, h;
if (terms.Length != 5 || !int.TryParse(terms[0], out x) || !int.TryParse(terms[1], out y)
|| !int.TryParse(terms[2], out w) || !int.TryParse(terms[3], out h))
{ {
roi.ClearRoi(); roi.ClearRoi();
failed = true; failed = true;
log.WarnFormat("{0}/{1} Cannot parse response: {2}", roiCfg.Name, camera.Name, response); log.WarnFormat("{0}/{1} Detection failed: {2}", roiCfg.Name, camera.Name, response);
return Event.RoiDetectionFailed; return Event.RoiDetectionFailed;
} }
else else
{ {
roi.SetRoi(x, y, w, h); string oroiStr = response.Substring(from + 1, to - from - 1);
log.WarnFormat("{0}/{1} Detection PASSED: x={2} y={3} w={4} h={5}", roiCfg.Name, camera.Name, x, y, w, h); string[] terms = oroiStr.Split(new char[] { ',' });
passed = true; int x, y, w, h;
if (terms.Length != 5 || !int.TryParse(terms[0], out x) || !int.TryParse(terms[1], out y)
/// || !int.TryParse(terms[2], out w) || !int.TryParse(terms[3], out h))
/// Start the file transfer
///
if (0 == camera.DownloadFile("detected.jpg", imgFileNamePrefix + "detected.jpg"))
{ {
/// File transfer successfully started roi.ClearRoi();
transferringDetectedImage = true; failed = true;
return Event.RoiDetectionPassed; log.WarnFormat("{0}/{1} Cannot parse response: {2}", roiCfg.Name, camera.Name, response);
return Event.RoiDetectionFailed;
} }
else else
{ {
return Event.CameraBusy; /// File transfer not started yet roi.SetRoi(x, y, w, h);
log.WarnFormat("{0}/{1} Detection PASSED: x={2} y={3} w={4} h={5}", roiCfg.Name,
camera.Name, x, y, w, h);
passed = true;
///
/// Start the file transfer
///
if (0 == camera.DownloadFile("detected.jpg", imgFileNamePrefix + "detected.jpg"))
{
/// File transfer successfully started
transferringDetectedImage = true;
return Event.RoiDetectionPassed;
}
else
{
return Event.CameraBusy; /// File transfer not started yet
}
} }
} }
} }
catch (Exception e)
{
log.ErrorFormat("Error in taken results! Details: {0}", e.StackTrace);
return Event.CameraBusy;
}
} }
else else
{ {
+4 -4
View File
@@ -39,7 +39,7 @@
<DebugType>full</DebugType> <DebugType>full</DebugType>
<Optimize>false</Optimize> <Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants> <DefineConstants>TRACE;DEBUG;CAMERA</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
@@ -50,7 +50,7 @@
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath> <OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE;CAMERA</DefineConstants>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel> <WarningLevel>4</WarningLevel>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
@@ -60,7 +60,7 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
<OutputPath>bin\Debug\</OutputPath> <OutputPath>bin\Debug\</OutputPath>
<DefineConstants>TRACE;DEBUG</DefineConstants> <DefineConstants>TRACE;DEBUG;CAMERA</DefineConstants>
<DebugType>full</DebugType> <DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>
<ErrorReport>prompt</ErrorReport> <ErrorReport>prompt</ErrorReport>
@@ -70,7 +70,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'"> <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath> <OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants> <DefineConstants>TRACE;CAMERA</DefineConstants>
<Optimize>true</Optimize> <Optimize>true</Optimize>
<DebugType>pdbonly</DebugType> <DebugType>pdbonly</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget> <PlatformTarget>AnyCPU</PlatformTarget>