pymetawear/c++: Delay after import required?

When I tried to create a counter data processor that counts events from a switch I ran into an interesting problem: apparently my code only runs when I add a delay after importing the MetaWearClient class. Otherwise I get a segmentation fault.

Here is my code:
from pymetawear.client import MetaWearClient

# Pause required after this line!

from pymetawear import libmetawear
from ctypes import cast, POINTER, c_uint
from pymetawear.mbientlab.metawear.core import Fn_VoidPtr, Fn_DataPtr, DataTypeId

c = MetaWearClient('D9:1B:01:B3:A9:01', 'pygatt')
switch_signal = libmetawear.mbl_mw_switch_get_state_data_signal(c.board)

# Callback: print the data
def sensor_data_print_uint32(data):
    assert(data.contents.type_id == DataTypeId.UINT32)
    data_ptr = cast(data.contents.value, POINTER(c_uint))
    print(data_ptr.contents.value)
callback_print = []
callback_print.append(Fn_DataPtr(sensor_data_print_uint32))

# Callback: counter is created, now subscribe to it
def counter_processor_created(signal):
    libmetawear.mbl_mw_datasignal_subscribe(signal, callback_print[0])

libmetawear.mbl_mw_dataprocessor_counter_create(switch_signal, Fn_VoidPtr(counter_processor_created))

Now there are actually two parts which I dont understand:

1. When I subscribe the sensor_data_print_uint32() function to the counters data signal, I have to store the Fn_DataPtr to an array (callback_print.append...) and then access it through the array. Otherwise It will not work.
I do not understand why this is the case (maybe something with pythons garbage collection...)

2. My main concern is the pymetawear.client.MetaWearClient import. I noticed that the code above only runs when I execute the first import statement in an interactive python shell, and when it is imported paste the rest of the code. Running the whole code as a script will result in a Segmentation Fault, just as pasting the script as a whole into an interactive python shell. In both cases the Segmentation Fault occurs right before libmetawear.mbl_mw_dataprocessor_counter_create(...) is called. Any idea why this is happening?

Best regards,
Johannes

Comments

This discussion has been closed.