Micro-Epsilon:scanCONTROL:PythonWrapper
lastmod 2026-03-27created 2026-03-272 edits
Micro-Epsilon scanCONTROL 3D Sensor SDK - Python Wrapper
pymegc is a Python wrapper for Micro-Epsilon's MEGC (Micro-Epsilon Genicam Control) C library. Built on ctypes, it lets you discover sensor devices, connect to them, set parameters, and acquire 2D/3D measurement data from a Python environment.
Supported sensors
- scanCONTROL
- ReflectControl
- SurfaceControl
Supported platforms
- Windows (DLL)
- Linux (SO)
- macOS (DYLIB)
Installation
- Check the Python installation path (e.g.
C:\Program Files\Python310) - Copy the
PythonWrapper/pymegcfolder into theLib\site-packagesdirectory - Run the example scripts in
PythonWrapper/examples/to confirm that everything works
Directory structure
PythonWrapper/
├── README.txt # 설치 안내
├── pymegc/ # 메인 라이브러리 패키지
│ ├── __init__.py # 패키지 초기화 (MEGC.py 재수출)
│ └── MEGC.py # ctypes 기반 C 라이브러리 바인딩 (자동 생성)
└── examples/ # 18개 예제 스크립트
├── FindDevices/ # 장치 검색
├── DeviceInfo/ # 장치 정보 조회
├── ParameterList/ # 파라미터 목록 출력
├── ReadOnlyAccess/ # 읽기 전용 접근
├── ScanControl2dMeasurement/ # 2D 측정 (콜백)
├── ScanControl3dMeasurement/ # 3D 측정 (콜백)
├── ScanControl2dMeasurementPoll/ # 2D 측정 (폴링)
├── ScanControl3dMeasurementPoll/ # 3D 측정 (폴링)
├── ReflectControl2dMeasurement/ # ReflectControl 2D (콜백)
├── ReflectControl3dMeasurement/ # ReflectControl 3D (콜백)
├── ReflectControl2dMeasurementPoll/ # ReflectControl 2D (폴링)
├── ReflectControl3dMeasurementPoll/ # ReflectControl 3D (폴링)
├── ScanControlCameraLive/ # 카메라 라이브 영상
├── ReflectControlCameraLive/ # ReflectControl 라이브 영상
├── SurfaceControl2dMeasurement/ # SurfaceControl 2D (콜백)
├── SurfaceControl3dMeasurement/ # SurfaceControl 3D (콜백)
├── SurfaceControl2dMeasurementPoll/ # SurfaceControl 2D (폴링)
└── SurfaceControl3dMeasurementPoll/ # SurfaceControl 3D (폴링)
Basic workflow
import ctypes as ct
import pymegc as megc
# 1. 시스템 초기화 및 장치 검색
sys_obj = megc.megc_system_t()
megc.SysInit(ct.byref(sys_obj))
megc.SysFindDevices(ct.byref(sys_obj))
# 2. 장치 정보 조회
device_count = megc.SysGetDeviceCount(ct.byref(sys_obj))
device = megc.SysGetDevice(ct.byref(sys_obj), 0)
# 3. MEGC 클라이언트 초기화 및 연결
megc_obj = megc.megc_t()
megc.Init(ct.byref(megc_obj))
megc.ConnectByDevice(ct.byref(megc_obj), device)
# 4. 파라미터 설정
params = megc.GetDeviceParams(ct.byref(megc_obj))
param = megc.ParamsGetParamByName(params, b"ExposureTime")
megc.ParamSetFloatValue(param, ct.c_double(100.0))
# 5. 컴포넌트 설정 및 획득 시작
# ... (측정 유형에 따라 다름)
# 6. 데이터 획득 (콜백 또는 폴링)
# ... (아래 상세 설명 참조)
# 7. 정리
megc.AcquisitionStop(ct.byref(megc_obj))
megc.Disconnect(ct.byref(megc_obj))
megc.Destroy(ct.byref(megc_obj))
megc.SysDestroy(ct.byref(sys_obj))
API reference
System functions (System)
Functions that discover and manage devices at the system level.
| Function | Parameters | Return value | Description |
| | megc_system_t pointer | Status code | Initializes the system object |
| | megc_system_t pointer | Status code | Cleans up the system object |
| | megc_system_t pointer | Status code | Searches for devices on the network |
| | megc_system_t pointer | Integer | Returns the number of devices found |
| | System pointer, index | megc_device_t pointer | Gets a device by index |
| | System pointer, IP string | megc_device_t pointer | Gets a device by IP address |
| | System pointer, serial number | megc_device_t pointer | Gets a device by serial number |
| | System pointer, pattern string | megc_device_t pointer | Gets a device by pattern |
| | megc_system_t pointer | Integer | Returns the number of network interfaces |
| | System pointer, index | megc_interface_t pointer | Gets a network interface |
Connection functions (Connection)
Handles initializing, connecting, and disconnecting the MEGC client object.
| Function | Parameters | Return value | Description |
| | megc_t pointer | Status code | Initializes the MEGC client object |
| | megc_t pointer | Status code | Initializes an empty MEGC object |
| | Client pointer, device pointer | Status code | Connects using a device handle |
| | Client pointer, IP string | Status code | Connects by IP address |
| | Client pointer, serial number | Status code | Connects by serial number |
| | Client pointer, pattern | Status code | Connects by pattern |
| | megc_t pointer | Status code | Disconnects from the device |
| | megc_t pointer | Status code | Cleans up the MEGC object |
Device info functions (Device Info)
Retrieves attribute information of the connected device.
| Function | Description |
| | Get model name |
| | Get vendor name |
| | Get serial number |
| | Get IP address |
| | Get MAC address |
| | Get subnet mask |
| | Get default gateway |
| | Get device ID |
| | Get GigE Vision version |
| | Whether DHCP is enabled |
| | Whether DHCP is available |
| | Whether Link-Local Address is enabled |
| | Whether static IP is enabled |
| | Change IP configuration |
Usage example:
# 장치 모델명 조회
buffer_size = ct.c_ulong(256)
buffer = ct.create_string_buffer(256)
megc.DeviceGetModelName(device, buffer, ct.byref(buffer_size))
print(f"모델명: {buffer.value.decode()}")
# 장치 시리얼 번호 조회
megc.DeviceGetSerialNumber(device, buffer, ct.byref(buffer_size))
print(f"시리얼: {buffer.value.decode()}")
# IP 주소 조회
megc.DeviceGetIPAddress(device, buffer, ct.byref(buffer_size))
print(f"IP: {buffer.value.decode()}")
Parameter functions (Parameter)
Functions that get and set device parameters.
Parameter types
| Constant | Value | Description |
| | 0 | None |
| | 1 | Boolean |
| | 2 | Command |
| | 3 | Enumeration |
| | 4 | Floating point |
| | 5 | Integer |
| | 6 | Unsigned integer |
| | 7 | String |
| | 8 | Register |
Parameter access functions
| Function | Description |
| | Get parameter type |
| | Get parameter name |
| | Get display name |
| | Get description |
| | Get tooltip |
| | Get unit |
| | Get visibility level |
| | Whether available |
| | Whether readable |
| | Whether writable |
Getting/setting values by type
| Type | Read function | Write function | Get range |
| Boolean | | | - |
| Integer | | | |
| UInteger | | | |
| Float | | | |
| String | | | |
| Enum | | | |
| Register | | | |
| Command | - | | - |
Enum parameter functions
| Function | Description |
| | Set enumeration value by name |
| | Get enumeration value as a string |
| | Get number of enumeration entries |
| | Get entry name by index |
| | Get display name by index |
| | Get entry value by index |
| | Whether the entry is available |
Usage example:
# 파라미터 컬렉션 가져오기
params = megc.GetDeviceParams(ct.byref(megc_obj))
param_count = megc.GetDeviceParamsCount(ct.byref(megc_obj))
# 이름으로 파라미터 가져오기
param = megc.ParamsGetParamByName(params, b"ExposureTime")
# Float 값 읽기
value = ct.c_double()
megc.ParamGetFloatValue(param, ct.byref(value))
print(f"노출 시간: {value.value}")
# Float 범위 조회
min_val = ct.c_double()
max_val = ct.c_double()
megc.ParamGetFloatMinMaxValues(param, ct.byref(min_val), ct.byref(max_val))
print(f"범위: {min_val.value} ~ {max_val.value}")
# Float 값 쓰기
megc.ParamSetFloatValue(param, ct.c_double(200.0))
# Integer 파라미터 예시
param_width = megc.ParamsGetParamByName(params, b"Width")
int_value = ct.c_longlong()
megc.ParamGetIntegerValue(param_width, ct.byref(int_value))
print(f"Width: {int_value.value}")
# Enum 파라미터 예시
param_trigger = megc.ParamsGetParamByName(params, b"TriggerMode")
megc.ParamSetEnumValueByName(param_trigger, b"On")
Parameter collection functions (Params)
| Function | Description |
| | Get device parameter collection |
| | Get number of device parameters |
| | Get stream parameter collection |
| | Get number of stream parameters |
| | Get communication parameter collection |
| | Get number of communication parameters |
| | Find parameter by name |
| | Get parameter by index |
| | Find category by name |
| | Get category by index |
| | Get number of categories |
| | Get parameter within a category |
Component functions (Component)
Manages image sources (components). A sensor can provide several kinds of images, and you enable only the components you need.
| Function | Description |
| | Get component by index |
| | Get array of all components |
| | Get number of components |
| | Enable/disable a component |
| | Check whether enabled |
| | Get component selector |
| | Set component selector |
| | Get source selector |
| | Set source selector |
| | Get region selector |
| | Set region selector |
Acquisition functions (Acquisition)
Starts and controls data acquisition.
| Function | Description |
| | Start acquisition (convenience function) |
| | Stop acquisition (convenience function) |
| | Start continuous acquisition |
| | Acquisition with a specified mode (0=continuous, 1=single frame) |
| | Stop acquisition |
| | Abort acquisition |
| | Check whether acquisition is active |
| | Set acquisition mode |
Data reception methods
Callback method (Callback)
Receives images asynchronously. When an image arrives, the registered callback function is called automatically.
| Function | Description |
| | Register a single-image callback |
| | Register an image vector callback |
| | Register an event callback |
| | Register a disconnect callback |
Callback function signatures:
# 단일 이미지 콜백
@ct.CFUNCTYPE(None, ct.POINTER(megc.meg_image_t), ct.c_void_p)
def image_callback(image, user_data):
# 이미지 처리 로직
pass
# 이미지 벡터 콜백
@ct.CFUNCTYPE(None, ct.POINTER(megc.meg_image_vec_t), ct.c_void_p)
def image_vec_callback(image_vec, user_data):
# 복수 이미지 처리 로직
pass
Polling method (Polling)
Waits synchronously until an image arrives. Suitable for script-based sequential processing.
# 이미지 벡터 초기화
image_vec = megc.meg_image_vec_t()
megc.ImageVecInitEmpty(ct.byref(image_vec))
# 타임아웃(밀리초)으로 이미지 대기
status = megc.PollImages(ct.byref(megc_obj), ct.byref(image_vec), 20000, None)
if megc.MEGC_STATUS_IS_OK(status):
# 이미지 처리
pass
# 정리
megc.ImageVecDestroy(ct.byref(image_vec))
Trigger functions (Trigger)
| Function | Description |
| | Set trigger mode |
| | Set trigger source |
| | Send a software trigger |
Image management functions (Image)
| Function | Description |
| | Initialize an image object |
| | Initialize an image from data |
| | Initialize an empty image |
| | Resize an image |
| | Free image memory |
| | Initialize an image vector |
| | Initialize an empty image vector |
| | Resize an image vector |
| | Free image vector memory |
Data structures
Image types
| Struct | Pixel format constant | Description |
| | | 8-bit monochrome image |
| | | 16-bit monochrome image |
| | - | 32-bit floating-point monochrome image |
| | | 8-bit RGB image |
| | | 16-bit RGB image |
| | | 8-bit RGBA image |
| | | 16-bit RGBA image |
| | | 3D point cloud (X, Y, Z coordinates) |
| | | 2D profile (amplitude + distance) |
| | | 16-bit amplitude/confidence |
| | | 32-bit confidence image |
3D point cloud data (meg_abc32f_t)
The core data structure used in 3D measurement.
# meg_abc32f_t 구조체 필드
# .a = X 좌표 (float32)
# .b = Y 좌표 (float32)
# .c = Z 좌표 (float32)
# 3D 이미지 데이터 접근 예시
data_ptr = ct.cast(image.contents.data, ct.POINTER(megc.meg_abc32f_t))
width = image.contents.width
height = image.contents.height
for row in range(height):
for col in range(width):
idx = row * width + col
x = data_ptr[idx].a
y = data_ptr[idx].b
z = data_ptr[idx].c
if not math.isnan(x): # 유효한 포인트만 처리
print(f"X={x:.3f}, Y={y:.3f}, Z={z:.3f}")
2D profile data (meg_ac32f_t)
The core data structure used in 2D measurement.
# meg_ac32f_t 구조체 필드
# .a = X 좌표/진폭 (float32)
# .c = Z 좌표/거리 (float32)
# 2D 프로파일 데이터 접근 예시
data_ptr = ct.cast(image.contents.data, ct.POINTER(megc.meg_ac32f_t))
width = image.contents.width
for col in range(width):
x = data_ptr[col].a
z = data_ptr[col].c
if not math.isnan(x):
print(f"X={x:.3f}, Z={z:.3f}")
Access modes
| Constant | Value | Description |
| | 0 | Unknown |
| | 1 | Open (can connect) |
| | 2 | Control mode (another client is in control) |
| | 3 | Read-only mode |
| | 4 | Exclusive access (blocks other clients) |
Setting up read-only access
Passively receives data from a device that another client is controlling.
# 접근 타입 확인
access_type = megc.GetAccessTypeByIPAddress(b"192.168.1.100")
if access_type == megc.MEGC_ACCESS_TYPE_CONTROL:
print("다른 클라이언트가 제어 중 - 읽기 전용 모드로 연결")
# 읽기 전용 모드로 설정 (포트 1042: 멀티캐스트 수신)
megc.SetAccessReadOnly(ct.byref(megc_obj), 1042)
# 또는 제어 모드로 전환
megc.SetAccessControl(ct.byref(megc_obj))
# 읽기 전용 여부 확인
is_readonly = megc.IsAccessReadOnly(ct.byref(megc_obj))
Error handling
Status codes
Every API function returns a status code. Status codes fall into the following three categories:
| Category | Condition | Helper function |
| Success || status == 0 | | |
| Warning | status > 0 | |
| Error | status < 0 | |
Common error codes
| Constant | Value | Description |
| | 0 | Success |
| | -1 | General error |
| | -2 | Out of memory |
| | -3 | Not initialized |
| | -4 | Internal error |
| | -6 | Out of range |
| | -200 | Failed to open device |
| | -201 | Failed to connect to device |
| | -202 | Failed to open stream |
| | -204 | Device not found |
| | -205 | Parameter not writable |
| | -206 | Parameter type mismatch |
| | -207 | Failed to write parameter |
| | -208 | Parameter not readable |
| | -209 | Invalid parameter value |
| | -213 | Acquisition already started |
| | -214 | Acquisition not started |
| | -225 | Timeout |
| | -226 | Device already open |
| | -229 | Callbacks and polling cannot be used at the same time |
| | 200 | Parameter range warning |
Getting the error message:
status = megc.ConnectByIPAddress(ct.byref(megc_obj), b"192.168.1.100")
if megc.MEGC_STATUS_IS_ERR(status):
error_msg = megc.GetErrorMessage(status)
print(f"오류 ({status}): {error_msg}")
Visibility levels
Controls the display level of parameters.
| Constant | Value | Description |
| | 0 | Shown to beginner users |
| | 1 | Shown to experts |
| | 2 | Shown to advanced experts |
| | 3 | Hidden |
| | 4 | Undefined |
Logging
| Function | Description |
| | Set log level |
| | Enable/disable logging |
| | Enable/disable console output |
| | Start logging |
| | Start logging to a file |
| | Stop logging |
| | Set log callback |
Log levels
| Constant | Value | Description |
| | 0x000 | Logging off |
| | 0x001 | Info |
| | 0x002 | Warning |
| | 0x004 | Error |
| | 0x008 | Severe |
| | 0x010 | Fatal |
Utility functions
| Function | Description |
| | Get library version |
| | Get detailed version information |
| | Get error message string |
| | Check license validity |
| | Get license error |
| | Wait for the specified time (ms) |
| | Get the byte size of a pixel type |
| | Set buffer count |
| | Get current buffer count |
| | Set thread delay |
File transfer
| Function | Description |
| | Upload a local file to the device |
| | Download a device file to the local machine |
| | Save the device XML description to a file |
Practical examples
Example 1: Device discovery (FindDevices)
Searches for all sensors connected to the network and prints their information.
import ctypes as ct
import pymegc as megc
# 시스템 초기화
megc_sys = megc.megc_system_t()
status = megc.SysInit(ct.byref(megc_sys))
if megc.MEGC_STATUS_IS_ERR(status):
print("시스템 초기화 실패")
exit(1)
# 장치 검색
megc.SysFindDevices(ct.byref(megc_sys))
device_count = megc.SysGetDeviceCount(ct.byref(megc_sys))
print(f"검색된 장치 수: {device_count}")
# 각 장치 정보 출력
buffer_size = ct.c_ulong(256)
buffer = ct.create_string_buffer(256)
for i in range(device_count):
device = megc.SysGetDevice(ct.byref(megc_sys), i)
buffer_size.value = 256
megc.DeviceGetModelName(device, buffer, ct.byref(buffer_size))
model = buffer.value.decode()
buffer_size.value = 256
megc.DeviceGetSerialNumber(device, buffer, ct.byref(buffer_size))
serial = buffer.value.decode()
buffer_size.value = 256
megc.DeviceGetIPAddress(device, buffer, ct.byref(buffer_size))
ip = buffer.value.decode()
print(f" [{i}] {model} (S/N: {serial}, IP: {ip})")
# 정리
megc.SysDestroy(ct.byref(megc_sys))
Example 2: 3D point cloud measurement (callback method)
Acquires 3D point cloud data from a scanCONTROL sensor.
import ctypes as ct
import pymegc as megc
import math
import time
# --- 콜백 함수 정의 ---
received_count = 0
@ct.CFUNCTYPE(None, ct.POINTER(megc.meg_image_t), ct.c_void_p)
def on_image(image, user_data):
global received_count
received_count += 1
img = image.contents
if img.type == megc.MEG_PIX_ABC32F:
data = ct.cast(img.data, ct.POINTER(megc.meg_abc32f_t))
valid_points = 0
for i in range(img.width * img.height):
if not math.isnan(data[i].a):
valid_points += 1
print(f"프레임 #{received_count}: {img.width}x{img.height}, "
f"유효 포인트: {valid_points}")
# --- 메인 로직 ---
# 시스템 초기화 및 장치 검색
megc_sys = megc.megc_system_t()
megc.SysInit(ct.byref(megc_sys))
megc.SysFindDevices(ct.byref(megc_sys))
if megc.SysGetDeviceCount(ct.byref(megc_sys)) == 0:
print("장치를 찾을 수 없습니다")
megc.SysDestroy(ct.byref(megc_sys))
exit(1)
device = megc.SysGetDevice(ct.byref(megc_sys), 0)
# MEGC 클라이언트 연결
megc_obj = megc.megc_t()
megc.Init(ct.byref(megc_obj))
megc.ConnectByDevice(ct.byref(megc_obj), device)
# 파라미터 설정
params = megc.GetDeviceParams(ct.byref(megc_obj))
# 노출 시간 설정
param = megc.ParamsGetParamByName(params, b"ExposureTime")
if param:
megc.ParamSetFloatValue(param, ct.c_double(100.0))
# 트리거 모드 설정
param = megc.ParamsGetParamByName(params, b"TriggerMode")
if param:
megc.ParamSetEnumValueByName(param, b"On")
# 3D 컴포넌트 활성화 (MEG_PIX_ABC32F)
comp_count = megc.GetComponentCount(ct.byref(megc_obj))
for i in range(comp_count):
comp = megc.GetComponent(ct.byref(megc_obj), i)
if comp and comp.contents.type == megc.MEG_PIX_ABC32F:
megc.ComponentEnable(ct.byref(megc_obj), comp, 1)
break
# 콜백 등록 및 획득 시작
megc.SetImageCallback(ct.byref(megc_obj), on_image, None)
megc.AcquisitionStart(ct.byref(megc_obj))
# 소프트웨어 트리거로 데이터 요청
for i in range(5):
megc.TriggerSoftware(ct.byref(megc_obj))
time.sleep(1)
# 정리
megc.AcquisitionStop(ct.byref(megc_obj))
megc.Disconnect(ct.byref(megc_obj))
megc.Destroy(ct.byref(megc_obj))
megc.SysDestroy(ct.byref(megc_sys))
print(f"총 수신 프레임: {received_count}")
Example 3: 2D profile measurement (polling method)
Acquires 2D profile data using the polling method.
import ctypes as ct
import pymegc as megc
import math
# 시스템 초기화 및 연결
megc_sys = megc.megc_system_t()
megc.SysInit(ct.byref(megc_sys))
megc.SysFindDevices(ct.byref(megc_sys))
device = megc.SysGetDevice(ct.byref(megc_sys), 0)
megc_obj = megc.megc_t()
megc.Init(ct.byref(megc_obj))
megc.ConnectByDevice(ct.byref(megc_obj), device)
# 파라미터 설정
params = megc.GetDeviceParams(ct.byref(megc_obj))
param = megc.ParamsGetParamByName(params, b"ExposureTime")
if param:
megc.ParamSetFloatValue(param, ct.c_double(100.0))
# 2D 컴포넌트 활성화 (MEG_PIX_AC32F)
comp_count = megc.GetComponentCount(ct.byref(megc_obj))
for i in range(comp_count):
comp = megc.GetComponent(ct.byref(megc_obj), i)
if comp and comp.contents.type == megc.MEG_PIX_AC32F:
megc.ComponentEnable(ct.byref(megc_obj), comp, 1)
break
# 이미지 벡터 초기화
image_vec = megc.meg_image_vec_t()
megc.ImageVecInitEmpty(ct.byref(image_vec))
# 획득 시작
megc.Start(ct.byref(megc_obj))
# 폴링으로 이미지 수신 (타임아웃: 20초)
for frame in range(5):
status = megc.PollImages(ct.byref(megc_obj), ct.byref(image_vec), 20000, None)
if megc.MEGC_STATUS_IS_OK(status):
# 이미지 벡터에서 데이터 추출
for j in range(image_vec.count):
img = image_vec.images[j]
if img.type == megc.MEG_PIX_AC32F:
data = ct.cast(img.data, ct.POINTER(megc.meg_ac32f_t))
print(f"프레임 #{frame}: 너비={img.width}")
# 처음 5개 포인트 출력
for k in range(min(5, img.width)):
x = data[k].a
z = data[k].c
if not math.isnan(x):
print(f" 포인트[{k}]: X={x:.3f}, Z={z:.3f}")
else:
print(f"폴링 실패: {status}")
# 정리
megc.Stop(ct.byref(megc_obj))
megc.ImageVecDestroy(ct.byref(image_vec))
megc.Disconnect(ct.byref(megc_obj))
megc.Destroy(ct.byref(megc_obj))
megc.SysDestroy(ct.byref(megc_sys))
Example 4: Listing parameters
Retrieves all device parameters by type and prints their current values.
import ctypes as ct
import pymegc as megc
# 연결 (생략: 위 예제 참조)
# ...
params = megc.GetDeviceParams(ct.byref(megc_obj))
param_count = megc.GetDeviceParamsCount(ct.byref(megc_obj))
buffer_size = ct.c_ulong(256)
buffer = ct.create_string_buffer(256)
for i in range(param_count):
param = megc.ParamsGetParam(params, i)
param_type = megc.ParamGetType(param)
buffer_size.value = 256
megc.ParamGetName(param, buffer, ct.byref(buffer_size))
name = buffer.value.decode()
# 읽기 가능한 파라미터만 값 표시
if not megc.ParamIsReadable(param):
print(f" {name}: [읽기 불가]")
continue
if param_type == megc.MEG_PARAM_BOOLEAN:
val = ct.c_ubyte()
megc.ParamGetBooleanValue(param, ct.byref(val))
print(f" {name} (Boolean): {bool(val.value)}")
elif param_type == megc.MEG_PARAM_INTEGER:
val = ct.c_longlong()
megc.ParamGetIntegerValue(param, ct.byref(val))
min_v, max_v, inc = ct.c_longlong(), ct.c_longlong(), ct.c_longlong()
megc.ParamGetIntegerMinMaxIncValues(param, ct.byref(min_v), ct.byref(max_v), ct.byref(inc))
print(f" {name} (Integer): {val.value} [{min_v.value}..{max_v.value}, step={inc.value}]")
elif param_type == megc.MEG_PARAM_FLOAT:
val = ct.c_double()
megc.ParamGetFloatValue(param, ct.byref(val))
min_v, max_v = ct.c_double(), ct.c_double()
megc.ParamGetFloatMinMaxValues(param, ct.byref(min_v), ct.byref(max_v))
print(f" {name} (Float): {val.value} [{min_v.value}..{max_v.value}]")
elif param_type == megc.MEG_PARAM_ENUM:
val = ct.c_longlong()
megc.ParamGetEnumValue(param, ct.byref(val))
buffer_size.value = 256
megc.ParamGetEnumStringValue(param, buffer, ct.byref(buffer_size))
print(f" {name} (Enum): {buffer.value.decode()} ({val.value})")
elif param_type == megc.MEG_PARAM_STRING:
buffer_size.value = 256
megc.ParamGetStringValue(param, buffer, ct.byref(buffer_size))
print(f" {name} (String): {buffer.value.decode()}")
Example 5: Read-only access (ReadOnlyAccess)
Passively monitors data from a device that another client is controlling.
import ctypes as ct
import pymegc as megc
device_ip = b"192.168.1.100"
# 접근 타입 확인
access_type = megc.GetAccessTypeByIPAddress(device_ip)
print(f"접근 타입: {access_type}")
if access_type == megc.MEGC_ACCESS_TYPE_OPEN:
print("장치가 사용 가능합니다 - 제어 모드로 연결")
elif access_type == megc.MEGC_ACCESS_TYPE_CONTROL:
print("다른 클라이언트가 제어 중 - 읽기 전용으로 연결")
# 클라이언트 초기화 및 읽기 전용 설정
megc_obj = megc.megc_t()
megc.Init(ct.byref(megc_obj))
megc.SetAccessReadOnly(ct.byref(megc_obj), 1042) # 멀티캐스트 포트
megc.ConnectByIPAddress(ct.byref(megc_obj), device_ip)
# 콜백 등록 후 데이터 수신
megc.SetImageCallback(ct.byref(megc_obj), on_image, None)
megc.Start(ct.byref(megc_obj))
# ... 데이터 수신 대기 ...
# 정리
megc.Stop(ct.byref(megc_obj))
megc.Disconnect(ct.byref(megc_obj))
megc.Destroy(ct.byref(megc_obj))
Common device parameters
A list of parameters frequently used with the sensors.
| Parameter name | Type | Description |
| | Float | Sensor exposure time (microseconds) |
| | Integer | Image width (pixels) |
| | Integer | Image height (pixels) |
| | Integer | Horizontal binning factor |
| | Enum | Region of interest (ROI) mode |
| | Enum | Region of interest selection |
| | Enum | Trigger mode (On/Off) |
| | Enum | Trigger selection |
| | Float | Scan line rate (lines/sec) |
| | Float | Frame rate (frames/sec) |
| | Enum | 3D coordinate selection |
| | Boolean | Enable invalid data marker |
| | Float | Invalid data value (default: NaN) |
| | Integer | Profile counter (chunk data) |
| | Enum | Encoder output mode |
| | Integer | Data request timeout (ms) |
Differences by sensor
| Feature | scanCONTROL 3xxx | scanCONTROL 8xxx | ReflectControl | SurfaceControl |
| Starting acquisition | | | | |
| Trigger | Triggered directly by acquisition mode | Uses | Same | Same |
| Frame rate | | | Varies by device | Varies by device |
| Region mode | Must be configured | Uses default | Uses default | Uses default |
| Camera live | MONO8/MONO10 | MONO8/MONO10 | MONO8/MONO10 | MONO8/MONO10 |
Network interfaces
| Function | Description |
| | Get interface description |
| | Get interface IP address |
| | Get interface MAC address |
| | Get subnet mask |
| | Get default gateway |
| | Get number of IP addresses |
| | Get number of connected devices |
| | Get device by index |
| | Make the IP address static |
Multicast streaming
Best practices
Resource management
- Always call
Destroy()andSysDestroy()to release resources - Free image vectors with
ImageVecDestroy() - Use try/finally blocks so cleanup runs even when an exception occurs
Error handling
- Check the status with
MEGC_STATUS_IS_ERR()after every API call - Get detailed error messages with
GetErrorMessage()
Performance optimization
- Enable only the components you need
- Set an appropriate buffer count (
SetBufferCount()) - Use the callback method when processing large volumes of data
- The polling method is simpler for script-based sequential processing
Callback vs polling
| Method | Pros | Cons | Best for |
| Callback | Asynchronous, high throughput, real-time | Requires attention to thread safety | Continuous monitoring, high-speed acquisition |
| Polling | Simple code, sequential processing | Waits on timeouts, lower throughput | Scripts, one-off measurements |
| WARNING |
| Using callbacks and polling at the same time raises the |
Troubleshooting
| Symptom | Cause | Solution |
| Device not found | Network configuration problem | Check firewall settings; check that it is on the same subnet as the sensor |
| Connection failed (-201) | Another client has exclusive access | Check the access type with |
| Timeout (-225) | Trigger not sent | Check the trigger mode/source settings; check that |
| Data is NaN | Points outside the measurement range | Check the |
| License error | DLL license problem | Check with |
| Parameter write failed (-207) | Parameter cannot be changed during acquisition | Stop acquisition, then change the parameter |
README.txt
How to install PythonWrapper
- Identify your Python installation folder, e.g. C:\Program Files\Python310
- Go to folder Lib\site-packages, e.g. C:\Program Files\Python310\Lib\site-packages
- From PythonWrapper, copy the pymegc folder to site-packages
- Test your installation by running a sample in PythonWrapper/examples/*