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); }
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); }
/* 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); } }
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); }
/* Returns a GenICam parameter node handle of the device identified by the name of the node. */ public NODE_HANDLE GetNodeFromDevice( string name ) { if( m_open && !m_removed ) { NODEMAP_HANDLE hNodemap = Pylon.DeviceGetNodeMap( m_hDevice ); return GenApi.NodeMapGetNode( hNodemap, name ); } return new NODE_HANDLE(); }
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); }
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); }
/* 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); } }
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; } }
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, ""); }
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. } }
public static List <StreamFormat> GetSupportedStreamFormats(PYLON_DEVICE_HANDLE deviceHandle) { // We get a list of all possible values from GenICam API. // We cannot use the Pylon .NET enum names because of casing mismatches. // Then for each possible value, we poll for availability through Pylon API. string enumerationName = "PixelFormat"; NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle); NODE_HANDLE nodeHandle = GenApi.NodeMapGetNode(nodeMapHandle, enumerationName); if (!nodeHandle.IsValid) { return(null); } EGenApiNodeType nodeType = GenApi.NodeGetType(nodeHandle); if (nodeType != EGenApiNodeType.EnumerationNode) { return(null); } List <StreamFormat> supportedList = new List <StreamFormat>(); uint total = GenApi.EnumerationGetNumEntries(nodeHandle); for (uint i = 0; i < total; i++) { NODE_HANDLE enumEntryHandle = GenApi.EnumerationGetEntryByIndex(nodeHandle, i); string symbol = GenApi.EnumerationEntryGetSymbolic(enumEntryHandle); //string symbol = GenApi.NodeGetDisplayName(entryHandle); //string featureName = string.Format("EnumEntry_{0}_{1}", enumerationName, symbol); //bool supported = Pylon.DeviceFeatureIsAvailable(deviceHandle, featureName); bool supported = GenApi.NodeIsAvailable(enumEntryHandle); if (supported) { string displayName = GenApi.NodeGetDisplayName(enumEntryHandle); supportedList.Add(new StreamFormat(symbol, displayName)); } } return(supportedList); }
private static CameraProperty ReadBooleanProperty(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.BooleanNode) { log.WarnFormat("Could not read Basler property {0}: the node is of the wrong type. Expected: Boolean. Received:{1}", symbol, type.ToString()); return(p); } p.Supported = true; p.Type = CameraPropertyType.Boolean; p.ReadOnly = accessMode != EGenApiAccessMode.RW; bool currentValue = GenApi.BooleanGetValue(nodeHandle); p.Representation = CameraPropertyRepresentation.Checkbox; p.CurrentValue = currentValue.ToString(CultureInfo.InvariantCulture); return(p); }
private static CameraProperty ReadBooleanProperty(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.BooleanNode) { return(p); } p.Type = CameraPropertyType.Boolean; bool currentValue = GenApi.BooleanGetValue(nodeHandle); p.Representation = CameraPropertyRepresentation.Checkbox; p.CurrentValue = currentValue.ToString(CultureInfo.InvariantCulture); return(p); }
public static StreamFormat GetCurrentStreamFormat(PYLON_DEVICE_HANDLE deviceHandle) { StreamFormat sf = null; string enumerationName = "PixelFormat"; NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle); NODE_HANDLE nodeHandle = GenApi.NodeMapGetNode(nodeMapHandle, enumerationName); if (!nodeHandle.IsValid) { return(null); } string selected = GenApi.NodeToString(nodeHandle); uint itemCount = GenApi.EnumerationGetNumEntries(nodeHandle); for (uint i = 0; i < itemCount; i++) { NODE_HANDLE entryHandle = GenApi.EnumerationGetEntryByIndex(nodeHandle, i); string symbol = GenApi.EnumerationEntryGetSymbolic(entryHandle); if (selected != symbol) { continue; } if (!GenApi.NodeIsAvailable(entryHandle)) { continue; } string displayName = GenApi.NodeGetDisplayName(entryHandle); sf = new StreamFormat(symbol, displayName); break; } return(sf); }
private static void WriteCenter(PYLON_DEVICE_HANDLE deviceHandle) { // Force write the CenterX and CenterY properties if supported. // https://docs.baslerweb.com/center-x-and-center-y.html // This is apparently required in order for the MaxWidth/MaxHeight properties to behave correctly // and independently of the offset property. // To summarize we use the following approach: // 1. If CenterX/CenterY are supported properties, we use them and OffsetX/OffsetY will be automated by Pylon. // 2. Otherwise we use manually write OffsetX/OffsetY to center the image. NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle); NODE_HANDLE nodeHandleX = GenApi.NodeMapGetNode(nodeMapHandle, "CenterX"); NODE_HANDLE nodeHandleY = GenApi.NodeMapGetNode(nodeMapHandle, "CenterY"); if (nodeHandleX.IsValid && nodeHandleY.IsValid) { EGenApiAccessMode accessModeOffsetX = GenApi.NodeGetAccessMode(nodeHandleX); EGenApiAccessMode accessModeOffsetY = GenApi.NodeGetAccessMode(nodeHandleY); if (accessModeOffsetX == EGenApiAccessMode.RW && accessModeOffsetY == EGenApiAccessMode.RW) { GenApi.BooleanSetValue(nodeHandleX, true); GenApi.BooleanSetValue(nodeHandleY, true); } } }
private static CameraProperty ReadFramerate(PYLON_DEVICE_HANDLE deviceHandle, Dictionary <string, CameraProperty> properties) { CameraProperty p = new CameraProperty(); p.Identifier = "AcquisitionFrameRate"; p.Supported = false; p.Type = CameraPropertyType.Float; NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle); NODE_HANDLE nodeHandle = GenApi.NodeMapGetNode(nodeMapHandle, p.Identifier); if (!nodeHandle.IsValid) { p.Identifier = "AcquisitionFrameRateAbs"; nodeHandle = GenApi.NodeMapGetNode(nodeMapHandle, p.Identifier); if (!nodeHandle.IsValid) { 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).", p.Identifier); return(p); } EGenApiNodeType type = GenApi.NodeGetType(nodeHandle); if (type != EGenApiNodeType.FloatNode) { log.WarnFormat("Could not read Basler property {0}: the node is of the wrong type. Expected: Float. Received:{1}", p.Identifier, type.ToString()); return(p); } p.ReadOnly = false; p.Supported = true; double currentValue = GenApi.FloatGetValue(nodeHandle); double min = GenApi.FloatGetMin(nodeHandle); double max = GenApi.FloatGetMax(nodeHandle); double step = 1.0; min = Math.Max(1.0, min); p.Minimum = min.ToString(CultureInfo.InvariantCulture); p.Maximum = max.ToString(CultureInfo.InvariantCulture); p.CurrentValue = currentValue.ToString(CultureInfo.InvariantCulture); p.Step = step.ToString(CultureInfo.InvariantCulture); // Fix values that should be log. double range = Math.Log10(max) - Math.Log10(min); p.Representation = (range >= 4) ? CameraPropertyRepresentation.LogarithmicSlider : CameraPropertyRepresentation.LinearSlider; // AcquisitionFrameRateEnable=false: the framerate is automatically set to the max value possible. // AcquisitionFrameRateEnable=true: use the custom framerate set by the user in AcquisitionFrameRate. string autoIdentifier = "AcquisitionFrameRateEnable"; p.AutomaticIdentifier = autoIdentifier; NODE_HANDLE nodeHandleAuto = GenApi.NodeMapGetNode(nodeMapHandle, autoIdentifier); p.CanBeAutomatic = nodeHandleAuto.IsValid && GenApi.NodeIsWritable(nodeHandleAuto); p.Automatic = false; if (p.CanBeAutomatic) { string currentAutoValue = GenApi.BooleanGetValue(nodeHandleAuto).ToString(CultureInfo.InvariantCulture).ToLower(); p.Automatic = currentAutoValue == GetAutoTrue(autoIdentifier); } if (properties != null) { properties.Add("framerate", p); } return(p); }
/// <summary> /// Write either width or height as a centered region of interest. /// </summary> private static void WriteSize(PYLON_DEVICE_HANDLE deviceHandle, CameraProperty property, string identifierOffset) { if (property.ReadOnly) { 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; } long value = long.Parse(property.CurrentValue, CultureInfo.InvariantCulture); long min = GenApi.IntegerGetMin(nodeHandle); long max = GenApi.IntegerGetMax(nodeHandle); long step = GenApi.IntegerGetInc(nodeHandle); value = FixValue(value, min, max, step); // Offset handling. // Some cameras have a CenterX/CenterY property. // When it is set, the offset is automatic and becomes read-only. bool setOffset = false; NODE_HANDLE nodeHandleOffset = GenApi.NodeMapGetNode(nodeMapHandle, identifierOffset); if (nodeHandleOffset.IsValid) { EGenApiAccessMode accessModeOffset = GenApi.NodeGetAccessMode(nodeHandleOffset); if (accessModeOffset == EGenApiAccessMode.RW) { setOffset = true; } } if (setOffset) { long offset = (max - value) / 2; long minOffset = GenApi.IntegerGetMin(nodeHandleOffset); long stepOffset = GenApi.IntegerGetInc(nodeHandleOffset); long remainderOffset = (offset - minOffset) % stepOffset; if (remainderOffset != 0) { offset = offset - remainderOffset + stepOffset; } // We need to be careful with the order and not write a value that doesn't fit due to the offset, or vice versa. long currentValue = GenApi.IntegerGetValue(nodeHandle); if (value > currentValue) { GenApi.IntegerSetValue(nodeHandleOffset, offset); GenApi.IntegerSetValue(nodeHandle, value); } else { GenApi.IntegerSetValue(nodeHandle, value); GenApi.IntegerSetValue(nodeHandleOffset, offset); } } else { GenApi.IntegerSetValue(nodeHandle, value); } }
/// <summary> /// Write generic property with optional auto flag. /// </summary> private static void WriteProperty(PYLON_DEVICE_HANDLE deviceHandle, CameraProperty property) { if (property.ReadOnly) { return; } NODEMAP_HANDLE nodeMapHandle = Pylon.DeviceGetNodeMap(deviceHandle); // Switch OFF the auto flag if needed, to be able to write the main property. if (!string.IsNullOrEmpty(property.AutomaticIdentifier)) { NODE_HANDLE nodeHandleAuto = GenApi.NodeMapGetNode(nodeMapHandle, property.AutomaticIdentifier); if (nodeHandleAuto.IsValid) { bool writeable = GenApi.NodeIsWritable(nodeHandleAuto); bool currentAuto = ReadAuto(nodeHandleAuto, property.AutomaticIdentifier); if (writeable && property.CanBeAutomatic && currentAuto && !property.Automatic) { WriteAuto(nodeHandleAuto, property.AutomaticIdentifier, false); } } } // At this point the auto flag is off. Write the main property. NODE_HANDLE nodeHandle = GenApi.NodeMapGetNode(nodeMapHandle, property.Identifier); if (!nodeHandle.IsValid) { return; } EGenApiAccessMode accessMode = GenApi.NodeGetAccessMode(nodeHandle); if (accessMode != EGenApiAccessMode.RW) { return; } try { switch (property.Type) { case CameraPropertyType.Integer: { long value = long.Parse(property.CurrentValue, CultureInfo.InvariantCulture); long min = GenApi.IntegerGetMin(nodeHandle); long max = GenApi.IntegerGetMax(nodeHandle); long step = GenApi.IntegerGetInc(nodeHandle); value = FixValue(value, min, max, step); GenApi.IntegerSetValue(nodeHandle, value); break; } case CameraPropertyType.Float: { double value = double.Parse(property.CurrentValue, CultureInfo.InvariantCulture); double min = GenApi.FloatGetMin(nodeHandle); double max = GenApi.FloatGetMax(nodeHandle); value = FixValue(value, min, max); GenApi.FloatSetValue(nodeHandle, value); break; } case CameraPropertyType.Boolean: { bool value = bool.Parse(property.CurrentValue); GenApi.BooleanSetValue(nodeHandle, value); break; } default: break; } } catch { log.ErrorFormat("Error while writing Basler Pylon GenICam property {0}.", property.Identifier); } // Finally, switch ON the auto flag if needed. if (!string.IsNullOrEmpty(property.AutomaticIdentifier)) { NODE_HANDLE nodeHandleAuto = GenApi.NodeMapGetNode(nodeMapHandle, property.AutomaticIdentifier); if (nodeHandleAuto.IsValid && GenApi.NodeIsWritable(nodeHandleAuto) && property.CanBeAutomatic && property.Automatic) { WriteAuto(nodeHandleAuto, property.AutomaticIdentifier, true); } } }
/* 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) { string selectorName = "UserSetSelector", commandName = "UserSetLoad"; NODEMAP_HANDLE hNodeMap; NODE_HANDLE hCommand, hSelector; EGenApiNodeType nodeType; bool bval; /* Get a handle for the device's node map. */ hNodeMap = Pylon.DeviceGetNodeMap(hDev); /* Look up the command node. */ hCommand = GenApi.NodeMapGetNode(hNodeMap, commandName); if (!hCommand.IsValid) { Console.WriteLine("There is no node named '" + commandName + "'."); return; } /* Look up the selector node. */ hSelector = GenApi.NodeMapGetNode(hNodeMap, selectorName); if (!hSelector.IsValid) { Console.WriteLine("There is no node named '" + selectorName + "'."); return; } /* We want a command feature node. */ nodeType = GenApi.NodeGetType(hCommand); if (EGenApiNodeType.CommandNode != nodeType) { Console.WriteLine("'" + selectorName + "' is not a command feature."); return; } /* Before executing the user set load command, the user set selector must be * set to the default set. */ /* Check to see if the selector is writable. */ bval = GenApi.NodeIsWritable(hSelector); if (bval) { /* Choose the default set (which includes one of the factory setups). */ GenApi.NodeFromString(hSelector, "Default"); } else { Console.WriteLine("Cannot set selector '{0}' - node not writable.", selectorName); } /* Check to see if the command is writable. */ bval = GenApi.NodeIsWritable(hCommand); if (bval) { /* Execute the user set load command. */ Console.WriteLine("Loading the default set."); GenApi.CommandExecute(hCommand); } else { Console.WriteLine("Cannot execute command '{0}' - node not writable.", commandName); } }
const uint NUM_EVENT_BUFFERS = 20; /* Number of buffers used for grabbing. */ 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 hStreamGrabber; /* Handle for the pylon stream grabber. */ PYLON_EVENTGRABBER_HANDLE hEventGrabber; /* Handle for the event grabber used for receiving events. */ PYLON_EVENTADAPTER_HANDLE hEventAdapter; /* Handle for the event adapter used for dispatching events. */ PYLON_WAITOBJECT_HANDLE hWaitStream; /* Handle used for waiting for a grab to be finished. */ PYLON_WAITOBJECT_HANDLE hWaitEvent; /* Handle used for waiting for an event message. */ PYLON_WAITOBJECTS_HANDLE hWaitObjects; /* Container allowing waiting for multiple wait objects. */ NODEMAP_HANDLE hNodeMap; /* Handle for the node map containing the * camera parameters. */ NODE_CALLBACK_HANDLE hCallback; /* Used for deregistering a callback function. */ NODE_HANDLE hNode; /* Handle for a camera parameter. */ 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. */ NodeCallbackHandler callbackHandler = new NodeCallbackHandler(); /* Handles incoming callbacks. */ int nGrabs; /* Counts the number of buffers grabbed. */ uint nStreams; /* The number of streams the device provides. */ bool isAvail; /* Used for checking feature availability. */ bool isReady; /* Used as an output parameter. */ int i; /* Counter. */ PylonEventResult_t eventMsg = new PylonEventResult_t(); /* Event data container. */ long sfncVersionMajor; /* The major number of the Standard Feature Naming Convention (SFNC) * version used by the camera device. */ #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, for grabbing images, and for grabbing events. */ Pylon.DeviceOpen(hDev, Pylon.cPylonAccessModeControl | Pylon.cPylonAccessModeStream | Pylon.cPylonAccessModeEvent); /* 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 burst start trigger if available */ isAvail = Pylon.DeviceFeatureIsAvailable(hDev, "EnumEntry_TriggerSelector_FrameBurstStart"); if (isAvail) { Pylon.DeviceFeatureFromString(hDev, "TriggerSelector", "FrameBurstStart"); 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. 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); } /* Determine the required size of the grab buffer. */ payloadSize = checked ((uint)Pylon.DeviceGetIntegerFeature(hDev, "PayloadSize")); /* Determine the major number of the SFNC version used by the camera device. */ if (Pylon.DeviceFeatureIsAvailable(hDev, "DeviceSFNCVersionMajor")) { sfncVersionMajor = Pylon.DeviceGetIntegerFeature(hDev, "DeviceSFNCVersionMajor"); } else { /* No SFNC version information is provided by the camera device. */ sfncVersionMajor = 0; } /* Enable camera events. */ /* Select the end-of-exposure event.*/ Pylon.DeviceFeatureFromString(hDev, "EventSelector", "ExposureEnd"); /* Enable the event. Select the enumeration entry name depending on the SFNC version used by the camera device. */ if (sfncVersionMajor >= 2) { Pylon.DeviceFeatureFromString(hDev, "EventNotification", "On"); } else { Pylon.DeviceFeatureFromString(hDev, "EventNotification", "GenICamEvent"); } /* 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. */ hStreamGrabber = Pylon.DeviceGetStreamGrabber(hDev, 0); Pylon.StreamGrabberOpen(hStreamGrabber); /* Get a handle for the stream grabber's wait object. The wait object * allows waiting for buffers to be grabbed. */ hWaitStream = Pylon.StreamGrabberGetWaitObject(hStreamGrabber); /* 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(hStreamGrabber, NUM_IMAGE_BUFFERS); /* .. We will not use buffers bigger than payloadSize bytes. */ Pylon.StreamGrabberSetMaxBufferSize(hStreamGrabber, 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(hStreamGrabber); /* 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 object 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_IMAGE_BUFFERS; ++i) { PylonBuffer <Byte> buffer = new PylonBuffer <byte>(payloadSize, true); PYLON_STREAMBUFFER_HANDLE handle = Pylon.StreamGrabberRegisterBuffer(hStreamGrabber, 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(hStreamGrabber, pair.Key, i++); } /* The stream grabber is now prepared. As soon the camera starts to acquire images, * the image data will be grabbed into the provided buffers. */ /* Create and prepare an event grabber. */ /* ... Get a handle for the event grabber. */ hEventGrabber = Pylon.DeviceGetEventGrabber(hDev); if (!hEventGrabber.IsValid) { /* The transport layer doesn't support event grabbers. */ throw new Exception("No event grabber supported."); } /* ... Tell the grabber how many buffers to use. */ Pylon.EventGrabberSetNumBuffers(hEventGrabber, NUM_EVENT_BUFFERS); /* ... Open the event grabber. */ Pylon.EventGrabberOpen(hEventGrabber); /* The event grabber is now ready * for receiving events. */ /* Retrieve the wait object that is associated with the event grabber. The event * will be signaled when an event message has been received. */ hWaitEvent = Pylon.EventGrabberGetWaitObject(hEventGrabber); /* For extracting the event data from an event message, an event adapter is used. */ hEventAdapter = Pylon.DeviceCreateEventAdapter(hDev); if (!hEventAdapter.IsValid) { /* The transport layer doesn't support event grabbers. */ throw new Exception("No event adapter supported."); } /* Register the callback function for the ExposureEndEventFrameID parameter. */ /*.Get the node map containing all parameters. */ hNodeMap = Pylon.DeviceGetNodeMap(hDev); /* Get the ExposureEndEventFrameID parameter. * Select the parameter name depending on the SFNC version used by the camera device. */ if (sfncVersionMajor >= 2) { hNode = GenApi.NodeMapGetNode(hNodeMap, "EventExposureEndFrameID"); } else { hNode = GenApi.NodeMapGetNode(hNodeMap, "ExposureEndEventFrameID"); } if (!hNode.IsValid) { /* There is no ExposureEndEventFrameID parameter. */ throw new Exception("There is no ExposureEndEventFrameID or EventExposureEndFrameID parameter!"); } /* ... Register the callback function. */ callbackHandler.CallbackEvent += new NodeCallbackHandler.NodeCallback(endOfExposureCallback); hCallback = GenApi.NodeRegisterCallback(hNode, callbackHandler); /* Put the wait objects into a container. */ /* ... Create the container. */ hWaitObjects = Pylon.WaitObjectsCreate(); /* ... Add the wait objects' handles. */ Pylon.WaitObjectsAdd(hWaitObjects, hWaitEvent); Pylon.WaitObjectsAdd(hWaitObjects, hWaitStream); /* Let the camera acquire images. */ Pylon.DeviceExecuteCommandFeature(hDev, "AcquisitionStart"); /* Grab NUM_GRABS images. */ nGrabs = 0; /* Counts the number of images grabbed. */ while (nGrabs < NUM_GRABS) { int bufferIndex; /* Index of the buffer. */ uint waitObjectIndex; /* Index of the wait object that is signalled.*/ Byte min, max; /* Wait for either an image buffer grabbed or an event received. Wait up to 1000 ms. */ isReady = Pylon.WaitObjectsWaitForAny(hWaitObjects, 1000, out waitObjectIndex); if (!isReady) { /* Timeout occurred. */ throw new Exception("Timeout. Neither grabbed an image nor received an event."); } if (0 == waitObjectIndex) { /* hWaitEvent has been signalled. At least one event message is available. Retrieve it. */ isReady = Pylon.EventGrabberRetrieveEvent(hEventGrabber, ref eventMsg); if (!isReady) { /* Oops. No event message available? We should never have reached this point. * Since the wait operation above returned without a timeout, an event message * should be available. */ throw new Exception("Failed to retrieve an event."); } /* Check to see if the event was successfully received. */ if (0 == eventMsg.ErrorCode) { /* Successfully received an event message. */ /* Pass the event message to the event adapter. The event adapter will * update the parameters related to events and will fire the callbacks * registered to event related parameters. */ Pylon.EventAdapterDeliverMessage(hEventAdapter, eventMsg); } else { Console.Error.WriteLine("Error when receiving an event: {1}", eventMsg.ErrorCode); } } else if (1 == waitObjectIndex) { /* hWaitStream has been signalled. The result of at least one grab * operation is available. Retrieve it. */ isReady = Pylon.StreamGrabberRetrieveResult(hStreamGrabber, 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 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."); } getMinMax(buffer.Array, 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(hStreamGrabber, grabResult.hBuffer, bufferIndex); } } /* Clean up. */ /* ... Stop the camera. */ Pylon.DeviceExecuteCommandFeature(hDev, "AcquisitionStop"); /* ... Switch off the events. */ Pylon.DeviceFeatureFromString(hDev, "EventSelector", "ExposureEnd"); Pylon.DeviceFeatureFromString(hDev, "EventNotification", "Off"); /* ... We must issue a cancel call to ensure that all pending buffers are put into the * stream grabber's output queue. */ Pylon.StreamGrabberCancelGrab(hStreamGrabber); /* ... The buffers can now be retrieved from the stream grabber. */ do { isReady = Pylon.StreamGrabberRetrieveResult(hStreamGrabber, 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(hStreamGrabber, pair.Key); pair.Value.Dispose(); } buffers = null; /* ... Release grabbing related resources. */ Pylon.StreamGrabberFinishGrab(hStreamGrabber); /* 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(hStreamGrabber); /* ... Deregister the callback. */ GenApi.NodeDeregisterCallback(hNode, hCallback); /* ... Close the event grabber.*/ Pylon.EventGrabberClose(hEventGrabber); /* ... Release the event adapter. */ Pylon.DeviceDestroyEventAdapter(hDev, hEventAdapter); /* ... Release the wait object container. */ Pylon.WaitObjectsDestroy(hWaitObjects); /* ... 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 PylonTerminate(). */ 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) { /* Disable the software trigger. */ Pylon.DeviceFeatureFromString(hDev, "TriggerMode", "Off"); /* ... 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); } }
/* Enumerate all possible entries for an enumerated feature. For every entry, a selection * of properties is displayed. A loop similar to the one shown below may be part of a * GUI program that wants to fill the entries of a menu. */ private static void demonstrateEnumIteration(PYLON_DEVICE_HANDLE hDev) { string featureName = "PixelFormat"; NODEMAP_HANDLE hNodeMap; NODE_HANDLE hNode; EGenApiNodeType nodeType; bool bval; /* 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 an enumeration feature node. */ nodeType = GenApi.NodeGetType(hNode); if (EGenApiNodeType.EnumerationNode != nodeType) { Console.WriteLine("'" + featureName + "' is not an enumeration feature."); return; } /* Check to see if the feature is readable. */ bval = GenApi.NodeIsReadable(hNode); if (bval) { uint max, i; /* Check entries. */ max = GenApi.EnumerationGetNumEntries(hNode); /* Write out header. */ Console.WriteLine("Allowed values for feature '{0}':\n" + "--------------", featureName); /* A loop to visit every enumeration entry node once. */ for (i = 0; i < max; i++) { NODE_HANDLE hEntry; string name, displayName, description; bool avail; /* Get handle for enumeration entry node. */ hEntry = GenApi.EnumerationGetEntryByIndex(hNode, i); /* Get node name. */ name = GenApi.NodeGetName(hEntry); /* Get display name. */ displayName = GenApi.NodeGetDisplayName(hEntry); /* Get description. */ description = GenApi.NodeGetDescription(hEntry); /* Get availability. */ avail = GenApi.NodeIsAvailable(hEntry); /* Write out results. */ Console.WriteLine("Node name: {0}\n" + "Display name: {1}\n" + "Description: {2}\n" + "Available: {3}\n" + "--------------", name, displayName, description, avail ? "yes" : "no"); } } else { Console.WriteLine("Cannot read feature '{0}' - node not readable.", featureName); } }
/* There are camera features that behave like enumerations. These features can take a value from a fixed * set of possible values. One example is the pixel format feature. This function illustrates how to deal with * enumeration features. */ private static void demonstrateEnumFeature(PYLON_DEVICE_HANDLE hDev) { string featureName = "PixelFormat"; NODEMAP_HANDLE hNodeMap; NODE_HANDLE hNode; EGenApiNodeType nodeType; bool bval; /* 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 an enumeration feature node. */ nodeType = GenApi.NodeGetType(hNode); if (EGenApiNodeType.EnumerationNode != nodeType) { Console.WriteLine("'" + featureName + "' is not an enumeration feature."); return; } /* Check to see if the feature is readable. */ bval = GenApi.NodeIsReadable(hNode); /* The allowed values for an enumeration feature are represented as strings. Use the * GenApi.NodeFromString and GenApi.NodeToString methods for setting and getting * the value of an enumeration feature. */ if (bval) { /* Symbolic names of pixel formats. */ string symMono8 = "Mono8", symMono16 = "Mono16", symYUV422Packed = "YUV422Packed"; string value; /* The current value of the feature. */ bool supportsMono8, supportsYUV422Packed, supportsMono16; NODE_HANDLE hEntry; /* Get the current value of the enumeration feature. */ value = GenApi.NodeToString(hNode); Console.WriteLine("PixelFormat: {0}", value); /* * For an enumeration feature, the pylon Viewer's "Feature Documentation" window lists the * names of the possible values. Some of the values may not be supported by the device. * To check if a certain "SomeValue" value for a "SomeFeature" feature can be set, call the * GenApi.NodeIsAvailable() function on the node of the entry. */ /* Check to see if the Mono8 pixel format can be set. */ hEntry = GenApi.EnumerationGetEntryByName(hNode, symMono8); supportsMono8 = hEntry.IsValid && GenApi.NodeIsAvailable(hEntry); Console.WriteLine("{0} {1} a supported value for the pixel format feature.", symMono8, supportsMono8 ? "is" : "is not"); /* Check to see if the YUV422Packed pixel format can be set. */ hEntry = GenApi.EnumerationGetEntryByName(hNode, symYUV422Packed); supportsYUV422Packed = hEntry.IsValid && GenApi.NodeIsAvailable(hEntry); Console.WriteLine("{0} {1} a supported value for the pixel format feature.", symYUV422Packed, supportsYUV422Packed ? "is" : "is not"); /* Check to see if the Mono16 pixel format can be set. */ hEntry = GenApi.EnumerationGetEntryByName(hNode, symMono16); supportsMono16 = hEntry.IsValid && GenApi.NodeIsAvailable(hEntry); Console.WriteLine("{0} {1} a supported value for the pixel format feature.", symMono16, supportsMono16 ? "is" : "is not"); /* Before writing a value, we recommend checking to see if the enumeration feature is * currently writable. */ bval = GenApi.NodeIsWritable(hNode); if (bval) { /* The PixelFormat feature is writable. Set it to one of the supported values. */ if (supportsMono16) { Console.WriteLine("Setting PixelFormat to Mono16."); GenApi.NodeFromString(hNode, symMono16); } else if (supportsYUV422Packed) { Console.WriteLine("Setting PixelFormat to YUV422Packed."); GenApi.NodeFromString(hNode, symYUV422Packed); } else if (supportsMono8) { Console.WriteLine("Setting PixelFormat to Mono8."); GenApi.NodeFromString(hNode, symMono8); } /* Reset the PixelFormat feature to its previous value. */ GenApi.NodeFromString(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); } }
/* * 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. */ NODEMAP_HANDLE hNodeMap; NODE_HANDLE hNode; EGenApiNodeType nodeType; bool bval; /* 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 an integer feature node. */ nodeType = GenApi.NodeGetType(hNode); if (EGenApiNodeType.IntegerNode != nodeType) { Console.WriteLine("'" + featureName + "' is not an integer feature."); return; } /* Check to see if the feature is readable. */ bval = GenApi.NodeIsReadable(hNode); if (bval) { string valueString; /* Get the value of a feature as a string. */ valueString = GenApi.NodeToString(hNode); Console.WriteLine("{0}: value string = {1}", featureName, valueString); /* A feature can be set as a string using the GenApi.NodeFromString() function. * If the content of a string can not be converted to the type of the feature, an * error is returned. */ bval = GenApi.NodeIsWritable(hNode); if (bval) { try { GenApi.NodeFromString(hNode, "fourty-two"); /* Can not 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); } } } else { Console.WriteLine("Cannot set value for feature '{0}' - node not writable.", featureName); } } else { Console.WriteLine("Cannot read feature '{0}' - node not readable.", featureName); } }
public static void Write(PYLON_DEVICE_HANDLE deviceHandle, CameraProperty property) { if (!property.Supported || string.IsNullOrEmpty(property.Identifier) || !deviceHandle.IsValid) { return; } // If "auto" flag is OFF we should write it first. On some cameras the value is not writable until the corresponding auto flag is off. // If it's ON (continuous), it doesn't matter as our value will be overwritten soon anyway. if (!string.IsNullOrEmpty(property.AutomaticIdentifier)) { string enumValue = property.Automatic ? "Continuous" : "Off"; PylonHelper.WriteEnum(deviceHandle, property.AutomaticIdentifier, enumValue); } 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) { if (!string.IsNullOrEmpty(property.AutomaticIdentifier) && !property.Automatic) { log.ErrorFormat("Error while writing Basler Pylon GenICam property {0}.", property.Identifier); log.ErrorFormat("The property is not writable."); } return; } try { 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 max = GenApi.FloatGetMax(nodeHandle); double min = GenApi.FloatGetMin(nodeHandle); double value = double.Parse(property.CurrentValue, CultureInfo.InvariantCulture); value = Math.Min(Math.Max(value, min), max); GenApi.FloatSetValue(nodeHandle, value); break; } case CameraPropertyType.Boolean: { bool value = bool.Parse(property.CurrentValue); GenApi.BooleanSetValue(nodeHandle, value); break; } default: break; } } catch { log.ErrorFormat("Error while writing Basler Pylon GenICam property {0}.", property.Identifier); } }
/* This function demonstrates how to check the presence, readability, and writability * of a feature. */ private static void demonstrateAccessibilityCheck(PYLON_DEVICE_HANDLE hDev) { NODEMAP_HANDLE hNodeMap; NODE_HANDLE hNode; string featureName; bool val, val_read, val_write; /* Get a handle for the device's node map. */ hNodeMap = Pylon.DeviceGetNodeMap(hDev); /* Check to see if a feature is implemented at all. The 'Width' feature is likely to * be implemented by just about every existing camera. */ featureName = "Width"; hNode = GenApi.NodeMapGetNode(hNodeMap, featureName); if (hNode.IsValid) { /* Node exists. Check whether the feature is implemented. */ val = GenApi.NodeIsImplemented(hNode); } else { /* Node does not exist. Feature is not implemented. */ val = false; } Console.WriteLine("The '{0}' feature {1} implemented", featureName, val ? "is" : "is not"); /* This feature does most likely not exist. */ featureName = "Weirdness"; hNode = GenApi.NodeMapGetNode(hNodeMap, featureName); if (hNode.IsValid) { /* Node exists. Check whether the feature is implemented. */ val = GenApi.NodeIsImplemented(hNode); } else { /* Node does not exist. Feature is not implemented. */ val = false; } Console.WriteLine("The '{0}' feature {1} implemented.", featureName, val ? "is" : "is not"); /* Although a feature is implemented by the device, it may not be available * with the device in its current state. Check to see if the feature is currently * available. The GenApi.NodeIsAvailable sets val to false if either the feature * is not implemented or if the feature is currently not available. */ featureName = "BinningVertical"; hNode = GenApi.NodeMapGetNode(hNodeMap, featureName); if (hNode.IsValid) { /* Node exists. Check whether the feature is available. */ val = GenApi.NodeIsAvailable(hNode); } else { /* Node does not exist. Feature is not implemented, and hence not available. */ val = false; } Console.WriteLine("The '{0}' feature {1} implemented.", featureName, val ? "is" : "is not"); /* If a feature is available, it could be read-only, write-only, or both * readable and writable. Use the Pylon.DeviceFeatureIsReadable() and the * Pylon.DeviceFeatureIsWritable() functions(). It is safe to call these functions * for features that are currently not available or not implemented by the device. * A feature that is not available or not implemented is neither readable nor writable. * The readability and writability of a feature can change depending on the current * state of the device. For example, the Width parameter might not be writable when * the camera is acquiring images. */ featureName = "Width"; hNode = GenApi.NodeMapGetNode(hNodeMap, featureName); if (hNode.IsValid) { /* Node exists. Check whether the feature is readable. */ val_read = GenApi.NodeIsReadable(hNode); val_write = GenApi.NodeIsReadable(hNode); } else { /* Node does not exist. Feature is neither readable nor writable. */ val_read = val_write = false; } Console.WriteLine("The '{0}' feature {1} readable.", featureName, val_read ? "is" : "is not"); Console.WriteLine("The '{0}' feature {1} writable.", featureName, val_write ? "is" : "is not"); Console.WriteLine(""); }
/* This function demonstrates how to handle integer camera parameters. */ private static void demonstrateIntFeature(PYLON_DEVICE_HANDLE hDev) { NODEMAP_HANDLE hNodeMap; NODE_HANDLE hNode; string featureName = "Width"; /* Name of the feature used in this sample: AOI Width. */ long val, min, max, incr; /* Properties of the feature. */ EGenApiNodeType nodeType; bool bval; /* 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 an integer feature node. */ nodeType = GenApi.NodeGetType(hNode); if (EGenApiNodeType.IntegerNode != nodeType) { Console.WriteLine("'" + featureName + "' is not an integer feature."); return; } /* * Query the current value, the range of allowed values, 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. */ bval = GenApi.NodeIsReadable(hNode); if (bval) { min = GenApi.IntegerGetMin(hNode); /* Get the minimum value. */ max = GenApi.IntegerGetMax(hNode); /* Get the maximum value. */ incr = GenApi.IntegerGetInc(hNode); /* Get the increment value. */ val = GenApi.IntegerGetValue(hNode); /* Get the current value. */ Console.WriteLine("{0}: min= {1} max= {2} incr={3} Value={4}", featureName, min, max, incr, val); bval = GenApi.NodeIsWritable(hNode); if (bval) { /* Set the Width parameter half-way between minimum and maximum. */ val = min + (max - min) / incr / 2 * incr; Console.WriteLine("Setting {0} to {1}", featureName, val); GenApi.IntegerSetValue(hNode, val); } else { Console.WriteLine("Cannot set value for feature '{0}' - node not writable.", featureName); } } else { Console.WriteLine("Cannot read feature '{0}' - node not readable.", featureName); } }