How to "return" result from _IRQ_SCAN_RESULT

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
PM-TPI
Posts: 75
Joined: Fri Jun 28, 2019 3:09 pm

How to "return" result from _IRQ_SCAN_RESULT

Post by PM-TPI » Sat Nov 23, 2019 6:22 pm

How do i retrieve the "return rssiValue" without using a global variable ????

Code: Select all

import ubluetooth
from micropython import const

IRQ_SCAN_RESULT = const(1 << 4)
IRQ_SCAN_COMPLETE = const(1 << 5)
bt = ubluetooth.BLE()
bt.active(True)

def bt_irq(event, data):
    if event == _IRQ_SCAN_RESULT:
        addr_type, addr, connectabt, rssi, adv_data = data
        if adv_data[2:11] == b'ble-name':
           rssiValue = rssi
           return rssiValue	
       
    elif event == _IRQ_SCAN_COMPLETE:
        print("scan complete")
 
bt.gap_scan(9_000, 30_000, 30_000)
bt.irq(bt_irq)
 
# retrieve the "return rssiValue" value ???? 	


User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: How to "return" result from _IRQ_SCAN_RESULT

Post by jimmo » Mon Nov 25, 2019 2:06 am

Hi,

The scan method runs asynchronously. So there's nothing to "return" to.

Here are a couple of options:

1. Set it in a global variable, then wait for the global variable to be set:

Code: Select all

rssiValue = None

def bt_irq(event, data):
    global rssiValue
    ..code to handle scan result...
      rssiValue = rssi
      
       
bt.irq(bt_irq)
bt.gap_scan(9_000, 30_000, 30_000)

while rssiValue is None:
  time.sleep_ms(100)
  
# or just sleep_ms(9000) to wait for the scan to complete
2. Set it in a global variable, and wait for the scan complete event.

You might find the example in https://github.com/micropython/micropython/pull/5343 (ble_temperature_central.py) useful for an example of this.

3. Do whatever you need to do with the rssi as soon as you get the scan result.

If you can provide more info about what your program is doing then I can give a better example.

Also, I notice you're using adv_data[2:11] to extract the advertising name. See also in that PR for some code that does this in a more generic way. I hope that PR gets merged this week.

PM-TPI
Posts: 75
Joined: Fri Jun 28, 2019 3:09 pm

Re: How to "return" result from _IRQ_SCAN_RESULT

Post by PM-TPI » Sat Jul 04, 2020 3:03 pm

Would using schedule in "elif event == _IRQ_SCAN_DONE:" be an acceptable method to pass data...

Code: Select all

rssiValue = None
def bt_irq(event, data):
    global rssiValue
    if event == _IRQ_SCAN_RESULT:
	rssiValue = rssi
    elif event == _IRQ_SCAN_DONE:
        schedule(func, rssiValue)

Post Reply