Ejemplo n.º 1
0
        private static Exception Build(Type exType, string msg)
        {
            ConstructorInfo ci = exType.GetConstructor(new Type[] { typeof(string) });

            log.ErrorFormat("{0}: {1}", exType.Name, msg);
            return((Exception)ci.Invoke(new object[] { msg }));
        }
Ejemplo n.º 2
0
        private static Exception Build(Type exType, string msg)
        {
            log.ErrorFormat("{0}: {1}", exType.Name, msg);

            // Try ctor with message
            ConstructorInfo ci = exType.GetConstructor(new Type[] { typeof(string) });

            if (null != ci)
            {
                return((Exception)ci.Invoke(new object[] { msg }));
            }

            // Fall-back
            return(new Exception(exType + ": " + msg));
        }
Ejemplo n.º 3
0
 private static void TestSetParameterToInvalid(string name, object value)
 {
     try
     {
         cam.SetParameter(name, value);
         log.ErrorFormat("Setting {0} to \"{1}\" should have thrown an Exception!", name, value);
     }
     catch (ArgumentException)
     {
         log.InfoFormat("Setting {0} to \"{1}\" expectedly caused an error.", name, value);
     }
     catch (ParameterNotSupportedException)
     {
         log.InfoFormat("Setting {0} to \"{1}\" caused an unexpected error." + Environment.NewLine
                        + "Probably the camera does not support this parameter.", name, value);
         return;
     }
     LogParameterValue(name);
 }
Ejemplo n.º 4
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="Exception">If the file <paramref name="filename"/> is not a MetriCam2 camera DLL.</exception>
        /// <exception cref="NativeDependencyMissingException">If the assembly could not be loaded because of missing a dependency.</exception>
        /// <exception cref="InvalidOperationException">
        /// If the file <paramref name="filename"/> could not be loaded, or
        /// if a file with the same name has been inspected before, or
        /// if no implementations of <see cref="MetriCam2.Camera"/> were found in the assembly.
        /// </exception>
        /// <param name="filename"></param>
        public static void ScanAssembly(string filename)
        {
            log.DebugFormat("ScanAssembly({0})", filename);
            if (!File.Exists(filename))
            {
                log.ErrorFormat("File '{0}' does not exist.", filename);
                return;
            }

            if (!Path.IsPathRooted(filename))
            {
                filename = Path.GetFullPath(filename);
                log.DebugFormat("Updated filename to absolute path: '{0}'.", filename);
            }

            Assembly assembly = null;

            try
            {
                // Try to load the assembly from the given filename
                assembly = Assembly.LoadFile(filename);
            }
            catch (Exception ex)
            {
                log.DebugFormat("    Loading '{0}' failed: {1}. Finding out the reason for failure...", filename, ex.Message);
                DetermineReasonForLoadFailure(filename); // If a reason is found an appropriate Exception is thrown
            }

            if (null == assembly)
            {
                // assembly is only set at the call to .LoadFile. If we end up here we were not able to determine the reason for failure.
                string msg = string.Format("Assembly could not be loaded (for an unknown reason).");
                log.Error(msg);
                throw new InvalidOperationException(msg);
            }

            if (inspectedCameraDllNames.Contains(assembly.GetName().ToString()))
            {
                string msg = "An assembly with the same name has already been inspected.";
                log.Warn(msg);
                throw new InvalidOperationException(msg);
            }

            if (!InspectAssembly(assembly, filename))
            {
                string msg = string.Format("No implementation of MetriCam2.Camera was found in {0}.", filename);
                log.Error(msg);
                throw new InvalidOperationException(msg);
            }
        }
Ejemplo n.º 5
0
 private static FloatImage Compare(FloatImage currentImg, FloatImage oldImg, float thres, int cnt, string channel, MetriLog log)
 {
     if (null != oldImg)
     {
         FloatImage diff = oldImg - currentImg;
         float      sad  = diff.Abs().Sum();
         log.Debug("SAD = " + sad);
         if (sad < thres)
         {
             log.ErrorFormat("Image {0}{1}: SAD ({2}) was below the threshold of {3}.", cnt, channel, sad, thres);
             return(null);
         }
     }
     oldImg = currentImg;
     return(oldImg);
 }
Ejemplo n.º 6
0
        private void ApplyConfiguration()
        {
            log.EnterMethod();

            int nrChannelsBeforeConfigurationChange = camera.Channels.Count;

            List <string> channelsNotDeactivated = new List <string>();
            List <string> channelsNotActivated   = new List <string>();

            // BUG: If currently selected channel will be deactivated, then we are in trouble

            Task channelsTask = Task.Factory.StartNew(() =>
            {
                log.Debug("Deactivate unchecked channels");
                for (int i = 0; i < checkedListBoxChannels.Items.Count; i++)
                {
                    var item       = checkedListBoxChannels.Items[i];
                    string channel = item.ToString();
                    if (!checkedListBoxChannels.CheckedItems.Contains(item))
                    {
                        try
                        {
                            camera.DeactivateChannel(channel);
                        }
                        catch (Exception ex)
                        {
                            log.ErrorFormat("Could not deactivate channel '{0}': {1}", channel, ex.Message);
                            channelsNotDeactivated.Add(channel);
                        }
                    }
                }
            }).ContinueWith((t) =>
            {
                log.Debug("Activate checked channels");
                for (int i = 0; i < checkedListBoxChannels.CheckedItems.Count; i++)
                {
                    var item       = checkedListBoxChannels.CheckedItems[i];
                    string channel = item.ToString();
                    try
                    {
                        camera.ActivateChannel(channel);
                    }
                    catch (Exception ex)
                    {
                        log.ErrorFormat("Could not activate channel '{0}': {1}", channel, ex.Message);
                        channelsNotActivated.Add(channel);
                    }
                }
            });

            channelsTask.Wait();

            log.Debug("Try to select a channel");
            if (1 == camera.ActiveChannels.Count)
            {
                camera.SelectChannel(camera.ActiveChannels[0].Name);
            }
            else if (1 == checkedListBoxChannels.SelectedItems.Count && checkedListBoxChannels.CheckedItems.Contains(checkedListBoxChannels.SelectedItem))
            {
                camera.SelectChannel(checkedListBoxChannels.SelectedItem.ToString());
            }

            if (channelsNotDeactivated.Count + channelsNotActivated.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                if (channelsNotDeactivated.Count > 0)
                {
                    sb.AppendLine(string.Format("Could not deactivate the channels '{0}'", string.Join("', '", channelsNotDeactivated)));
                }
                if (channelsNotDeactivated.Count > 0)
                {
                    sb.AppendLine(string.Format("Could not activate the channels '{0}'", string.Join("', '", channelsNotActivated)));
                }

                MessageBox.Show(sb.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            log.Debug("Apply camera parameters");
            cameraSettingsControl.ApplyCameraSettings();

            //If configuring the camera involves an automatic change of the available channels, we should update the channel panel size.
            //TODO: Perform a deep comparison of all channels instead of just comparing the number of elements.
            if (camera.Channels.Count != nrChannelsBeforeConfigurationChange)
            {
                LoadChannels();
                AdjustLayout();
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Reads the XML part and saves the image properties (e.g. width/height).
        /// </summary>
        /// <param name="xml">XML string</param>
        private void ReadXML(string xml)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(new StringReader(xml));

            XmlNode dataSets                  = doc["SickRecord"]["DataSets"];
            XmlNode dataSetDepthMap           = dataSets["DataSetDepthMap"];
            XmlNode formatDescriptionDepthMap = dataSetDepthMap["FormatDescriptionDepthMap"];
            XmlNode dataStream                = formatDescriptionDepthMap["DataStream"];

            // get camera/image parameters
            width  = Convert.ToInt32(dataStream["Width"].InnerText);
            height = Convert.ToInt32(dataStream["Height"].InnerText);

            XmlNode      cameraToWorldTransform = dataStream["CameraToWorldTransform"];
            List <float> cam2WorldList          = new List <float>();

            foreach (XmlNode child in cameraToWorldTransform)
            {
                cam2WorldList.Add(float.Parse(child.InnerText, CultureInfo.InvariantCulture.NumberFormat));
            }
            cam2WorldMatrix = cam2WorldList.ToArray();
            cam2WorldList   = null;

            XmlNode cameraMatrix = dataStream["CameraMatrix"];

            fx = float.Parse(cameraMatrix.ChildNodes[0].InnerText, CultureInfo.InvariantCulture.NumberFormat);
            fy = float.Parse(cameraMatrix.ChildNodes[1].InnerText, CultureInfo.InvariantCulture.NumberFormat);
            cx = float.Parse(cameraMatrix.ChildNodes[2].InnerText, CultureInfo.InvariantCulture.NumberFormat);
            cy = float.Parse(cameraMatrix.ChildNodes[3].InnerText, CultureInfo.InvariantCulture.NumberFormat);

            XmlNode distortionParams = dataStream["CameraDistortionParams"];

            k1 = float.Parse(distortionParams["K1"].InnerText, CultureInfo.InvariantCulture.NumberFormat);
            k2 = float.Parse(distortionParams["K2"].InnerText, CultureInfo.InvariantCulture.NumberFormat);

            f2rc = Convert.ToSingle(dataStream["FocalToRayCross"].InnerText, CultureInfo.InvariantCulture.NumberFormat);

            // data types, should always be uint16_t
            if (dataStream["Distance"].InnerText.ToLower() == "uint16")
            {
                numBytesPerDistanceValue = 2;
            }
            else
            {
                log.ErrorFormat("Bytes per distance value has unexpected value \"{0}\"", dataStream.ChildNodes[8].InnerText.ToLower());
                ExceptionBuilder.Throw(typeof(NotImplementedException), cam, "error_unknown", "Bytes per distance value has unexpected value.");
            }
            if (dataStream["Intensity"].InnerText.ToLower() == "uint16")
            {
                numBytesPerIntensityValue = 2;
            }
            else
            {
                log.ErrorFormat("Bytes per intensity value has unexpected value \"{0}\"", dataStream.ChildNodes[8].InnerText.ToLower());
                ExceptionBuilder.Throw(typeof(NotImplementedException), cam, "error_unknown", "Bytes per intensity value has unexpected value.");
            }
            if (dataStream["Confidence"].InnerText.ToLower() == "uint16")
            {
                numBytesPerConfidenceValue = 2;
            }
            else
            {
                log.ErrorFormat("Bytes per confidence value has unexpected value \"{0}\"", dataStream.ChildNodes[8].InnerText.ToLower());
                ExceptionBuilder.Throw(typeof(NotImplementedException), cam, "error_unknown", "Bytes per confidence value has unexpected value.");
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the raw frame data from camera.
        /// </summary>
        /// <remarks>Data is checked for correct protocol version and packet type.</remarks>
        /// <returns>Raw frame</returns>
        public byte[] Stream_GetFrame()
        {
            log.Debug("Start getting frame");
            List <byte> data = new List <byte>();

            byte[] buffer = new byte[FRAGMENT_SIZE];
            int    read   = 0;

            // first read and check header
            read = streamData.Read(buffer, 0, buffer.Length);
            if (read < 11)
            {
                ExceptionBuilder.Throw(typeof(InvalidOperationException), cam, "error_getData", "Not enough bytes received: " + read);
            }

            // check buffer content
            uint   magicWord, pkgLength;
            ushort protocolVersion;
            byte   packetType;

            magicWord       = BitConverter.ToUInt32(buffer, 0);
            pkgLength       = BitConverter.ToUInt32(buffer, 4);
            protocolVersion = BitConverter.ToUInt16(buffer, 8);
            packetType      = buffer[10];

            // take care of endianness
            magicWord       = Utils.ConvertEndiannessUInt32(magicWord);
            pkgLength       = Utils.ConvertEndiannessUInt32(pkgLength);
            protocolVersion = Utils.ConvertEndiannessUInt16(protocolVersion);

            if (magicWord != 0x02020202)
            {
                log.ErrorFormat("MagicWord is wrong. Got {0}", magicWord);
                ExceptionBuilder.Throw(typeof(Exception), cam, "error_getData", "MagicWord is wrong.");
            }
            if (protocolVersion != 0x0001)
            {
                log.ErrorFormat("ProtocolVersion is wrong. Got {0}", protocolVersion);
                ExceptionBuilder.Throw(typeof(Exception), cam, "error_getData", "ProtocolVersion is wrong.");
            }
            if (packetType != 0x62)
            {
                log.ErrorFormat("PacketType is wrong. Got {0}", packetType);
                ExceptionBuilder.Throw(typeof(Exception), cam, "error_getData", "PacketType is wrong.");
            }

            // get actual frame data
            data.AddRange(buffer.Take(read));
            pkgLength++; // checksum byte
            int alreadyReceived = read - 8;

            while (alreadyReceived < pkgLength)
            {
                read = streamData.Read(buffer, 0, (int)Math.Min(FRAGMENT_SIZE, pkgLength - alreadyReceived));
                if (read == 0)
                {
                    log.Error("Failed to receive bytes from camera.");
                    ExceptionBuilder.Throw(typeof(Exception), cam, "error_getData", "Failed to read Frame.");
                }
                data.AddRange(buffer.Take(read));
                alreadyReceived += read;
            }

            log.Debug("Done: Start getting frame");
            return(data.ToArray());
        }