Can't import python Async functions, throws 'Python Error: RuntimeError: Cannot change thread mode after it is set'

7 visualizaciones (últimos 30 días)
So, I have created a python API which uses Bleak and Winrt library to connect to a BLE device and write to a specific characteristic.
Now, usually I try to import the API using py.importlib.import_module() and then do a py.importlib.reload().
But now when I do this I get the error - Python Error: RuntimeError: Cannot change thread mode after it is set.This error is encountered due to winrt library. If I comment that out I won't get any error when I press run.
But now the next error I encounter is after running the API functions. Which states : sys:1: RuntimeWarning: coroutine 'getBleDetails' was never awaited. RuntimeWarning: Enable tracemalloc to get the object allocation traceback
The Codes are attached below :
test_ble.m
% Set the threading mode in Python before importing the module
pe = eval("pyenv");
if ~strcmp(pe.Version,'3.9')
eval("pyenv('Version','3.9')");
end
% Import the Python module and reload it
try
bluetooth_ble = py.importlib.import_module('bluetooth_handler');
py.importlib.reload(bluetooth_ble);
catch ME
disp(ME)
end
fname = 'bluetoothAddr.txt';
script_file = fileread(fname);
line = split(script_file,newline);
bluetoothMac = strip(line{1});
response = eval("py.bluetooth_handler.getBleDetails(bluetoothMac)");
response = eval("bluetooth_ble.sendCommand(bluetoothMac)")
bluetooth_handler.py
import asyncio
from bleak import BleakScanner, BleakClient
from winrt.windows.devices import radios
import struct
async def powerBluetooth(state):
"""
Method to Turn On, Off system Bluetooth
Args:
state (str): Enter `ON` to turn on device Bluetooth or `OFF` to turn off device Bluetooth
Returns:
bool: Returns `True` is successfully set Bluetooth or `False` on failure
"""
try:
all_radios = await radios.Radio.get_radios_async()
bluetooth_radio = None
for this_radio in all_radios:
if this_radio.kind == radios.RadioKind.BLUETOOTH:
bluetooth_radio = this_radio
break
if bluetooth_radio is not None:
if state == "ON":
if bluetooth_radio.state != radios.RadioState.ON:
await bluetooth_radio.set_state_async(radios.RadioState.ON)
else:
if bluetooth_radio.state != radios.RadioState.OFF:
await bluetooth_radio.set_state_async(radios.RadioState.OFF)
else:
print("Bluetooth Radio not found.")
return True # Success
except Exception as e:
print(f"An error occurred while powering Bluetooth: {str(e)}")
return False # Failure
async def sendCommand(address,mode='normalmode'):
try:
async with BleakClient(address) as client:
# print('Got Connection')
# await asyncio.sleep(10)
config_uuid = 'xxx-xxx-xxx'
config_char = client.services.get_characteristic(config_uuid)
if config_char:
try:
// Read write characteristics
except Exception as e:
print(f'Error Setting Mode : {e}')
return False
else:
print('Requested Characteristic not found')
return False
except Exception as e:
print(f'Error Connecting Device : {e}')
return False
if __name__ == "__main__":
# asyncio.run(bleDiscover())
devAddr = asyncio.run(getBleDetails())
if devAddr:
asyncio.run(sendCommand(devAddr))
else:
print("Device not found")
My reason to use Python and not MATLAB in-built BLE function is : MATLAB BLE interface requires the device to be manually paired to the PC. While using python code I can choose which device to pair.
How can I import this API to work with MATLAB ?
  1 comentario
Malay Agarwal
Malay Agarwal el 29 de Ag. de 2024
Editada: Malay Agarwal el 29 de Ag. de 2024
Hi @palak,
Your Python code seems to be missing the getBleDetails function. Could you post the code for the function?

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Python Package Integration en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by