예제 #1
0
        /* Some features are boolean features that can be switched on and off.
         * This function illustrates how to access boolean features. */
        private static void demonstrateBooleanFeature(PYLON_DEVICE_HANDLE hDev)
        {
            string featureName = "GammaEnable"; /* The name of the feature. */
            bool   isWritable;                  /* Is the feature writable? */
            bool   value;                       /* The value of the feature. */

            /* Check to see if the feature is writable. */
            isWritable = Pylon.DeviceFeatureIsWritable(hDev, featureName);

            if (isWritable)
            {
                /* Retrieve the current state of the feature. */
                value = Pylon.DeviceGetBooleanFeature(hDev, featureName);

                Console.WriteLine("The {0} features is {1}.", featureName, value ? "on" : "off");

                /* Set a new value. */
                value = !value;  /* New value. */
                Console.WriteLine("Switching the {0} feature {1}.", featureName, value ? "on" : "off");
                Pylon.DeviceSetBooleanFeature(hDev, featureName, value);
            }
            else
            {
                Console.WriteLine("The {0} feature isn't writable.", featureName);
            }
        }
예제 #2
0
        /* Some features are floating point features. This function illustrates how to set and get floating
         * point parameters. */
        private static void demonstrateFloatFeature(PYLON_DEVICE_HANDLE hDev)
        {
            string featureName = "Gamma";  /* The name of the feature used. */
            bool   isAvailable;            /* Is the feature available? */
            bool   isWritable;             /* Is the feature writable? */
            double min, max, value;        /* Value range and current value. */

            isAvailable = Pylon.DeviceFeatureIsAvailable(hDev, featureName);

            if (isAvailable)
            {
                /* Query the value range and the current value. */
                min   = Pylon.DeviceGetFloatFeatureMin(hDev, featureName);
                max   = Pylon.DeviceGetFloatFeatureMax(hDev, featureName);
                value = Pylon.DeviceGetFloatFeature(hDev, featureName);

                Console.WriteLine("{0}: min = {1}, max = {2}, value = {3}", featureName, min, max, value);

                /* Set a new value. */
                isWritable = Pylon.DeviceFeatureIsWritable(hDev, featureName);
                if (isWritable)
                {
                    value = 0.5 * (min + max);
                    Console.WriteLine("Setting {0} to {1}.", featureName, value);
                    Pylon.DeviceSetFloatFeature(hDev, featureName, value);
                }
            }
            else
            {
                Console.WriteLine("The {0} feature isn't available.", featureName);
            }
        }
예제 #3
0
        /* This function demonstrates how to handle integer camera parameters. */
        private static void demonstrateIntFeature(PYLON_DEVICE_HANDLE hDev)
        {
            string featureName = "Width";  /* Name of the feature used in this sample: AOI Width. */
            long   val, min, max, incr;    /* Properties of the feature. */

            /*
             * Query the current value, the allowed value range, and the increment of the feature.
             * For some integer features, you are not allowed to set every value within the
             * value range. For example, for some cameras the Width parameter must be a multiple
             * of 2. These constraints are expressed by the increment value. Valid values
             * follow the rule: val >= min && val <= max && val == min + n * inc.
             *
             * To help clarify this sample, we don't check for the feature accessibility as demonstrated
             * in the demonstrateAccessibility() function.
             */
            min  = Pylon.DeviceGetIntegerFeatureMin(hDev, featureName); /* Get the minimum value. */
            max  = Pylon.DeviceGetIntegerFeatureMax(hDev, featureName); /* Get the maximum value. */
            incr = Pylon.DeviceGetIntegerFeatureInc(hDev, featureName); /* Get the increment value. */
            val  = Pylon.DeviceGetIntegerFeature(hDev, featureName);    /* Get the current value. */

            Console.WriteLine("{0}: min= {1}  max= {2}  incr={3}  Value={4}", featureName, min, max, incr, val);

            /* Set the Width to its maximum allowed value. */
            Pylon.DeviceSetIntegerFeature(hDev, featureName, max);
            Console.WriteLine("The {0} was set to {1}.", featureName, max);
        }
예제 #4
0
        /// <summary>
        /// Commit value of properties that can be written during streaming and don't require a reconnect to be applied.
        /// This is used by the configuration, to update the image while configuring.
        /// </summary>
        public static void Write(PYLON_DEVICE_HANDLE deviceHandle, CameraProperty property)
        {
            if (!property.Supported || string.IsNullOrEmpty(property.Identifier) || !deviceHandle.IsValid)
            {
                return;
            }

            try
            {
                switch (property.Identifier)
                {
                case "AcquisitionFrameRate":
                case "AcquisitionFrameRateAbs":
                case "ExposureTime":
                case "ExposureTimeAbs":
                case "Gain":
                case "GainRaw":
                    WriteProperty(deviceHandle, property);
                    break;

                case "Width":
                case "Height":
                    // Do nothing. These properties must be changed from WriteCriticalProperties below.
                    break;

                default:
                    log.ErrorFormat("Basler  property not supported: {0}.", property.Identifier);
                    break;
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("Error while writing Basler property {0}. {1}", property.Identifier, e.Message);
            }
        }
예제 #5
0
        /*
         * Regardless of the parameter's type, any parameter value can be retrieved as a string. Likewise, each parameter
         * can be set by passing in a string. This function illustrates how to set and get the
         * Width parameter as a string. As demonstrated above, the Width parameter is of the integer type.
         */
        private static void demonstrateFromStringToString(PYLON_DEVICE_HANDLE hDev)
        {
            string featureName = "Width";   /* The name of the feature. */
            string value;

            /* Get the value of a feature as a string. */
            value = Pylon.DeviceFeatureToString(hDev, featureName);

            Console.WriteLine("{0}: {1}", featureName, value);

            /* A feature can be set as a string using the PylonDeviceFeatureFromString() function.
             * If the content of a string can not be converted to the type of the feature, an
             * error is returned. */

            try
            {
                Pylon.DeviceFeatureFromString(hDev, featureName, "fourty-two"); /* Cannot be converted to an integer. */
            }
            catch (Exception e)
            {
                /* Retrieve the error message. */
                string msg = GenApi.GetLastErrorMessage() + "\n" + GenApi.GetLastErrorDetail();
                Console.WriteLine("Exception caught:");
                Console.WriteLine(e.Message);
                if (msg != "\n")
                {
                    Console.WriteLine("Last error message:");
                    Console.WriteLine(msg);
                }
            }
        }
예제 #6
0
        private void Open()
        {
            if (grabbing)
            {
                Stop();
            }

            try
            {
                deviceHandle = Pylon.CreateDeviceByIndex(deviceIndex);
                imageProvider.Open(deviceHandle);
            }
            catch (Exception e)
            {
                log.Error("Could not open Basler device.");
                LogError(e, imageProvider.GetLastErrorMessage());
                return;
            }

            if (!deviceHandle.IsValid)
            {
                return;
            }

            SpecificInfo specific = summary.Specific as SpecificInfo;

            if (specific == null)
            {
                return;
            }

            // Store the handle into the specific info so that we can retrieve device informations from the configuration dialog.
            specific.Handle = deviceHandle;
            GenApiEnum currentStreamFormat = PylonHelper.ReadEnumCurrentValue(deviceHandle, "PixelFormat");

            if (!string.IsNullOrEmpty(specific.StreamFormat) && specific.StreamFormat != currentStreamFormat.Symbol)
            {
                PylonHelper.WriteEnum(deviceHandle, "PixelFormat", specific.StreamFormat);
            }

            // The bayer conversion mode will be set during Prepare().

            if (firstOpen)
            {
                // Restore camera parameters from the XML blurb.
                // Regular properties, including image size.
                // First we read the current properties from the API to get fully formed properties.
                // We merge the values saved in the XML into the properties.
                // (The restoration from the XML doesn't create fully formed properties, it just contains the values).
                // Then commit the properties to the camera.
                Dictionary <string, CameraProperty> cameraProperties = CameraPropertyManager.Read(deviceHandle, summary.Identifier);
                CameraPropertyManager.MergeProperties(cameraProperties, specific.CameraProperties);
                specific.CameraProperties = cameraProperties;
                CameraPropertyManager.WriteCriticalProperties(deviceHandle, specific.CameraProperties);
            }
            else
            {
                CameraPropertyManager.WriteCriticalProperties(deviceHandle, specific.CameraProperties);
            }
        }
예제 #7
0
        public FormConfiguration(CameraSummary summary)
        {
            this.summary = summary;

            InitializeComponent();
            tbAlias.AutoSize = false;
            tbAlias.Height   = 20;

            tbAlias.Text            = summary.Alias;
            lblSystemName.Text      = summary.Name;
            btnIcon.BackgroundImage = summary.Icon;

            SpecificInfo specific = summary.Specific as SpecificInfo;

            if (specific == null || specific.Handle == null || !specific.Handle.IsValid)
            {
                return;
            }

            deviceHandle     = specific.Handle;
            cameraProperties = CameraPropertyManager.Read(specific.Handle, summary.Identifier);

            if (cameraProperties.Count != specific.CameraProperties.Count)
            {
                specificChanged = true;
            }

            Populate();
        }
예제 #8
0
        private static CameraProperty ReadFloatProperty(PYLON_DEVICE_HANDLE deviceHandle, string symbol)
        {
            CameraProperty p = new CameraProperty();

            p.Identifier = symbol;

            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, symbol);

            if (!nodeHandle.IsValid)
            {
                return(p);
            }

            EGenApiAccessMode accessMode = GenApi.NodeGetAccessMode(nodeHandle);

            if (accessMode == EGenApiAccessMode._UndefinedAccesMode || accessMode == EGenApiAccessMode.NA ||
                accessMode == EGenApiAccessMode.NI || accessMode == EGenApiAccessMode.WO)
            {
                return(p);
            }

            p.Supported = true;
            p.ReadOnly  = accessMode != EGenApiAccessMode.RW;

            EGenApiNodeType type = GenApi.NodeGetType(nodeHandle);

            if (type != EGenApiNodeType.FloatNode)
            {
                return(p);
            }

            p.Type = CameraPropertyType.Float;

            double min = GenApi.FloatGetMin(nodeHandle);
            double max = GenApi.FloatGetMax(nodeHandle);
            EGenApiRepresentation repr = GenApi.FloatGetRepresentation(nodeHandle);
            double currentValue        = GenApi.FloatGetValue(nodeHandle);

            // We don't support a dedicated control for "pure numbers" just use the regular slider.
            if (repr == EGenApiRepresentation.PureNumber)
            {
                repr = EGenApiRepresentation.Linear;
            }

            // Fix values that should be log.
            double range = Math.Log(max - min, 10);

            if (range > 4 && repr == EGenApiRepresentation.Linear)
            {
                repr = EGenApiRepresentation.Logarithmic;
            }

            p.Minimum        = min.ToString(CultureInfo.InvariantCulture);
            p.Maximum        = max.ToString(CultureInfo.InvariantCulture);
            p.Representation = ConvertRepresentation(repr);
            p.CurrentValue   = currentValue.ToString(CultureInfo.InvariantCulture);

            return(p);
        }
예제 #9
0
        /* If the device provides a heartbeat timeout, this function will set the heartbeat timeout.
         * When the device provides the parameter, the old value is returned, -1 otherwise.
         * The heartbeat timeout is a parameter provided by the transport layer.
         * The transport layer parameters are exposed as a GenApi node map that
         * can be retrieved from the device.
         */
        private static long setHeartbeatTimeout(PYLON_DEVICE_HANDLE hDev, long timeout_ms)
        {
            NODEMAP_HANDLE hNodemap;   /* Handle to the node map. */
            NODE_HANDLE    hNode;      /* Handle to a node, i.e., a feature. */
            long           oldTimeout; /* The current timeout value. */

            /* Get the node map for the transport layer parameters. */
            hNodemap = Pylon.DeviceGetTLNodeMap(hDev);

            if (!hNodemap.IsValid)
            {
                /* The device doesn't provide a transport layer node map. Nothing to do. */
                Console.WriteLine("The device doesn't provide a transport layer node map. Cannot set heartbeat timeout.");
                return(-1);
            }
            /* Get the node for the heartbeat timeout parameter. */
            hNode = GenApi.NodeMapGetNode(hNodemap, "HeartbeatTimeout");

            if (!hNode.IsValid)
            {
                /* There is no heartbeat timeout parameter. Nothing to do. */
                Console.WriteLine("There is no heartbeat timeout parameter. Cannot set heartbeat timeout.");
                return(-1);
            }

            /* Get the current value. */
            oldTimeout = GenApi.IntegerGetValue(hNode);

            /* Set the new value. */
            GenApi.IntegerSetValue(hNode, timeout_ms);

            /* Return the old value. */
            return(oldTimeout);
        }
예제 #10
0
        public static void WriteEnum(PYLON_DEVICE_HANDLE deviceHandle, string enumerationName, string enumerationValue)
        {
            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, enumerationName);

            WriteEnum(nodeHandle, enumerationName, enumerationValue);
        }
예제 #11
0
 public BaslerPylon()
     : base()
 {
     try
     {
         /* Get a handle for specific index.  */
         _hDev = _hDevQueue.Dequeue();
     }
     catch (Exception e)
     {
         throw new APXExeception(e.Message);
     }
     try
     {
         Pylon.DeviceOpen(_hDev, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream);
         InitDeviceInfo();
         if (Pylon.DeviceIsOpen(_hDev))
         {
             Pylon.DeviceClose(_hDev);
         }
     }
     catch (Exception e)
     {
         throw new APXExeception(e.Message);
     }
 }
예제 #12
0
        public static void WriteCriticalProperties(PYLON_DEVICE_HANDLE deviceHandle, Dictionary <string, CameraProperty> properties)
        {
            if (properties == null || properties.Count == 0)
            {
                return;
            }

            try
            {
                WriteCenter(deviceHandle);

                foreach (var pair in properties)
                {
                    if (pair.Key == "width")
                    {
                        WriteSize(deviceHandle, pair.Value, "OffsetX");
                    }
                    else if (pair.Key == "height")
                    {
                        WriteSize(deviceHandle, pair.Value, "OffsetY");
                    }
                    else
                    {
                        WriteProperty(deviceHandle, pair.Value);
                    }
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("Error while writing Basler property. {0}", e.Message);
            }
        }
예제 #13
0
        /* Some features are floating point features. This function illustrates how to set and get floating
         * point parameters. */
        private static void demonstrateFloatFeature(PYLON_DEVICE_HANDLE hDev)
        {
            NODEMAP_HANDLE  hNodeMap;
            NODE_HANDLE     hNode;
            string          featureName = "Gamma"; /* The name of the feature used. */
            bool            bval;                  /* Is the feature available? */
            double          min, max, value;       /* Value range and current value. */
            EGenApiNodeType nodeType;

            /* Get a handle for the device's node map. */
            hNodeMap = Pylon.DeviceGetNodeMap(hDev);

            /* Look up the feature node. */
            hNode = GenApi.NodeMapGetNode(hNodeMap, featureName);
            if (!hNode.IsValid)
            {
                Console.WriteLine("There is no feature named '" + featureName + "'.");
                return;
            }

            /* We want a float feature node. */
            nodeType = GenApi.NodeGetType(hNode);

            if (EGenApiNodeType.FloatNode != nodeType)
            {
                Console.WriteLine("'" + featureName + "' is not an floating-point feature.");
                return;
            }

            bval = GenApi.NodeIsReadable(hNode);

            if (bval)
            {
                /* Query the value range and the current value. */
                min   = GenApi.FloatGetMin(hNode);
                max   = GenApi.FloatGetMax(hNode);
                value = GenApi.FloatGetValue(hNode);

                Console.WriteLine("{0}: min = {1}, max = {2}, value = {3}", featureName, min, max, value);

                /* Set a new value. */
                bval = GenApi.NodeIsWritable(hNode);

                if (bval)
                {
                    value = 0.5 * (min + max);
                    Console.WriteLine("Setting {0} to {1}", featureName, value);
                    GenApi.FloatSetValue(hNode, value);
                }
                else
                {
                    Console.WriteLine("Cannot set value for feature '{0}' - node not writable.", featureName);
                }
            }
            else
            {
                Console.WriteLine("Cannot read feature '{0}' - node not readable.", featureName);
            }
        }
예제 #14
0
        private static CameraProperty ReadIntegerProperty(PYLON_DEVICE_HANDLE deviceHandle, string symbol)
        {
            CameraProperty p = new CameraProperty();

            p.Identifier = symbol;

            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, symbol);

            if (!nodeHandle.IsValid)
            {
                log.WarnFormat("Could not read Basler property {0}: node handle is not valid. (The property is not supported).", symbol);
                return(p);
            }

            EGenApiAccessMode accessMode = GenApi.NodeGetAccessMode(nodeHandle);

            if (accessMode == EGenApiAccessMode._UndefinedAccesMode || accessMode == EGenApiAccessMode.NA ||
                accessMode == EGenApiAccessMode.NI || accessMode == EGenApiAccessMode.WO)
            {
                log.WarnFormat("Could not read Basler property {0}: Access mode not supported. (The property is not readable).", symbol);
                return(p);
            }

            EGenApiNodeType type = GenApi.NodeGetType(nodeHandle);

            if (type != EGenApiNodeType.IntegerNode)
            {
                log.WarnFormat("Could not read Basler property {0}: the node is of the wrong type. Expected: Integer. Received:{1}", symbol, type.ToString());
                return(p);
            }

            p.Supported = true;
            p.Type      = CameraPropertyType.Integer;
            p.ReadOnly  = accessMode != EGenApiAccessMode.RW;

            long min  = GenApi.IntegerGetMin(nodeHandle);
            long max  = GenApi.IntegerGetMax(nodeHandle);
            long step = GenApi.IntegerGetInc(nodeHandle);
            EGenApiRepresentation repr = GenApi.IntegerGetRepresentation(nodeHandle);

            // Fix values that should be log.
            double range = Math.Log10(max) - Math.Log10(min);

            if (range > 4 && repr == EGenApiRepresentation.Linear)
            {
                repr = EGenApiRepresentation.Logarithmic;
            }

            long currentValue = GenApi.IntegerGetValue(nodeHandle);

            p.Minimum        = min.ToString(CultureInfo.InvariantCulture);
            p.Maximum        = max.ToString(CultureInfo.InvariantCulture);
            p.Step           = step.ToString(CultureInfo.InvariantCulture);
            p.Representation = ConvertRepresentation(repr);
            p.CurrentValue   = currentValue.ToString(CultureInfo.InvariantCulture);

            return(p);
        }
예제 #15
0
 private void pylonInitialize()
 {
     /* Before using any pylon methods, the pylon runtime must be initialized. */
     Pylon.Initialize();
     _pylonDevHandle = GetPylonDeviceHandle();
     initDefaultGrabFeatures();
     setGevSCPSPacketSize();
 }
예제 #16
0
        public static string DeviceGetStringFeature(PYLON_DEVICE_HANDLE handle, string featureName)
        {
            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(handle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, featureName);
            string         featureValue  = GenApi.NodeToString(nodeHandle);

            return(featureValue);
        }
예제 #17
0
        /* Some features are boolean features that can be switched on and off.
         * This function illustrates how to access boolean features. */
        private static void demonstrateBooleanFeature(PYLON_DEVICE_HANDLE hDev)
        {
            NODEMAP_HANDLE  hNodeMap;
            NODE_HANDLE     hNode;
            string          featureName = "GammaEnable"; /* The name of the feature. */
            bool            value, bval;                 /* The value of the feature. */
            EGenApiNodeType nodeType;

            /* Get a handle for the device's node map. */
            hNodeMap = Pylon.DeviceGetNodeMap(hDev);

            /* Look up the feature node. */
            hNode = GenApi.NodeMapGetNode(hNodeMap, featureName);
            if (!hNode.IsValid)
            {
                Console.WriteLine("There is no feature named '" + featureName + "'.");
                return;
            }

            /* We want a boolean feature node. */
            nodeType = GenApi.NodeGetType(hNode);

            if (EGenApiNodeType.BooleanNode != nodeType)
            {
                Console.WriteLine("'" + featureName + "' is not a boolean feature.");
                return;
            }

            /* Check to see if the feature is readable. */
            bval = GenApi.NodeIsReadable(hNode);

            if (bval)
            {
                /* Retrieve the current state of the feature. */
                value = GenApi.BooleanGetValue(hNode);

                Console.WriteLine("The {0} feature is {1}.", featureName, value ? "on" : "off");

                /* Set a new value. */
                bval = GenApi.NodeIsWritable(hNode);

                if (bval)
                {
                    value = (bool)!value;  /* New value. */
                    Console.WriteLine("Switching the {0} feature {1}.", featureName, value ? "on" : "off");
                    GenApi.BooleanSetValue(hNode, value);
                }
                else
                {
                    Console.WriteLine("Cannot set value for feature '{0}' - node not writable.", featureName);
                }
            }
            else
            {
                Console.WriteLine("Cannot read feature '{0}' - node not readable.", featureName);
            }
        }
예제 #18
0
        private static CameraProperty ReadIntegerProperty(PYLON_DEVICE_HANDLE deviceHandle, string symbol)
        {
            CameraProperty p = new CameraProperty();

            p.Identifier = symbol;

            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, symbol);

            if (!nodeHandle.IsValid)
            {
                return(p);
            }

            EGenApiAccessMode accessMode = GenApi.NodeGetAccessMode(nodeHandle);

            if (accessMode == EGenApiAccessMode._UndefinedAccesMode || accessMode == EGenApiAccessMode.NA ||
                accessMode == EGenApiAccessMode.NI || accessMode == EGenApiAccessMode.WO)
            {
                return(p);
            }

            p.Supported = true;
            p.ReadOnly  = accessMode != EGenApiAccessMode.RW;

            EGenApiNodeType type = GenApi.NodeGetType(nodeHandle);

            if (type != EGenApiNodeType.IntegerNode)
            {
                return(p);
            }

            p.Type = CameraPropertyType.Integer;

            long min  = GenApi.IntegerGetMin(nodeHandle);
            long max  = GenApi.IntegerGetMax(nodeHandle);
            long step = GenApi.IntegerGetInc(nodeHandle);
            EGenApiRepresentation repr = GenApi.IntegerGetRepresentation(nodeHandle);

            // Fix values that should be log.
            double range = Math.Log(max - min, 10);

            if (range > 4 && repr == EGenApiRepresentation.Linear)
            {
                repr = EGenApiRepresentation.Logarithmic;
            }

            long currentValue = GenApi.IntegerGetValue(nodeHandle);

            p.Minimum        = min.ToString(CultureInfo.InvariantCulture);
            p.Maximum        = max.ToString(CultureInfo.InvariantCulture);
            p.Step           = step.ToString(CultureInfo.InvariantCulture);
            p.Representation = ConvertRepresentation(repr);
            p.CurrentValue   = currentValue.ToString(CultureInfo.InvariantCulture);

            return(p);
        }
예제 #19
0
        public static void Write(PYLON_DEVICE_HANDLE deviceHandle, CameraProperty property)
        {
            if (!property.Supported || string.IsNullOrEmpty(property.Identifier))
            {
                return;
            }

            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, property.Identifier);

            if (!nodeHandle.IsValid)
            {
                return;
            }

            EGenApiAccessMode accessMode = GenApi.NodeGetAccessMode(nodeHandle);

            if (accessMode != EGenApiAccessMode.RW)
            {
                return;
            }

            switch (property.Type)
            {
            case CameraPropertyType.Integer:
            {
                long value     = long.Parse(property.CurrentValue, CultureInfo.InvariantCulture);
                long step      = long.Parse(property.Step, CultureInfo.InvariantCulture);
                long remainder = value % step;
                if (remainder > 0)
                {
                    value = value - remainder;
                }

                GenApi.IntegerSetValue(nodeHandle, value);
                break;
            }

            case CameraPropertyType.Float:
            {
                double value = double.Parse(property.CurrentValue, CultureInfo.InvariantCulture);
                GenApi.FloatSetValue(nodeHandle, value);
                break;
            }

            case CameraPropertyType.Boolean:
            {
                bool value = bool.Parse(property.CurrentValue);
                GenApi.BooleanSetValue(nodeHandle, value);
                break;
            }

            default:
                break;
            }
        }
예제 #20
0
        public static Dictionary <string, CameraProperty> Read(PYLON_DEVICE_HANDLE deviceHandle, string fullName)
        {
            Dictionary <string, CameraProperty> properties = new Dictionary <string, CameraProperty>();

            // Enumerate devices again to make sure we have the correct device index and find the device class.
            DeviceEnumerator.Device        device  = null;
            List <DeviceEnumerator.Device> devices = DeviceEnumerator.EnumerateDevices();

            foreach (DeviceEnumerator.Device candidate in devices)
            {
                if (candidate.FullName != fullName)
                {
                    continue;
                }

                device = candidate;
                break;
            }

            if (device == null)
            {
                return(properties);
            }

            string deviceClass = "BaslerGigE";

            try
            {
                deviceClass = Pylon.DeviceInfoGetPropertyValueByName(device.DeviceInfoHandle, Pylon.cPylonDeviceInfoDeviceClassKey);
            }
            catch
            {
                log.ErrorFormat("Could not read Basler device class. Assuming BaslerGigE.");
            }

            properties.Add("width", ReadIntegerProperty(deviceHandle, "Width"));
            properties.Add("height", ReadIntegerProperty(deviceHandle, "Height"));
            properties.Add("enableFramerate", ReadBooleanProperty(deviceHandle, "AcquisitionFrameRateEnable"));

            if (deviceClass == "BaslerUsb")
            {
                properties.Add("framerate", ReadFloatProperty(deviceHandle, "AcquisitionFrameRate"));
                properties.Add("exposure", ReadFloatProperty(deviceHandle, "ExposureTime"));
                properties.Add("gain", ReadFloatProperty(deviceHandle, "Gain"));
            }
            else
            {
                properties.Add("framerate", ReadFloatProperty(deviceHandle, "AcquisitionFrameRateAbs"));
                properties.Add("exposure", ReadFloatProperty(deviceHandle, "ExposureTimeAbs"));
                properties.Add("gain", ReadIntegerProperty(deviceHandle, "GainRaw"));
            }

            return(properties);
        }
예제 #21
0
        private static void demonstrateCategory(PYLON_DEVICE_HANDLE hDev)
        {
            NODEMAP_HANDLE hNodeMap;
            NODE_HANDLE    hNode;

            /* Get a handle for the device's node map. */
            hNodeMap = Pylon.DeviceGetNodeMap(hDev);

            /* Look up the root node. */
            hNode = GenApi.NodeMapGetNode(hNodeMap, "Root");

            handleCategory(hNode, "");
        }
예제 #22
0
        private static void ReadFramerate(PYLON_DEVICE_HANDLE deviceHandle, Dictionary <string, CameraProperty> properties)
        {
            properties.Add("enableFramerate", ReadBooleanProperty(deviceHandle, "AcquisitionFrameRateEnable"));

            CameraProperty prop = ReadFloatProperty(deviceHandle, "AcquisitionFrameRate");

            if (!prop.Supported)
            {
                prop = ReadFloatProperty(deviceHandle, "AcquisitionFrameRateAbs");
            }

            properties.Add("framerate", prop);
        }
 /* Open using index. Before ImageProvider can be opened using the index, Pylon.EnumerateDevices() needs to be called. */
 public void Open(uint index)
 {
     /* Get a handle for the device and proceed. */
     try
     {
         PYLON_DEVICE_HANDLE PDH = Pylon.CreateDeviceByIndex(index);
         Open(PDH);
     }
     catch (Exception e)
     {
         MyDebug.ShowMessage(e, "相机创建失败");
     }
 }
예제 #24
0
        public static float GetResultingFramerate(PYLON_DEVICE_HANDLE deviceHandle)
        {
            if (Pylon.DeviceFeatureIsReadable(deviceHandle, "ResultingFrameRateAbs"))
            {
                return((float)Pylon.DeviceGetFloatFeature(deviceHandle, "ResultingFrameRateAbs"));
            }
            else if (Pylon.DeviceFeatureIsReadable(deviceHandle, "ResultingFrameRate"))
            {
                return((float)Pylon.DeviceGetFloatFeature(deviceHandle, "ResultingFrameRate"));
            }

            return(0);
        }
예제 #25
0
        private static void ReadFramerate(PYLON_DEVICE_HANDLE deviceHandle, string deviceClass, Dictionary <string, CameraProperty> properties)
        {
            properties.Add("enableFramerate", ReadBooleanProperty(deviceHandle, "AcquisitionFrameRateEnable"));

            if (deviceClass == "BaslerUsb")
            {
                properties.Add("framerate", ReadFloatProperty(deviceHandle, "AcquisitionFrameRate"));
            }
            else
            {
                properties.Add("framerate", ReadFloatProperty(deviceHandle, "AcquisitionFrameRateAbs"));
            }
        }
예제 #26
0
        public static void WriteStreamFormat(PYLON_DEVICE_HANDLE deviceHandle, string selectedFormatSymbol)
        {
            string enumerationName = "PixelFormat";

            NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle);
            NODE_HANDLE    nodeHandle    = GenApi.NodeMapGetNode(nodeMapHandle, enumerationName);

            if (!nodeHandle.IsValid)
            {
                return;
            }

            try
            {
                bool available = GenApi.NodeIsAvailable(nodeHandle);
                if (!available)
                {
                    return;
                }

                uint itemCount = GenApi.EnumerationGetNumEntries(nodeHandle);
                for (uint i = 0; i < itemCount; i++)
                {
                    NODE_HANDLE entryHandle = GenApi.EnumerationGetEntryByIndex(nodeHandle, i);

                    if (!GenApi.NodeIsAvailable(entryHandle))
                    {
                        continue;
                    }

                    string value = GenApi.EnumerationEntryGetSymbolic(entryHandle);
                    if (value != selectedFormatSymbol)
                    {
                        continue;
                    }

                    if (GenApi.NodeToString(nodeHandle) == value)
                    {
                        continue;
                    }

                    GenApi.NodeFromString(nodeHandle, value);
                    break;
                }
            }
            catch
            {
                // Silent catch.
            }
        }
예제 #27
0
        /* There are camera features, such as AcquisitionStart, that represent a command.
         * This function that loads the default set, illustrates how to execute a command feature.  */
        private static void demonstrateCommandFeature(PYLON_DEVICE_HANDLE hDev)
        {
            /* Before executing the user set load command, the user set selector must be
             * set to the default set. Since we are focusing on the command feature,
             * we skip the recommended steps for checking the availability of the user set
             * related features and values. */

            /* Choose the default set (which includes one of the factory setups). */
            Pylon.DeviceFeatureFromString(hDev, "UserSetSelector", "Default");

            /* Execute the user set load command. */
            Console.WriteLine("Loading the default settings.");
            Pylon.DeviceExecuteCommandFeature(hDev, "UserSetLoad");
        }
        private uint _timeout = 1000 * 1; // timeout 時間, 預設為 1 秒

        #endregion Fields

        #region Constructors

        public LineScanGrabImageWorkingMan()
        {
            initStatus();

            // Pylon
            _hDev = new PYLON_DEVICE_HANDLE(); /* Handle for the pylon device. */
            //_ExceptionMessageList = new List<string>();
            #if DEBUG
            /* This is a special debug setting needed only for GigE cameras.
                See 'Building Applications with pylon' in the programmers guide */
            Environment.SetEnvironmentVariable("PYLON_GIGE_HEARTBEAT", "300000" /*ms*/);
            #endif
            initialize();
            initializeBackgroundWorker();
        }
예제 #29
0
        /// <summary>
        /// Get camera config
        /// </summary>
        /// <param name="device">camera device</param>
        /// <param name="featureName">feature name</param>
        /// <returns>feature value</returns>
        private string GetConfig(PYLON_DEVICE_HANDLE device, string featureName)
        {
            string value = string.Empty;

            try
            {
                value = Pylon.DeviceFeatureToString(device, featureName);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(value);
        }
예제 #30
0
        private long _PEGY = 4096;  //pixels
        public LineScanGrabImageWorkingMan()
        {
            initStatus();

            // Pylon
            _hDev = new PYLON_DEVICE_HANDLE(); /* Handle for the pylon device. */
            //_ExceptionMessageList = new List<string>();
#if DEBUG
            /* This is a special debug setting needed only for GigE cameras.
             *  See 'Building Applications with pylon' in the programmers guide */
            Environment.SetEnvironmentVariable("PYLON_GIGE_HEARTBEAT", "300000" /*ms*/);
#endif
            initialize();
            initializeBackgroundWorker();
        }
예제 #31
0
        private static void ReadGain(PYLON_DEVICE_HANDLE deviceHandle, Dictionary <string, CameraProperty> properties)
        {
            CameraProperty prop = ReadFloatProperty(deviceHandle, "Gain");

            if (!prop.Supported)
            {
                prop = ReadIntegerProperty(deviceHandle, "GainRaw");
            }

            prop.CanBeAutomatic      = true;
            prop.AutomaticIdentifier = "GainAuto";
            GenApiEnum auto = PylonHelper.ReadEnumCurrentValue(deviceHandle, prop.AutomaticIdentifier);

            prop.Automatic = auto != null && auto.Symbol == "Continuous";
            properties.Add("gain", prop);
        }
예제 #32
0
        public static Dictionary <string, CameraProperty> Read(PYLON_DEVICE_HANDLE deviceHandle, string fullName)
        {
            Dictionary <string, CameraProperty> properties = new Dictionary <string, CameraProperty>();

            // Enumerate devices again to make sure we have the correct device index and find the device class.
            DeviceEnumerator.Device        device  = null;
            List <DeviceEnumerator.Device> devices = DeviceEnumerator.EnumerateDevices();

            foreach (DeviceEnumerator.Device candidate in devices)
            {
                if (candidate.FullName != fullName)
                {
                    continue;
                }

                device = candidate;
                break;
            }

            if (device == null)
            {
                return(properties);
            }

            string deviceClass = "BaslerGigE";

            try
            {
                deviceClass = Pylon.DeviceInfoGetPropertyValueByName(device.DeviceInfoHandle, Pylon.cPylonDeviceInfoDeviceClassKey);
            }
            catch
            {
                log.ErrorFormat("Could not read Basler device class. Assuming BaslerGigE.");
            }

            properties.Add("width", ReadIntegerProperty(deviceHandle, "Width"));
            properties.Add("height", ReadIntegerProperty(deviceHandle, "Height"));

            // Camera properties in Kinovea combine the value and the "auto" flag.
            // We potentially need to read several Basler camera properties to create one Kinovea camera property.
            // Furthermore, some properties name or type depends on whether the camera is USB or GigE.
            ReadFramerate(deviceHandle, deviceClass, properties);
            ReadExposure(deviceHandle, deviceClass, properties);
            ReadGain(deviceHandle, deviceClass, properties);

            return(properties);
        }
        protected bool m_triggered = true; /* Indicates that we wish to trigger single shots */

        #endregion Fields

        #region Constructors

        /* Constructor with creation of basic objects. */
        public ImageProvider()
        {
            /* Create a thread for image grabbing. */
            m_grabThread = new Thread(Grab);
            /* Create objects used for buffer handling. */
            m_lockObject = new Object();
            m_buffers = new Dictionary<PYLON_STREAMBUFFER_HANDLE, PylonBuffer<Byte>>();
            m_grabbedBuffers = new List<GrabResult>();
            /* Create handles. */
            m_hGrabber = new PYLON_STREAMGRABBER_HANDLE();
            m_hDevice = new PYLON_DEVICE_HANDLE();
            m_hRemovalCallback = new PYLON_DEVICECALLBACK_HANDLE();
            m_hConverter = new PYLON_FORMAT_CONVERTER_HANDLE();
            /* Create callback handler and attach the method. */
            m_callbackHandler = new DeviceCallbackHandler();
            m_callbackHandler.CallbackEvent += new DeviceCallbackHandler.DeviceCallback(RemovalCallbackHandler);
        }
예제 #34
0
        private Camera()
        {
            grabbing = false;

            Pylon.Initialize();

            uint numDevices = Pylon.EnumerateDevices();

            if (numDevices == 0)
            {
                //throw new Exception("No Camera connected");
                Console.WriteLine("No Camera connected. \nPlease restart the programm with a connect BASLER camera!");
                dev = null;
                return;
            }

            dev = Pylon.CreateDeviceByIndex(0);
        }
 /// <summary>
 /// 取得第一個找到的 Device
 /// </summary>
 /// <returns></returns>
 public PYLON_DEVICE_HANDLE GetPylonDeviceHandle()
 {
     if (_pylonDevHandle == null)
     {
         _latestMessage = "";
         uint numDevices = Pylon.EnumerateDevices();
         var deviceNotExists = (0 == numDevices);
         if (deviceNotExists)
         {
             _latestMessage = "No devices found.";
         }
         else
         {
             /* Get a handle for the first device found.  */
             _pylonDevHandle = Pylon.CreateDeviceByIndex(0);
         }
     }
     return _pylonDevHandle;
 }
 private void pylonInitialize()
 {
     /* Before using any pylon methods, the pylon runtime must be initialized. */
     Pylon.Initialize();
     _pylonDevHandle = GetPylonDeviceHandle();
     initDefaultGrabFeatures();
     setGevSCPSPacketSize();
 }
        private void initialize()
        {
            _initSuccess = true;
            /* Before using any pylon methods, the pylon runtime must be initialized. */
            Pylon.Initialize();

            /* Enumerate all camera devices. You must call
                PylonEnumerateDevices() before creating a device. */
            _numDevices = Pylon.EnumerateDevices();

            if (0 == _numDevices)
            {
                _initSuccess = false;
                notifyError("No devices found!");
            }

            /* Get a handle for the first device found.  */
            _hDev = Pylon.CreateDeviceByIndex(0);

            /* Before using the device, it must be opened. Open it for configuring
            parameters and for grabbing images. */
            Pylon.DeviceOpen(_hDev, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream);

            /* Set the pixel format to Mono8, where gray values will be output as 8 bit values for each pixel. */
            /* ... Check first to see if the device supports the Mono8 format. */
            isAvail = Pylon.DeviceFeatureIsAvailable(_hDev, "EnumEntry_PixelFormat_Mono8");

            if (!isAvail)
            {
                /* Feature is not available. */
                _initSuccess = false;
                notifyError("Device doesn't support the Mono8 pixel format.");
            }
            else
            {
                /* ... Set the pixel format to Mono8. */
                Pylon.DeviceFeatureFromString(_hDev, "PixelFormat", "Mono8");
            }

            /* For GigE cameras, we recommend increasing the packet size for better
                   performance. If the network adapter supports jumbo frames, set the packet
                   size to a value > 1500, e.g., to 8192. In this sample, we only set the packet size
                   to 1500. */
            /* ... Check first to see if the GigE camera packet size parameter is supported and if it is writable. */
            isAvail = Pylon.DeviceFeatureIsWritable(_hDev, "GevSCPSPacketSize");

            if (isAvail)
            {
                /* ... The device supports the packet size feature. Set a value. */
                Pylon.DeviceSetIntegerFeature(_hDev, "GevSCPSPacketSize", 1500);
            }

            setStreamGrabber();

            //Free Run Settings
            //setFreeRunParams();
            setPEGParams(_PEGX, _PEGY);

            prepareDevice();
            setStatus(GrabInstruction.Initialize, GrabStage.Connected, GrabState.Idle);
            notifyStateChange(_bgworker, new GrabImageStatusChangedEventArgs() { Status = this.Status });
        }
예제 #38
0
        /* Handles the selection of cameras from the list box. The currently open device is closed and the first
         selected device is opened. */
        private void deviceListView_SelectedIndexChanged(object sender, EventArgs ev)
        {
            /* Close the currently open image provider. */
            /* Stops the grabbing of images. */
            Stop();
            /* Close the image provider. */
            CloseTheImageProvider();

            /* Open the selected image provider. */
            if (deviceListView.SelectedItems.Count > 0)
            {
                /* Get the first selected item. */
                ListViewItem item = deviceListView.SelectedItems[0];
                /* Get the attached device data. */
                DeviceEnumerator.Device device = (DeviceEnumerator.Device)item.Tag;
                try
                {
                    /* Open the image provider using the index from the device data. */
                    m_imageProvider.Open(device.Index);
                    m_imageProvider.GetNodeFromDevice(device.Name);
                    hDev = Pylon.CreateDeviceByIndex(device.Index);

                }
                catch (Exception e)
                {
                    ShowException(e, m_imageProvider.GetLastErrorMessage());
                }
            }
             //          Console.WriteLine(m_imageProvider.get_integerParam("Width").ToString());

            //            hDev = new PYLON_DEVICE_HANDLE();
              //          Pylon.Initialize();

            /* Enumerate all camera devices. You must call
            PylonEnumerateDevices() before creating a device. */

            /*            if (0 == Pylon.EnumerateDevices())
            {
                throw new Exception("No devices found.");
            }
            */
        }
        static void Main(string[] args)
        {
            PYLON_DEVICE_HANDLE hDev = new PYLON_DEVICE_HANDLE(); /* Handle for the pylon device. */
            try
            {
                uint numDevices;               /* Number of available devices. */
                PYLON_STREAMGRABBER_HANDLE hGrabber;  /* Handle for the pylon stream grabber. */
                PYLON_WAITOBJECT_HANDLE hWait;        /* Handle used for waiting for a grab to be finished. */
                uint payloadSize;              /* Size of an image frame in bytes. */
                Dictionary<PYLON_STREAMBUFFER_HANDLE, PylonBuffer<Byte>> buffers; /* Holds handles and buffers used for grabbing. */
                PylonGrabResult_t grabResult;               /* Stores the result of a grab operation. */
                int nGrabs;                   /* Counts the number of buffers grabbed. */
                uint nStreams;                 /* The number of streams provides by the device.  */
                bool isAvail;                  /* Used for checking feature availability. */
                bool isReady;                  /* Used as an output parameter. */
                int i;                        /* Counter. */

            #if DEBUG
                /* This is a special debug setting needed only for GigE cameras.
                See 'Building Applications with pylon' in the programmer's guide. */
                Environment.SetEnvironmentVariable("PYLON_GIGE_HEARTBEAT", "300000" /*ms*/);
            #endif

                /* Before using any pylon methods, the pylon runtime must be initialized. */
                Pylon.Initialize();

                /* Enumerate all camera devices. You must call
                PylonEnumerateDevices() before creating a device. */
                numDevices = Pylon.EnumerateDevices();

                if (0 == numDevices)
                {
                    throw new Exception("No devices found.");
                }

                /* Get a handle for the first device found.  */
                hDev = Pylon.CreateDeviceByIndex(0);

                /* Before using the device, it must be opened. Open it for configuring
                parameters and for grabbing images. */
                Pylon.DeviceOpen(hDev, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream);

                /* Print out the name of the camera we are using. */
                {
                    bool isReadable = Pylon.DeviceFeatureIsReadable(hDev, "DeviceModelName");
                    if (isReadable)
                    {
                        string name = Pylon.DeviceFeatureToString(hDev, "DeviceModelName");
                        Console.WriteLine("Using camera {0}.", name);
                    }
                }

                /* Set the pixel format to Mono8, where gray values will be output as 8 bit values for each pixel. */
                /* ... Check first to see if the device supports the Mono8 format. */
                isAvail = Pylon.DeviceFeatureIsAvailable(hDev, "EnumEntry_PixelFormat_Mono8");

                if (!isAvail)
                {
                    /* Feature is not available. */
                    throw new Exception("Device doesn't support the Mono8 pixel format.");
                }
                /* ... Set the pixel format to Mono8. */
                Pylon.DeviceFeatureFromString(hDev, "PixelFormat", "Mono8");

                /* Disable acquisition start trigger if available */
                isAvail = Pylon.DeviceFeatureIsAvailable(hDev, "EnumEntry_TriggerSelector_AcquisitionStart");
                if (isAvail)
                {
                    Pylon.DeviceFeatureFromString(hDev, "TriggerSelector", "AcquisitionStart");
                    Pylon.DeviceFeatureFromString(hDev, "TriggerMode", "Off");
                }

                /* Disable frame start trigger if available */
                isAvail = Pylon.DeviceFeatureIsAvailable(hDev, "EnumEntry_TriggerSelector_FrameStart");
                if (isAvail)
                {
                    Pylon.DeviceFeatureFromString(hDev, "TriggerSelector", "FrameStart");
                    Pylon.DeviceFeatureFromString(hDev, "TriggerMode", "Off");
                }

                /* We will use the Continuous frame mode, i.e., the camera delivers
                images continuously. */
                Pylon.DeviceFeatureFromString(hDev, "AcquisitionMode", "Continuous");

                /* For GigE cameras, we recommend increasing the packet size for better
                   performance. When the network adapter supports jumbo frames, set the packet
                   size to a value > 1500, e.g., to 8192. In this sample, we only set the packet size
                   to 1500. */
                /* ... Check first to see if the GigE camera packet size parameter is supported and if it is writable. */
                isAvail = Pylon.DeviceFeatureIsWritable(hDev, "GevSCPSPacketSize");
                if (isAvail)
                {
                    /* ... The device supports the packet size feature. Set a value. */
                    Pylon.DeviceSetIntegerFeature(hDev, "GevSCPSPacketSize", 1500);
                }

                /* Determine the required size of the grab buffer. */
                payloadSize = checked((uint)Pylon.DeviceGetIntegerFeature(hDev, "PayloadSize"));

                /* Image grabbing is done using a stream grabber.
                  A device may be able to provide different streams. A separate stream grabber must
                  be used for each stream. In this sample, we create a stream grabber for the default
                  stream, i.e., the first stream ( index == 0 ).
                  */

                /* Get the number of streams supported by the device and the transport layer. */
                nStreams = Pylon.DeviceGetNumStreamGrabberChannels(hDev);

                if (nStreams < 1)
                {
                    throw new Exception("The transport layer doesn't support image streams.");
                }

                /* Create and open a stream grabber for the first channel. */
                hGrabber = Pylon.DeviceGetStreamGrabber(hDev, 0);
                Pylon.StreamGrabberOpen(hGrabber);

                /* Get a handle for the stream grabber's wait object. The wait object
                   allows waiting for buffers to be filled with grabbed data. */
                hWait = Pylon.StreamGrabberGetWaitObject(hGrabber);

                /* We must tell the stream grabber the number and size of the buffers
                    we are using. */
                /* .. We will not use more than NUM_BUFFERS for grabbing. */
                Pylon.StreamGrabberSetMaxNumBuffer(hGrabber, NUM_BUFFERS);

                /* .. We will not use buffers bigger than payloadSize bytes. */
                Pylon.StreamGrabberSetMaxBufferSize(hGrabber, payloadSize);

                /*  Allocate the resources required for grabbing. After this, critical parameters
                    that impact the payload size must not be changed until FinishGrab() is called. */
                Pylon.StreamGrabberPrepareGrab(hGrabber);

                /* Before using the buffers for grabbing, they must be registered at
                   the stream grabber. For each registered buffer, a buffer handle
                   is returned. After registering, these handles are used instead of the
                   buffer objects pointers. The buffer objects are held in a dictionary,
                   that provides access to the buffer using a handle as key.
                 */
                buffers = new Dictionary<PYLON_STREAMBUFFER_HANDLE, PylonBuffer<Byte>>();
                for (i = 0; i < NUM_BUFFERS; ++i)
                {
                    PylonBuffer<Byte> buffer = new PylonBuffer<byte>(payloadSize, true);
                    PYLON_STREAMBUFFER_HANDLE handle = Pylon.StreamGrabberRegisterBuffer(hGrabber, ref buffer);
                    buffers.Add(handle, buffer);
                }

                /* Feed the buffers into the stream grabber's input queue. For each buffer, the API
                   allows passing in an integer as additional context information. This integer
                   will be returned unchanged when the grab is finished. In our example, we use the index of the
                   buffer as context information. */
                i = 0;
                foreach (KeyValuePair<PYLON_STREAMBUFFER_HANDLE, PylonBuffer<Byte>> pair in buffers)
                {
                    Pylon.StreamGrabberQueueBuffer(hGrabber, pair.Key, i++);
                }

                /* The stream grabber is now prepared. As soon the camera starts acquiring images,
                   the image data will be grabbed into the provided buffers.  */

                /* Let the camera acquire images. */
                Pylon.DeviceExecuteCommandFeature(hDev, "AcquisitionStart");

                /* Grab NUM_GRABS images */
                nGrabs = 0;                         /* Counts the number of grabbed images. */
                while (nGrabs < NUM_GRABS)
                {
                    int bufferIndex;                /* Index of the buffer. */
                    Byte min, max;
                    /* Wait for the next buffer to be filled. Wait up to 1000 ms. */
                    isReady = Pylon.WaitObjectWait(hWait, 1000);

                    if (!isReady)
                    {
                        /* Timeout occurred. */
                        throw new Exception("Grab timeout occurred.");
                    }

                    /* Since the wait operation was successful, the result of at least one grab
                       operation is available. Retrieve it. */
                    isReady = Pylon.StreamGrabberRetrieveResult(hGrabber, out grabResult);

                    if (!isReady)
                    {
                        /* Oops. No grab result available? We should never have reached this point.
                           Since the wait operation above returned without a timeout, a grab result
                           should be available. */
                        throw new Exception("Failed to retrieve a grab result");
                    }

                    nGrabs++;

                    /* Get the buffer index from the context information. */
                    bufferIndex = (int)grabResult.Context;

                    /* Check to see if the image was grabbed successfully. */
                    if (grabResult.Status == EPylonGrabStatus.Grabbed)
                    {
                        /*  Success. Perform image processing. Since we passed more than one buffer
                        to the stream grabber, the remaining buffers are filled in the background while
                        we do the image processing. The processed buffer won't be touched by
                        the stream grabber until we pass it back to the stream grabber. */

                        PylonBuffer<Byte> buffer;        /* Reference to the buffer attached to the grab result. */

                        /* Get the buffer from the dictionary. Since we also got the buffer index,
                           we could alternatively use an array, e.g. buffers[bufferIndex]. */
                        if (!buffers.TryGetValue(grabResult.hBuffer, out buffer))
                        {
                            /* Oops. No buffer available? We should never have reached this point. Since all buffers are
                               in the dictionary. */
                            throw new Exception("Failed to find the buffer associated with the handle returned in grab result.");
                        }

                        /* Perform processing. */
                        getMinMax(buffer.Array, grabResult.SizeX, grabResult.SizeY, out min, out max);
                        Console.WriteLine("Grabbed frame {0} into buffer {1}. Min. gray value = {2}, Max. gray value = {3}",
                            nGrabs, bufferIndex, min, max);
                    }
                    else if (grabResult.Status == EPylonGrabStatus.Failed)
                    {
                        Console.Error.WriteLine("Frame {0} wasn't grabbed successfully.  Error code = {1}",
                            nGrabs, grabResult.ErrorCode);
                    }

                    /* Once finished with the processing, requeue the buffer to be filled again. */
                    Pylon.StreamGrabberQueueBuffer(hGrabber, grabResult.hBuffer, bufferIndex);
                }

                /* Clean up. */

                /*  ... Stop the camera. */
                Pylon.DeviceExecuteCommandFeature(hDev, "AcquisitionStop");

                /* ... We must issue a cancel call to ensure that all pending buffers are put into the
                   stream grabber's output queue. */
                Pylon.StreamGrabberCancelGrab(hGrabber);

                /* ... The buffers can now be retrieved from the stream grabber. */
                do
                {
                    isReady = Pylon.StreamGrabberRetrieveResult(hGrabber, out grabResult);

                } while (isReady);

                /* ... When all buffers are retrieved from the stream grabber, they can be deregistered.
                       After deregistering the buffers, it is safe to free the memory. */

                foreach (KeyValuePair<PYLON_STREAMBUFFER_HANDLE, PylonBuffer<Byte>> pair in buffers)
                {
                    Pylon.StreamGrabberDeregisterBuffer(hGrabber, pair.Key);
                    pair.Value.Dispose();
                }
                buffers = null;

                /* ... Release grabbing related resources. */
                Pylon.StreamGrabberFinishGrab(hGrabber);

                /* After calling PylonStreamGrabberFinishGrab(), parameters that impact the payload size (e.g.,
                the AOI width and height parameters) are unlocked and can be modified again. */

                /* ... Close the stream grabber. */
                Pylon.StreamGrabberClose(hGrabber);

                /* ... Close and release the pylon device. The stream grabber becomes invalid
                   after closing the pylon device. Don't call stream grabber related methods after
                   closing or releasing the device. */
                Pylon.DeviceClose(hDev);
                Pylon.DestroyDevice(hDev);

                /* ... Shut down the pylon runtime system. Don't call any pylon method after
                   calling Pylon.Terminate(). */
                Pylon.Terminate();

                Console.Error.WriteLine("\nPress enter to exit.");
                Console.ReadLine();
            }
            catch (Exception e)
            {
                /* Retrieve the error message. */
                string msg = GenApi.GetLastErrorMessage() + "\n" + GenApi.GetLastErrorDetail();
                Console.Error.WriteLine("Exception caught:");
                Console.Error.WriteLine(e.Message);
                if (msg != "\n")
                {
                    Console.Error.WriteLine("Last error message:");
                    Console.Error.WriteLine(msg);
                }

                try
                {
                    if (hDev.IsValid)
                    {
                        /* ... Close and release the pylon device. */
                        if (Pylon.DeviceIsOpen(hDev))
                        {
                            Pylon.DeviceClose(hDev);
                        }
                        Pylon.DestroyDevice(hDev);
                    }
                }
                catch (Exception)
                {
                    /*No further handling here.*/
                }

                Pylon.Terminate();  /* Releases all pylon resources. */

                Console.Error.WriteLine("\nPress enter to exit.");
                Console.ReadLine();

                Environment.Exit(1);
            }
        }
        /* Open using device.*/
        protected void Open(PYLON_DEVICE_HANDLE device)
        {
            try
            {
                /* Use provided device. */
                m_hDevice = device;

                /* Before using the device, it must be opened. Open it for configuring
                parameters and for grabbing images. */
                Pylon.DeviceOpen(m_hDevice, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream);

                /* Register the callback function. */
                m_hRemovalCallback = Pylon.DeviceRegisterRemovalCallback(m_hDevice, m_callbackHandler);

                /* For GigE cameras, we recommend increasing the packet size for better
                   performance. When the network adapter supports jumbo frames, set the packet
                   size to a value > 1500, e.g., to 8192. In this sample, we only set the packet size
                   to 1500. */
                /* ... Check first to see if the GigE camera packet size parameter is supported and if it is writable. */
                if (Pylon.DeviceFeatureIsWritable(m_hDevice, "GevSCPSPacketSize"))
                {
                    /* ... The device supports the packet size feature. Set a value. */
                    Pylon.DeviceSetIntegerFeature(m_hDevice, "GevSCPSPacketSize", 1500);
                }

                /* The sample does not work in chunk mode. It must be disabled. */
                if (Pylon.DeviceFeatureIsWritable(m_hDevice, "ChunkModeActive"))
                {
                    /* Disable the chunk mode. */
                    Pylon.DeviceSetBooleanFeature(m_hDevice, "ChunkModeActive", false);
                }

                /* Disable acquisition start trigger if available. */
                if (Pylon.DeviceFeatureIsAvailable(m_hDevice, "EnumEntry_TriggerSelector_AcquisitionStart"))
                {
                    Pylon.DeviceFeatureFromString(m_hDevice, "TriggerSelector", "AcquisitionStart");
                    Pylon.DeviceFeatureFromString(m_hDevice, "TriggerMode", "Off");
                }

                /* Disable frame start trigger if available. */
                if (Pylon.DeviceFeatureIsAvailable(m_hDevice, "EnumEntry_TriggerSelector_FrameStart"))
                {
                    Pylon.DeviceFeatureFromString(m_hDevice, "TriggerSelector", "FrameStart");
                    Pylon.DeviceFeatureFromString(m_hDevice, "TriggerMode", "Off");
                }

                /* Image grabbing is done using a stream grabber.
                  A device may be able to provide different streams. A separate stream grabber must
                  be used for each stream. In this sample, we create a stream grabber for the default
                  stream, i.e., the first stream ( index == 0 ).
                  */

                /* Get the number of streams supported by the device and the transport layer. */
                if (Pylon.DeviceGetNumStreamGrabberChannels(m_hDevice) < 1)
                {
                    throw new Exception("The transport layer doesn't support image streams.");
                }

                /* Create and open a stream grabber for the first channel. */
                m_hGrabber = Pylon.DeviceGetStreamGrabber(m_hDevice, 0);
                Pylon.StreamGrabberOpen(m_hGrabber);

                /* Get a handle for the stream grabber's wait object. The wait object
                   allows waiting for m_buffers to be filled with grabbed data. */
                m_hWait = Pylon.StreamGrabberGetWaitObject(m_hGrabber);
            }
            catch
            {
                /* Get the last error message here, because it could be overwritten by cleaning up. */
                UpdateLastError();

                try
                {
                    Close(); /* Try to close any open handles. */
                }
                catch
                {
                    /* Another exception cannot be handled. */
                }
                throw;
            }

            /* Notify that the ImageProvider is open and ready for grabbing and configuration. */
            OnDeviceOpenedEvent();
        }
 /* This callback is called by the pylon layer using DeviceCallbackHandler. */
 protected void RemovalCallbackHandler(PYLON_DEVICE_HANDLE hDevice)
 {
     /* Notify that the device has been removed from the PC. */
     OnDeviceRemovedEvent();
 }
 public void Connect()
 {
     Hanbo.Log.LogManager.Debug("Pylon Connect");
     if (hDev == null)
     {
         Hanbo.Log.LogManager.Debug("Pylon Device IS Null");
         hDev = createDevice();
     }
     if (hDev != null)
     {
         Hanbo.Log.LogManager.Debug("Pylon Device IS Not Null");
         _isConnected = Pylon.DeviceIsOpen(hDev);
         Hanbo.Log.LogManager.Debug("Pylon DeviceIsOpen Check :" + _isConnected);
         if (!_isConnected)
         {
             Hanbo.Log.LogManager.Debug("Pylon DeviceOpen");
             Pylon.DeviceOpen(hDev, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream);
             Hanbo.Log.LogManager.Debug("Pylon resetDriveModeFeatures");
             resetDrivenModeFeatures();
         }
         _isConnected = Pylon.DeviceIsOpen(hDev);
     }
 }