Skip to content
Search

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

  1. Check the Python installation path (e.g. C:\Program Files\Python310)
  2. Copy the PythonWrapper/pymegc folder into the Lib\site-packages directory
  3. Run the example scripts in PythonWrapper/examples/ to confirm that everything works
# Linux/macOS 예시
cp -r PythonWrapper/pymegc /path/to/python/lib/site-packages/

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

SysInit(megc_sys)

megc_system_t pointer

Status code

Initializes the system object

SysDestroy(megc_sys)

megc_system_t pointer

Status code

Cleans up the system object

SysFindDevices(megc_sys)

megc_system_t pointer

Status code

Searches for devices on the network

SysGetDeviceCount(megc_sys)

megc_system_t pointer

Integer

Returns the number of devices found

SysGetDevice(megc_sys, index)

System pointer, index

megc_device_t pointer

Gets a device by index

SysGetDeviceByIP(megc_sys, ip)

System pointer, IP string

megc_device_t pointer

Gets a device by IP address

SysGetDeviceBySerialNumber(megc_sys, serial)

System pointer, serial number

megc_device_t pointer

Gets a device by serial number

SysGetDeviceByPattern(megc_sys, pattern)

System pointer, pattern string

megc_device_t pointer

Gets a device by pattern

SysGetInterfaceCount(megc_sys)

megc_system_t pointer

Integer

Returns the number of network interfaces

SysGetInterface(megc_sys, index)

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

Init(megc_obj)

megc_t pointer

Status code

Initializes the MEGC client object

InitEmpty(megc_obj)

megc_t pointer

Status code

Initializes an empty MEGC object

ConnectByDevice(megc_obj, device)

Client pointer, device pointer

Status code

Connects using a device handle

ConnectByIPAddress(megc_obj, ip)

Client pointer, IP string

Status code

Connects by IP address

ConnectBySerialNumber(megc_obj, serial)

Client pointer, serial number

Status code

Connects by serial number

ConnectByPattern(megc_obj, pattern)

Client pointer, pattern

Status code

Connects by pattern

Disconnect(megc_obj)

megc_t pointer

Status code

Disconnects from the device

Destroy(megc_obj)

megc_t pointer

Status code

Cleans up the MEGC object

Device info functions (Device Info)

Retrieves attribute information of the connected device.

Function

Description

DeviceGetModelName(device, buffer, size)

Get model name

DeviceGetVendorName(device, buffer, size)

Get vendor name

DeviceGetSerialNumber(device, buffer, size)

Get serial number

DeviceGetIPAddress(device, buffer, size)

Get IP address

DeviceGetMACAddress(device, buffer, size)

Get MAC address

DeviceGetSubnetMask(device, buffer, size)

Get subnet mask

DeviceGetDefaultGateway(device, buffer, size)

Get default gateway

DeviceGetID(device, buffer, size)

Get device ID

DeviceGetGEVVersion(device)

Get GigE Vision version

DeviceIsDHCPEnabled(device)

Whether DHCP is enabled

DeviceIsDHCPAvailable(device)

Whether DHCP is available

DeviceIsLLAEnabled(device)

Whether Link-Local Address is enabled

DeviceIsPersistentEnabled(device)

Whether static IP is enabled

DeviceSetIPConfiguration(device, ip, subnet, gateway)

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

MEG_PARAM_NONE

0

None

MEG_PARAM_BOOLEAN

1

Boolean

MEG_PARAM_COMMAND

2

Command

MEG_PARAM_ENUM

3

Enumeration

MEG_PARAM_FLOAT

4

Floating point

MEG_PARAM_INTEGER

5

Integer

MEG_PARAM_UINTEGER

6

Unsigned integer

MEG_PARAM_STRING

7

String

MEG_PARAM_REGISTER

8

Register

Parameter access functions

Function

Description

ParamGetType(param)

Get parameter type

ParamGetName(param, buffer, size)

Get parameter name

ParamGetDisplayName(param, buffer, size)

Get display name

ParamGetDescription(param, buffer, size)

Get description

ParamGetTooltip(param, buffer, size)

Get tooltip

ParamGetUnit(param, buffer, size)

Get unit

ParamGetVisibility(param)

Get visibility level

ParamIsAvailable(param)

Whether available

ParamIsReadable(param)

Whether readable

ParamIsWritable(param)

Whether writable

Getting/setting values by type

Type

Read function

Write function

Get range

Boolean

ParamGetBooleanValue(param, value)

ParamSetBooleanValue(param, value)

-

Integer

ParamGetIntegerValue(param, value)

ParamSetIntegerValue(param, value)

ParamGetIntegerMinMaxIncValues(param, min, max, inc)

UInteger

ParamGetUIntegerValue(param, value)

ParamSetUIntegerValue(param, value)

ParamGetUIntegerMinMaxIncValues(param, min, max, inc)

Float

ParamGetFloatValue(param, value)

ParamSetFloatValue(param, value)

ParamGetFloatMinMaxValues(param, min, max)

String

ParamGetStringValue(param, buffer, size)

ParamSetStringValue(param, value)

ParamGetStringMaxSize(param, size)

Enum

ParamGetEnumValue(param, value)

ParamSetEnumValue(param, value)

ParamGetEnumEntryCount(param)

Register

ParamGetRegisterValue(param, buffer, size)

ParamSetRegisterValue(param, buffer, size)

ParamGetRegisterSize(param, size)

Command

-

ParamSendCommand(param)

-

Enum parameter functions

Function

Description

ParamSetEnumValueByName(param, name)

Set enumeration value by name

ParamGetEnumStringValue(param, buffer, size)

Get enumeration value as a string

ParamGetEnumEntryCount(param)

Get number of enumeration entries

ParamGetEnumEntryName(param, index, buffer, size)

Get entry name by index

ParamGetEnumEntryDisplayName(param, index, buffer, size)

Get display name by index

ParamGetEnumEntryValue(param, index, value)

Get entry value by index

ParamGetEnumEntryAvailable(param, 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

GetDeviceParams(megc_obj)

Get device parameter collection

GetDeviceParamsCount(megc_obj)

Get number of device parameters

GetStreamParams(megc_obj)

Get stream parameter collection

GetStreamParamsCount(megc_obj)

Get number of stream parameters

GetCommunicationParams(megc_obj)

Get communication parameter collection

GetCommunicationParamsCount(megc_obj)

Get number of communication parameters

ParamsGetParamByName(params, name)

Find parameter by name

ParamsGetParam(params, index)

Get parameter by index

ParamsGetCategoryByName(params, name)

Find category by name

ParamsGetCategory(params, index)

Get category by index

ParamsGetCategoryCount(params)

Get number of categories

ParamsGetParamInCategory(params, category, index)

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

GetComponent(megc_obj, index)

Get component by index

GetComponentArray(megc_obj)

Get array of all components

GetComponentCount(megc_obj)

Get number of components

ComponentEnable(megc_obj, component, enable)

Enable/disable a component

ComponentIsEnabled(megc_obj, component)

Check whether enabled

GetComponentSelector(megc_obj, selector)

Get component selector

SetComponentSelector(megc_obj, selector)

Set component selector

GetSourceSelector(megc_obj, selector)

Get source selector

SetSourceSelector(megc_obj, selector)

Set source selector

GetRegionSelector(megc_obj, selector)

Get region selector

SetRegionSelector(megc_obj, selector)

Set region selector

Acquisition functions (Acquisition)

Starts and controls data acquisition.

Function

Description

Start(megc_obj)

Start acquisition (convenience function)

Stop(megc_obj)

Stop acquisition (convenience function)

AcquisitionStart(megc_obj)

Start continuous acquisition

AcquisitionStartMode(megc_obj, mode, count)

Acquisition with a specified mode (0=continuous, 1=single frame)

AcquisitionStop(megc_obj)

Stop acquisition

AcquisitionAbort(megc_obj)

Abort acquisition

IsAcquisitionActive(megc_obj)

Check whether acquisition is active

SetAcquisitionMode(megc_obj, mode)

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

SetImageCallback(megc_obj, callback, user_data)

Register a single-image callback

SetImageVecCallback(megc_obj, callback, user_data)

Register an image vector callback

SetEventCallback(megc_obj, callback, user_data)

Register an event callback

SetDisconnectCallback(megc_obj, callback, user_data)

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

SetTriggerMode(megc_obj, mode)

Set trigger mode

SetTriggerSource(megc_obj, source)

Set trigger source

TriggerSoftware(megc_obj)

Send a software trigger

Image management functions (Image)

Function

Description

ImageInit(image, width, height, type)

Initialize an image object

ImageInitData(image, data, width, height, type)

Initialize an image from data

ImageInitEmpty(image)

Initialize an empty image

ImageResize(image, width, height)

Resize an image

ImageDestroy(image)

Free image memory

ImageVecInit(vec, count)

Initialize an image vector

ImageVecInitEmpty(vec)

Initialize an empty image vector

ImageVecResize(vec, count)

Resize an image vector

ImageVecDestroy(vec)

Free image vector memory

Data structures

Image types

Struct

Pixel format constant

Description

meg_image_mono8_t

MEG_PIX_MONO8 (0x01008001)

8-bit monochrome image

meg_image_mono16_t

MEG_PIX_MONO16 (0x01010007)

16-bit monochrome image

meg_image_mono32f_t

-

32-bit floating-point monochrome image

meg_image_rgb8_t

MEG_PIX_RGB8 (0x02018014)

8-bit RGB image

meg_image_rgb16_t

MEG_PIX_RGB16 (0x02030033)

16-bit RGB image

meg_image_rgba8_t

MEG_PIX_RGBA8 (0x02020016)

8-bit RGBA image

meg_image_rgba16_t

MEG_PIX_RGBA16 (0x02040063)

16-bit RGBA image

meg_image_abc32f_t

MEG_PIX_ABC32F (0x020060C0)

3D point cloud (X, Y, Z coordinates)

meg_image_ac32f_t

MEG_PIX_AC32F (0x020040C2)

2D profile (amplitude + distance)

meg_image_ac16_t

MEG_PIX_AC16 (0x020020BB)

16-bit amplitude/confidence

meg_image_c32f_t

MEG_PIX_C32F (0x010020BF)

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

MEGC_ACCESS_TYPE_UNKNOWN

0

Unknown

MEGC_ACCESS_TYPE_OPEN

1

Open (can connect)

MEGC_ACCESS_TYPE_CONTROL

2

Control mode (another client is in control)

MEGC_ACCESS_TYPE_READONLY

3

Read-only mode

MEGC_ACCESS_TYPE_EXCLUSIVE

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

MEGC_STATUS_IS_OK(status)

Warning

status > 0

MEGC_STATUS_IS_WARN(status)

Error

status < 0

MEGC_STATUS_IS_ERR(status)

Common error codes

Constant

Value

Description

MEGC_OK

0

Success

MEGC_ERROR

-1

General error

MEGC_ERR_OUT_OF_MEMORY

-2

Out of memory

MEGC_ERR_UNINITIALIZED

-3

Not initialized

MEGC_ERR_INTERNAL

-4

Internal error

MEGC_ERR_OUT_OF_RANGE

-6

Out of range

MEGC_ERR_DEVICE_OPEN_FAILED

-200

Failed to open device

MEGC_ERR_DEVICE_CONNECT_FAILED

-201

Failed to connect to device

MEGC_ERR_STREAM_OPEN_FAILED

-202

Failed to open stream

MEGC_ERR_DEVICE_NOT_FOUND

-204

Device not found

MEGC_ERR_PARAM_NOT_WRITEABLE

-205

Parameter not writable

MEGC_ERR_PARAM_TYPE_MISMATCH

-206

Parameter type mismatch

MEGC_ERR_PARAM_WRITE_FAILED

-207

Failed to write parameter

MEGC_ERR_PARAM_NOT_READABLE

-208

Parameter not readable

MEGC_ERR_PARAM_INVALID_VALUE

-209

Invalid parameter value

MEGC_ERR_ACQUI_ALREADY_STARTED

-213

Acquisition already started

MEGC_ERR_ACQUI_NOT_STARTED

-214

Acquisition not started

MEGC_ERR_TIMEOUT

-225

Timeout

MEGC_ERR_DEVICE_ALREADY_OPEN

-226

Device already open

MEGC_ERR_POLL_WITH_CALLBACK

-229

Callbacks and polling cannot be used at the same time

MEGC_WARN_PARAMETER_RANGE

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

MEG_VIS_BEGINNER

0

Shown to beginner users

MEG_VIS_EXPERT

1

Shown to experts

MEG_VIS_GURU

2

Shown to advanced experts

MEG_VIS_INVISIBLE

3

Hidden

MEG_VIS_UNDEFINED

4

Undefined

Logging

Function

Description

LogSetLevel(level)

Set log level

LogSetEnable(enable)

Enable/disable logging

LogSetConsole(enable)

Enable/disable console output

LogStart()

Start logging

LogStartFilename(filename)

Start logging to a file

LogStop()

Stop logging

LogSetCallback(callback)

Set log callback

Log levels

Constant

Value

Description

MEG_LOGLVL_OFF

0x000

Logging off

MEG_LOGLVL_INFO

0x001

Info

MEG_LOGLVL_WARN

0x002

Warning

MEG_LOGLVL_ERROR

0x004

Error

MEG_LOGLVL_SEVERE

0x008

Severe

MEG_LOGLVL_FATAL

0x010

Fatal

Utility functions

Function

Description

GetVersion()

Get library version

GetVersionDetail()

Get detailed version information

GetErrorMessage(status)

Get error message string

CheckLicense()

Check license validity

GetLicenseError()

Get license error

Sleep(milliseconds)

Wait for the specified time (ms)

PixelTypeGetSize(type)

Get the byte size of a pixel type

SetBufferCount(megc_obj, count)

Set buffer count

GetBufferCount(megc_obj)

Get current buffer count

SetThreadDelay(megc_obj, delay_ms)

Set thread delay

File transfer

Function

Description

UploadFile(megc_obj, local_path, device_path)

Upload a local file to the device

DownloadFile(megc_obj, device_path, local_path)

Download a device file to the local machine

DumpXML(megc_obj, filename)

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

ExposureTime

Float

Sensor exposure time (microseconds)

Width

Integer

Image width (pixels)

Height

Integer

Image height (pixels)

BinningHorizontal

Integer

Horizontal binning factor

RegionMode

Enum

Region of interest (ROI) mode

RegionSelector

Enum

Region of interest selection

TriggerMode

Enum

Trigger mode (On/Off)

TriggerSelector

Enum

Trigger selection

AcquisitionLineRate

Float

Scan line rate (lines/sec)

AcquisitionFrameRate

Float

Frame rate (frames/sec)

Scan3dCoordinateSelector

Enum

3D coordinate selection

Scan3dInvalidDataFlag

Boolean

Enable invalid data marker

Scan3dInvalidDataValue

Float

Invalid data value (default: NaN)

ChunkProfileCounter

Integer

Profile counter (chunk data)

EncoderOutputMode

Enum

Encoder output mode

RequestTimeout

Integer

Data request timeout (ms)

Differences by sensor

Feature

scanCONTROL 3xxx

scanCONTROL 8xxx

ReflectControl

SurfaceControl

Starting acquisition

AcquisitionStartMode(obj, 1, 1) (single frame)

AcquisitionStart(obj) (continuous)

AcquisitionStart(obj)

AcquisitionStart(obj)

Trigger

Triggered directly by acquisition mode

Uses TriggerSoftware(obj)

Same

Same

Frame rate

AcquisitionFrameRate

AcquisitionLineRate

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

InterfaceGetDescription(interface, buffer, size)

Get interface description

InterfaceGetIPAddress(interface, buffer, size)

Get interface IP address

InterfaceGetMACAddress(interface, buffer, size)

Get interface MAC address

InterfaceGetSubnetMask(interface, buffer, size)

Get subnet mask

InterfaceGetDefaultGateway(interface, buffer, size)

Get default gateway

InterfaceGetIPAddressCount(interface)

Get number of IP addresses

InterfaceGetDeviceCount(interface)

Get number of connected devices

InterfaceGetDevice(interface, index)

Get device by index

IPMakePersistent(interface, ip)

Make the IP address static

Multicast streaming

# 멀티캐스트 대상 주소 및 포트 설정
megc.SetStreamDestination(ct.byref(megc_obj), b"239.1.1.1", 1042)

Best practices

Resource management

  • Always call Destroy() and SysDestroy() 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 MEGC_ERR_POLL_WITH_CALLBACK (-229) error.

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 GetAccessTypeByIPAddress()

Timeout (-225)

Trigger not sent

Check the trigger mode/source settings; check that TriggerSoftware() is called

Data is NaN

Points outside the measurement range

Check the Scan3dInvalidDataFlag setting; filter for valid points

License error

DLL license problem

Check with CheckLicense(); get details with GetLicenseError()

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/*

See also

Favorite site

author Zer0 sitemap