[1.1.0] Multiple Observers threading --- use observeInBackground()

Asked by Michael

Need help in making the below code work. What I'm trying to do is have two regions and simultaneously observing the two regions using threading for images and when they appear, popup stating the image appears

import thread

reg1 = Region(76,61,569,635)
reg2 = Region(680,66,637,622)

def findMario():
    reg1.onAppear(r'C:\Sikuli Nightly\Mario_png.PNG', lambda e:popup("Mario Appeared"))
    reg1.observe(FOREVER)

def findMushroom():
    reg2.onAppear(r'C:\Sikuli Nightly\Mushroom2.PNG', lambda e:popup("Mushroomh Appeared"))
    reg2.observe(FOREVER, True)

if __name__ == '__main__':

    thread.start_new_thread(findMario,())
    thread.start_new_thread(findMushroom,())

The scripts doesn't observer, the moment run is pressed, the script is stopped without any errors. If i observe the whole screen, the following message is displayed
[error] Region: observe: already running for this region. Only one allowed!

Much appreciated if someone can provide resolution

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
RaiMan (raimund-hocke) said :
#1

Be sure to have the latest nightly 1.1.0 and looked into the docs about observe (revised yesterday).

-- 1. with your threading ...
 ... since you delegated everything to threads, the main script immediately stops after the last statement, since nothing else to do.

add a sufficient wait(someTime), and it should work.

-- 2. using the whole screen ...
... is problematic, since it is one "static" Region object and as the error tells you:
[error] Region: observe: already running for this region. Only one allowed!

so this would solve it:
reg1 = SCREEN
reg2 = Region(SCREEN) or reg2 = Screen(0)
which both create a new Region object for the whole screen

-- 3. we have our own threaded observe:
observeInBackground() runs in parallel

reg1 = Region(76,61,569,635)
reg2 = Region(680,66,637,622)

addImagePath(r'C:\Sikuli Nightly')

def findMario():
    reg1.onAppear('Mario_png.PNG', lambda e:popup("Mario Appeared"))
    reg1.observeInBackground(FOREVER)

def findMushroom():
    reg2.onAppear('Mushroom2.PNG', lambda e:popup("Mushroomh Appeared"))
    reg2.observeInBackground(FOREVER)

findMario()
findMushroom()
wait(60) # hoping something happens within 60 seconds

Revision history for this message
Best RaiMan (raimund-hocke) said :
#2

by the way:

someRegion.observeInBackground()

would be sufficient, since FOREVER is the default

Revision history for this message
Michael (michael-satish) said :
#3

Thanks RaiMan, it solved my problem

Revision history for this message
Michael (michael-satish) said :
#4

Thanks RaiMan, that solved my question.