Exemplo n.º 1
0
    def __init__(self):

        self._config_reader = ConfigReader()

        self.__enable_log = self._config_reader.get_log_enable_value()

        self.__set_log_path()

        self._robot_manager = RobotManager()

        self._info_manager = InfoManager()
        self._info_manager.tiny_update()

        self._robot_context = self._info_manager.get_info("ROBOT CONTEXT")
Exemplo n.º 2
0
    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """

        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()
Exemplo n.º 3
0
    def __init__(self):

        self._config_reader = ConfigReader()

        self.__enable_log = self._config_reader.get_log_enable_value()

        self.__set_log_path()
Exemplo n.º 4
0
    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """
        self._main_component = None
        self._sub_components = []

        self._timedout_main_components = []
        self._timedout_sub_components = []

        self._main_extra_img_log = None
        self._sub_extra_imgages_log = []

        self._rect_extra_timedout_image = None

        self._robot_manager = RobotManager()

        self._rf_is_set = self._robot_manager.context_is_set()


        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        self._timed_out_images = []

        self._find_thread_images = []
        self._find_thread_images_disappear = []
        #self._find_thread_images_copy = []
        self._last_thread_image = None
        self._last_thread_image_copy = None
        self._heartbeat_images = []
        self._heartbeat_images_copy = []

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._info_manager = InfoManager()
        self._scaling_factor = self._info_manager.get_info("SCALING FACTOR INT")

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()

        self.__enable_debug_calcperf = False

        #self._timer_for_disappear = 0

        self._object_is_found_flag = False

        self._is_object_finder = False
        self._objects_found_of_sub_object_finder = []
Exemplo n.º 5
0
class BaseFinder(object):


    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """
        self._main_component = None
        self._sub_components = []

        self._timedout_main_components = []
        self._timedout_sub_components = []

        self._main_extra_img_log = None
        self._sub_extra_imgages_log = []

        self._rect_extra_timedout_image = None

        self._robot_manager = RobotManager()

        self._rf_is_set = self._robot_manager.context_is_set()


        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        self._timed_out_images = []

        self._find_thread_images = []
        self._find_thread_images_disappear = []
        #self._find_thread_images_copy = []
        self._last_thread_image = None
        self._last_thread_image_copy = None
        self._heartbeat_images = []
        self._heartbeat_images_copy = []

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._info_manager = InfoManager()
        self._scaling_factor = self._info_manager.get_info("SCALING FACTOR INT")

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()

        self.__enable_debug_calcperf = False

        #self._timer_for_disappear = 0

        self._object_is_found_flag = False

        self._is_object_finder = False
        self._objects_found_of_sub_object_finder = []

    def _compress_image(self, img):
        return cv2.imencode('.png', img)[1]

    def _uncompress_image(self, compressed_img):
        return cv2.imdecode(compressed_img, cv2.CV_LOAD_IMAGE_GRAYSCALE)

    def set_name(self, name):
        """
        set the name of the object.

        :type name: string
        :param name: the name of the object
        """
        self._name = name
        self._log_manager.set_object_name(self._name)

    def get_name(self):
        """
        get the name of the object.

        :rtype: string
        :return: the name of the object
        """
        return self._name

    def set_name_with_caller(self):

        tmp_name = self._name

        for object_caller in self._objects_finders_caller:
            tmp_name = object_caller + os.sep + tmp_name

        self._name_with_caller = tmp_name
        self._log_manager.set_object_name(self._name_with_caller)

    def set_source_image_color(self, image_data):
        """
        set the color image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the color image
        """
        self._source_image_color = image_data.copy()
        img_gray = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY)
        self.set_source_image_gray(img_gray)
        #self._log_manager.set_image(self._source_image)

    def set_source_image_gray(self, image_data):
        """
        set the gray image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the gray image
        """
        self._source_image_gray = image_data.copy()

    def get_source_image_color(self):
        """
        get the color image on which the find method will search the object.

        :rtype: numpy.ndarray
        :return: the source color image
        """
        return self._source_image_color

    def get_source_image_gray(self):
        """
        get the gray image on which the find method will search the object.

        :rtype: numpy.ndarray
        :return: the source gray image
        """
        return self._source_image_gray

    def find(self):
        raise NotImplementedError

    def wait(self, timeout=-1, wait_disappear=False):
        """
        wait until the object appears on the screen.
        if timeout value is -1 (default value) then timeout value will be read from config file.
        if configuration file doesn't exist, then timeout value will be 15 sec.

        :param timeout: timeout in seconds
        :type timeout: int
        """

        #cv2.imwrite()

        #self._robot_manager.write_log_message("wait method: " + self.get_name(), "ERROR", False)
        #self._robot_manager.write_log_message("wait method: " + self.get_name(), "ERROR", False)
        #sss = self._robot_manager.get_suite_name()
        #ttt = self._robot_manager.get_testcase_name()

        #self._robot_manager.method1().method2()

        timeout_value = 15

        if timeout == -1:
            timeout_value = self._configReader.get_finder_wait_timeout()
        else:
            timeout_value = timeout

        self._objects_found = []

        self._heartbeat_images = []
        self._find_thread_images = []

        self._flag_thread_started = False
        self._flag_thread_have_to_exit = False

        self._heartbeat_images_copy = []

        time_elapsed = 0.0
        #time_of_last_change = 0.0
        self._time_checked_before_exit_start = None

        self._object_is_found_flag = False

        #screenCapture = ScreenManager()
        thread_interval = self._info_manager.get_info("FINDER THREAD INTERVAL") #self._configReader.get_finder_thread_interval()
        #thread_interval = 0.5
        check_diff_interval = self._info_manager.get_info("CHECK DIFF INTERVAL")

        img1 = self._cacheManager.GetLastObjFoundFullImg()

        if img1 is None:
            img1 = self._screen_capture.grab_desktop(self._screen_capture.get_gray_mat)

        thread_t0 = time.time()
        time_before_loop = time.time()
        while True:
            #txx = time.time()
            try:

                if len(self._objects_found) > 0 and self._flag_thread_started is False:
                    #do analysis cjecl_time()
                    """
                    print "len main:", len(self._objects_found)

                    print "main x, y, w, h:", self._objects_found[0][0].x, self._objects_found[0][0].y, self._objects_found[0][0].width, self._objects_found[0][0].height


                    if self._objects_found[0][1] is not None:
                        print "len secodn:", len(self._objects_found[0][1])
                        for sub_obj in self._objects_found[0][1]:
                            print "sub x, y, w, h:", sub_obj.x, sub_obj.y, sub_obj.width, sub_obj.height
                    """

                    self._last_thread_image = self._uncompress_image(self._find_thread_images[-1][1])

                    #time.sleep(3600)

                    if wait_disappear is False:
                        self._log_manager.save_objects_found(self._name, self.get_source_image_gray(), self._objects_found, [x[1] for x in self._sub_components])

                    if wait_disappear is True:
                        self._heartbeat_images_copy = copy.deepcopy(self._heartbeat_images)
                        self._last_thread_image_copy = copy.deepcopy(self._last_thread_image)
                        #self._timer_for_disappear = self._heartbeat_images[-1][0]
                        #self._find_thread_images_copy = copy.deepcopy(self._find_thread_images)
                        return -2
                    else:
                        self._object_is_found_flag = True
                        self._last_thread_image_copy = copy.deepcopy(self._last_thread_image)
                        return self._get_performance()


                if time_elapsed > timeout_value and self._flag_thread_started is False:
                    self._last_thread_image = self._uncompress_image(self._find_thread_images[-1][1])
                    #from alyvix.finders.cv.rectfinder import RectFinder
                    #from alyvix.finders.cv.imagefinder import ImageFinder
                    #from alyvix.finders.cv.textfinder import TextFinder
                    from alyvix.finders.cv.objectfinder import ObjectFinder

                    #if not isinstance(self, ObjectFinder):
                    self._log_manager.save_timedout_objects(self._name + "_timedout", self.get_source_image_gray(), self._timedout_main_components, self._timedout_sub_components, self._main_extra_img_log, self._sub_extra_imgages_log)
                    #else:
                    if isinstance(self, ObjectFinder):

                        #self._log_manager.save_timedout_objects(self._name + "_timedout", self._last_thread_image, self._main_component[0]._timedout_main_components, self._main_component[0]._timedout_sub_components, self._main_component[0]._main_extra_img_log, self._main_component[0]._sub_extra_imgages_log, True, self._main_component[0]._name)

                        if len(self._main_component[0]._objects_found) == 0:
                            self._log_manager.save_timedout_objects(self._name + "_timedout", self._last_thread_image, self._main_component[0]._timedout_main_components, self._main_component[0]._timedout_sub_components, self._main_component[0]._main_extra_img_log, self._main_component[0]._sub_extra_imgages_log, True, self._main_component[0]._name)

                        for t_sub in self._sub_components:
                            self._log_manager.save_timedout_objects(self._name + "_timedout", self._last_thread_image, t_sub[0]._timedout_main_components, t_sub[0]._timedout_sub_components, t_sub[0]._main_extra_img_log, t_sub[0]._sub_extra_imgages_log, True, t_sub[0]._name)

                    return -1

                t0 = time.time()

                #cv2.imwrite('img2.png', img2)

                #if time.time() - thread_t0 >= thread_interval:
                if time_elapsed < timeout_value and time.time() - thread_t0 >= thread_interval and self._flag_thread_started is False:
                    thread_t0 = time.time()

                    self._flag_thread_started = True

                    """
                    folder = 'c:\\log\\buffer_images'
                    for the_file in os.listdir(folder):
                        file_path = os.path.join(folder, the_file)
                        try:
                            if os.path.isfile(file_path):
                                os.unlink(file_path)
                        except Exception, e:
                            print e
                    """


                    #for i in range(len(self._find_thread_images)):
                        #cv2.imwrite("c:\\log\\buffer_images\\_old_" + str(self._find_thread_images[i][0]) + ".png", self._uncompress_image(self._find_thread_images[i][1]))


                    self._find_thread_images = copy.deepcopy(self._heartbeat_images)
                    self._heartbeat_images = []

                    self.set_source_image_color(img2_color)
                    self.set_source_image_gray(img2_gray)
                    if self._log_manager.is_log_enable() is True:
                        self._log_manager.delete_all_items(keep_items=20, exclude_item="difference")
                    worker = Thread(target=self.find)
                    worker.setDaemon(True)
                    worker.start()

                img2_color = self._screen_capture.grab_desktop(self._screen_capture.get_color_mat)
                img2_gray = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)
                self._heartbeat_images.append((time_elapsed, self._compress_image(img2_gray)))


                t1 = time.time() - t0
                time_sleep = check_diff_interval - t1
                if time_sleep < 0:
                    time_sleep = 0

                time.sleep(time_sleep)

                time_elapsed = time.time() - time_before_loop
                #print time_elapsed

            except Exception, err:
                #print str(err) + " on line " + str(sys.exc_traceback.tb_lineno)
                self._log_manager.save_exception("ERROR", "an exception has occurred: " + str(err) + " on line " + str(sys.exc_traceback.tb_lineno))
                return None
Exemplo n.º 6
0
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Developer: Alan Pipitone (Violet Atom) - http://www.violetatom.com/
# Supporter: Wuerth Phoenix - http://www.wuerth-phoenix.com/
# Official website: http://www.alyvix.com/

from alyvix.tools.configreader import ConfigReader
from alyvix.tools.screen import ScreenManager
from alyvix.bridge.robot import RobotManager
import time

config_reader = ConfigReader()
robot_manager = RobotManager()
screen_manager = ScreenManager()

_log_folder = None

_dict = {}


class InfoManager():
    def update(self):
        """
        updates all info.
        """

        self.set_info('START TIME', int(time.time()))
Exemplo n.º 7
0
    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """
        self._main_component = None
        self._sub_components = []

        self._timedout_main_components = []
        self._timedout_sub_components = []

        self._main_extra_img_log = None
        self._sub_extra_imgages_log = []

        self._rect_extra_timedout_image = None

        self._robot_manager = RobotManager()

        self._rf_is_set = self._robot_manager.context_is_set()

        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        self._timed_out_images = []

        self._find_thread_images = []
        self._find_thread_images_disappear = []
        #self._find_thread_images_copy = []
        self._last_thread_image = None
        self._last_thread_image_copy = None
        self._heartbeat_images = []
        self._heartbeat_images_copy = []

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._info_manager = InfoManager()
        self._scaling_factor = self._info_manager.get_info(
            "SCALING FACTOR INT")

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()

        self.__enable_debug_calcperf = False

        #self._timer_for_disappear = 0

        self._object_is_found_flag = False

        self._is_object_finder = False
        self._objects_found_of_sub_object_finder = []
Exemplo n.º 8
0
class BaseFinder(object):
    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """
        self._main_component = None
        self._sub_components = []

        self._timedout_main_components = []
        self._timedout_sub_components = []

        self._main_extra_img_log = None
        self._sub_extra_imgages_log = []

        self._rect_extra_timedout_image = None

        self._robot_manager = RobotManager()

        self._rf_is_set = self._robot_manager.context_is_set()

        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        self._timed_out_images = []

        self._find_thread_images = []
        self._find_thread_images_disappear = []
        #self._find_thread_images_copy = []
        self._last_thread_image = None
        self._last_thread_image_copy = None
        self._heartbeat_images = []
        self._heartbeat_images_copy = []

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._info_manager = InfoManager()
        self._scaling_factor = self._info_manager.get_info(
            "SCALING FACTOR INT")

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()

        self.__enable_debug_calcperf = False

        #self._timer_for_disappear = 0

        self._object_is_found_flag = False

        self._is_object_finder = False
        self._objects_found_of_sub_object_finder = []

    def _compress_image(self, img):
        return cv2.imencode('.png', img)[1]

    def _uncompress_image(self, compressed_img):
        return cv2.imdecode(compressed_img, cv2.CV_LOAD_IMAGE_GRAYSCALE)

    def set_name(self, name):
        """
        set the name of the object.

        :type name: string
        :param name: the name of the object
        """
        self._name = name
        self._log_manager.set_object_name(self._name)

    def get_name(self):
        """
        get the name of the object.

        :rtype: string
        :return: the name of the object
        """
        return self._name

    def set_name_with_caller(self):

        tmp_name = self._name

        for object_caller in self._objects_finders_caller:
            tmp_name = object_caller + os.sep + tmp_name

        self._name_with_caller = tmp_name
        self._log_manager.set_object_name(self._name_with_caller)

    def set_source_image_color(self, image_data):
        """
        set the color image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the color image
        """
        self._source_image_color = image_data.copy()
        img_gray = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY)
        self.set_source_image_gray(img_gray)
        #self._log_manager.set_image(self._source_image)

    def set_source_image_gray(self, image_data):
        """
        set the gray image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the gray image
        """
        self._source_image_gray = image_data.copy()

    def get_source_image_color(self):
        """
        get the color image on which the find method will search the object.

        :rtype: numpy.ndarray
        :return: the source color image
        """
        return self._source_image_color

    def get_source_image_gray(self):
        """
        get the gray image on which the find method will search the object.

        :rtype: numpy.ndarray
        :return: the source gray image
        """
        return self._source_image_gray

    def find(self):
        raise NotImplementedError

    def wait(self, timeout=-1, wait_disappear=False):
        """
        wait until the object appears on the screen.
        if timeout value is -1 (default value) then timeout value will be read from config file.
        if configuration file doesn't exist, then timeout value will be 15 sec.

        :param timeout: timeout in seconds
        :type timeout: int
        """

        #cv2.imwrite()

        #self._robot_manager.write_log_message("wait method: " + self.get_name(), "ERROR", False)
        #self._robot_manager.write_log_message("wait method: " + self.get_name(), "ERROR", False)
        #sss = self._robot_manager.get_suite_name()
        #ttt = self._robot_manager.get_testcase_name()

        #self._robot_manager.method1().method2()

        timeout_value = 15

        if timeout == -1:
            timeout_value = self._configReader.get_finder_wait_timeout()
        else:
            timeout_value = timeout

        self._objects_found = []

        self._heartbeat_images = []
        self._find_thread_images = []

        self._flag_thread_started = False
        self._flag_thread_have_to_exit = False

        self._heartbeat_images_copy = []

        time_elapsed = 0.0
        #time_of_last_change = 0.0
        self._time_checked_before_exit_start = None

        self._object_is_found_flag = False

        #screenCapture = ScreenManager()
        thread_interval = self._info_manager.get_info(
            "FINDER THREAD INTERVAL"
        )  #self._configReader.get_finder_thread_interval()
        #thread_interval = 0.5
        check_diff_interval = self._info_manager.get_info(
            "CHECK DIFF INTERVAL")

        img1 = self._cacheManager.GetLastObjFoundFullImg()

        if img1 is None:
            img1 = self._screen_capture.grab_desktop(
                self._screen_capture.get_gray_mat)

        thread_t0 = time.time()
        time_before_loop = time.time()
        while True:
            #txx = time.time()
            try:

                if len(self._objects_found
                       ) > 0 and self._flag_thread_started is False:
                    #do analysis cjecl_time()
                    """
                    print "len main:", len(self._objects_found)

                    print "main x, y, w, h:", self._objects_found[0][0].x, self._objects_found[0][0].y, self._objects_found[0][0].width, self._objects_found[0][0].height


                    if self._objects_found[0][1] is not None:
                        print "len secodn:", len(self._objects_found[0][1])
                        for sub_obj in self._objects_found[0][1]:
                            print "sub x, y, w, h:", sub_obj.x, sub_obj.y, sub_obj.width, sub_obj.height
                    """

                    self._last_thread_image = self._uncompress_image(
                        self._find_thread_images[-1][1])

                    #time.sleep(3600)

                    if wait_disappear is False:
                        self._log_manager.save_objects_found(
                            self._name, self.get_source_image_gray(),
                            self._objects_found,
                            [x[1] for x in self._sub_components])

                    if wait_disappear is True:
                        self._heartbeat_images_copy = copy.deepcopy(
                            self._heartbeat_images)
                        self._last_thread_image_copy = copy.deepcopy(
                            self._last_thread_image)
                        #self._timer_for_disappear = self._heartbeat_images[-1][0]
                        #self._find_thread_images_copy = copy.deepcopy(self._find_thread_images)
                        return -2
                    else:
                        self._object_is_found_flag = True
                        self._last_thread_image_copy = copy.deepcopy(
                            self._last_thread_image)
                        return self._get_performance()

                if time_elapsed > timeout_value and self._flag_thread_started is False:
                    self._last_thread_image = self._uncompress_image(
                        self._find_thread_images[-1][1])
                    #from alyvix.finders.cv.rectfinder import RectFinder
                    #from alyvix.finders.cv.imagefinder import ImageFinder
                    #from alyvix.finders.cv.textfinder import TextFinder
                    from alyvix.finders.cv.objectfinder import ObjectFinder

                    #if not isinstance(self, ObjectFinder):
                    self._log_manager.save_timedout_objects(
                        self._name + "_timedout", self.get_source_image_gray(),
                        self._timedout_main_components,
                        self._timedout_sub_components,
                        self._main_extra_img_log, self._sub_extra_imgages_log)
                    #else:
                    if isinstance(self, ObjectFinder):

                        #self._log_manager.save_timedout_objects(self._name + "_timedout", self._last_thread_image, self._main_component[0]._timedout_main_components, self._main_component[0]._timedout_sub_components, self._main_component[0]._main_extra_img_log, self._main_component[0]._sub_extra_imgages_log, True, self._main_component[0]._name)

                        if len(self._main_component[0]._objects_found) == 0:
                            self._log_manager.save_timedout_objects(
                                self._name + "_timedout",
                                self._last_thread_image, self.
                                _main_component[0]._timedout_main_components,
                                self._main_component[0].
                                _timedout_sub_components,
                                self._main_component[0]._main_extra_img_log,
                                self._main_component[0]._sub_extra_imgages_log,
                                True, self._main_component[0]._name)

                        for t_sub in self._sub_components:
                            self._log_manager.save_timedout_objects(
                                self._name + "_timedout",
                                self._last_thread_image,
                                t_sub[0]._timedout_main_components,
                                t_sub[0]._timedout_sub_components,
                                t_sub[0]._main_extra_img_log,
                                t_sub[0]._sub_extra_imgages_log, True,
                                t_sub[0]._name)

                    return -1

                t0 = time.time()

                #cv2.imwrite('img2.png', img2)

                #if time.time() - thread_t0 >= thread_interval:
                if time_elapsed < timeout_value and time.time(
                ) - thread_t0 >= thread_interval and self._flag_thread_started is False:
                    thread_t0 = time.time()

                    self._flag_thread_started = True
                    """
                    folder = 'c:\\log\\buffer_images'
                    for the_file in os.listdir(folder):
                        file_path = os.path.join(folder, the_file)
                        try:
                            if os.path.isfile(file_path):
                                os.unlink(file_path)
                        except Exception, e:
                            print e
                    """

                    #for i in range(len(self._find_thread_images)):
                    #cv2.imwrite("c:\\log\\buffer_images\\_old_" + str(self._find_thread_images[i][0]) + ".png", self._uncompress_image(self._find_thread_images[i][1]))

                    self._find_thread_images = copy.deepcopy(
                        self._heartbeat_images)
                    self._heartbeat_images = []

                    self.set_source_image_color(img2_color)
                    self.set_source_image_gray(img2_gray)
                    if self._log_manager.is_log_enable() is True:
                        self._log_manager.delete_all_items(
                            keep_items=20, exclude_item="difference")
                    worker = Thread(target=self.find)
                    worker.setDaemon(True)
                    worker.start()

                img2_color = self._screen_capture.grab_desktop(
                    self._screen_capture.get_color_mat)
                img2_gray = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)
                self._heartbeat_images.append(
                    (time_elapsed, self._compress_image(img2_gray)))

                t1 = time.time() - t0
                time_sleep = check_diff_interval - t1
                if time_sleep < 0:
                    time_sleep = 0

                time.sleep(time_sleep)

                time_elapsed = time.time() - time_before_loop
                #print time_elapsed

            except Exception, err:
                #print str(err) + " on line " + str(sys.exc_traceback.tb_lineno)
                self._log_manager.save_exception(
                    "ERROR", "an exception has occurred: " + str(err) +
                    " on line " + str(sys.exc_traceback.tb_lineno))
                return None
Exemplo n.º 9
0
class LogManager:

    #__image = None
    #__main_object_points = None
    #__sub_objects_points = []

    def __init__(self):

        self._config_reader = ConfigReader()

        self.__enable_log = self._config_reader.get_log_enable_value()

        self.__set_log_path()

        self._robot_manager = RobotManager()

        self._info_manager = InfoManager()
        self._info_manager.tiny_update()

        self._robot_context = self._info_manager.get_info("ROBOT CONTEXT")

    def set_object_name(self, name):
        """
        set the object name.

        :type name: string
        :param name: the object name
        """

        current_time = datetime.now().strftime("%H_%M_%S.%f")

        current_time = current_time[:-4]

        self.__name = name
        self.__name_with_time = current_time + "_" + name

    def __set_log_path(self, path=None):

        global log_path

        #print "log_path:", root_log_path

        test_case_name = os.getenv("alyvix_test_case_name", "generic")
        #print test_case_name

        #set testcase root log folder
        if log_path is None and self.__enable_log is True:

            day_time = time.strftime("%d-%m-%y")
            hh_mm_ss = time.strftime("%H_%M_%S")

            root_log_path = self._config_reader.get_log_folder()

            #print root_log_path
            path = root_log_path + os.sep + test_case_name + os.sep + day_time + os.sep + hh_mm_ss

            try:
                if not os.path.exists(path):
                    os.makedirs(path)
            except:
                pass

            log_path = path
            #print path

            self.__delete_old_folders(root_log_path + os.sep + test_case_name)

    def __delete_old_folders(self, root_path):

        daily_folders = os.listdir(root_path)

        for daily_folder in daily_folders:

        
            try:
                if not "-" in daily_folder:
                    continue
                daily_folder_datetime = datetime.strptime(daily_folder, "%d-%m-%y")
                current_datetime = datetime.now()

                current_full_path = root_path + os.sep + daily_folder

                log_max_days = os.getenv("alyvix_log_max_days", "7")
                log_max_days_int = int(log_max_days)

                #if log folder are too old, then delete it
                if daily_folder_datetime <= current_datetime + timedelta(days=(log_max_days_int * -1)):
                    shutil.rmtree(current_full_path)
                #otherwise, check if we have to delete hours folder
                elif daily_folder == time.strftime("%d-%m-%y"):
                    minutes_folders = os.listdir(current_full_path)

                    for minutes_folder in minutes_folders:
                        try:

                            if not "-" in minutes_folder:
                                continue

                            #create fake datetime, that because we need only to compare hours
                            minutes_folder_datetime = datetime.strptime(daily_folder + "_" + minutes_folder,
                                                                        "%d-%m-%y_%H_%M_%S")
                            log_max_hours = os.getenv("alyvix_log_max_hours_per_days", "24")
                            log_max_hours_int = int(log_max_hours)

                            #if hours folder are too old, then delete it
                            if minutes_folder_datetime <= current_datetime + timedelta(hours=(log_max_hours_int * -1)):
                                shutil.rmtree(current_full_path + os.sep + minutes_folder)
                        except:
                            pass
            except:
                pass

    def __delete_items_but(self, path, max_items=None, exclude_item=None):
        if max_items is not None:

            if not os.path.exists(path):
                return

            items = os.listdir(path)

            if exclude_item is not None:
                new_items = [item for item in items if item != exclude_item]
            else:
                new_items = items

            while len(new_items) >= max_items:
            
                try:

                    items = os.listdir(path)

                    if exclude_item is not None:
                        new_items = [item for item in items if item != exclude_item]
                    else:
                        new_items = items

                    full_name = path + os.sep + new_items[0]

                    if os.path.isdir(full_name) is True:
                        shutil.rmtree(full_name)
                    else:
                        os.remove(full_name)
                        
                except:
                    pass

    def __delete_files(self, path, max_files=None):

        if not os.path.exists(path):
            return

        if max_files is not None:
            while len(os.listdir(path)) > max_files:
            
                try:

                    files = os.listdir(path)
                    os.remove(path + os.sep + files[0])
                except:
                    pass

    def is_log_enable(self):
        """
        check if log is enabled.

        :rtype: bool
        :return: a boolean
        """
        return self.__enable_log

    def save_exception(self, type, text_data):

        """
        save the exception into the test case log folder.

        :type sub_dir: string
        :param sub_dir: the subdir to create inside the test case log folder
        :type file_name: string
        :param file_name: the name of the image
        :type text_data: string
        :param text_data: the text to write
        """

        global log_path

        if self.__enable_log is True:

            current_time = datetime.now().strftime("%H:%M:%S.%f")

            fullname = log_path + os.sep + "log.txt"
            #print fullname

            if not os.path.exists(log_path):
                os.makedirs(log_path)

            text_file = open(fullname, "a")
            text_file.write(type + "|" + current_time + "|" + self.__name + "|" + text_data)
            text_file.close()

    def save_image(self, sub_dir, image_name, image_data):
        """
        save the image into the test case log folder.

        :type sub_dir: string
        :param sub_dir: the subdir to create inside the test case log folder
        :type image_name: string
        :param image_name: the name of the image
        :type image_data: numpy.ndarray or Image.Image or cv.iplimage
        :param image_data: the image data to save
        """

        try:
            if isinstance(image_data, numpy.ndarray):
                self.__save_numpy_image(sub_dir, image_name, image_data)

            if isinstance(image_data, Image.Image):
                self.__save_pil_image(sub_dir, image_name, image_data)

            if isinstance(image_data, cv.iplimage):
                self.__save_cv_image(sub_dir, image_name, image_data)
        except Exception, err:
            pass
Exemplo n.º 10
0
class BaseFinder(object):


    def __init__(self, name=None):
        """
        init the class

        :type name: string
        :param name: the object name
        """

        self._source_image_color = None
        self._source_image_gray = None
        self._objects_found = []
        self._log_manager = None

        #variables for the perfdata
        self._cacheManager = None
        self._min_different_contours = 15
        self._flag_thread_started = False
        self._flag_check_before_exit = False
        self._flag_checked_before_exit = False
        self._flag_thread_have_to_exit = False
        self._screen_capture = None
        #end perfdata section

        self._time_checked_before_exit_start = 0

        self._objects_finders_caller = []
        self._name_with_caller = None

        self._name = name
        self._log_manager = LogManager()
        self._log_manager.set_object_name(self._name)
        self._screen_capture = ScreenManager()
        self._cacheManager = CacheManager()
        self._configReader = ConfigReader()

    def set_name(self, name):
        """
        set the name of the object.

        :type name: string
        :param name: the name of the object
        """
        self._name = name
        self._log_manager.set_object_name(self._name)

    def get_name(self):
        """
        get the name of the object.

        :rtype: string
        :return: the name of the object
        """
        return self._name

    def set_name_with_caller(self):

        tmp_name = self._name

        for object_caller in self._objects_finders_caller:
            tmp_name = object_caller + os.sep + tmp_name

        self._name_with_caller = tmp_name
        self._log_manager.set_object_name(self._name_with_caller)

    def set_source_image_color(self, image_data):
        """
        set the color image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the color image
        """
        self._source_image_color = image_data.copy()
        img_gray = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY)
        self.set_source_image_gray(img_gray)
        #self._log_manager.set_image(self._source_image)

    def set_source_image_gray(self, image_data):
        """
        set the gray image on which the find method will search the object.

        :type image_data: numpy.ndarray
        :param image_data: the gray image
        """
        self._source_image_gray = image_data.copy()

    def find(self):
        raise NotImplementedError

    def wait(self, timeout=-1):
        """
        wait until the object appears on the screen.
        if timeout value is -1 (default value) then timeout value will be read from config file.
        if configuration file doesn't exist, then timeout value will be 15 sec.

        :param timeout: timeout in seconds
        :type timeout: int
        """

        timeout_value = 15

        if timeout == -1:
            timeout_value = self._configReader.get_finder_wait_timeout()
        else:
            timeout_value = timeout

        self._objects_found = []
        self._flag_thread_started = False
        self._flag_thread_have_to_exit = False

        time_elapsed = 0
        time_of_last_change = 0
        self._time_checked_before_exit_start = None

        #screenCapture = ScreenManager()
        thread_interval = self._configReader.get_finder_thread_interval()
        check_diff_interval = self._configReader.get_finder_diff_interval()

        img1 = self._cacheManager.GetLastObjFoundFullImg()

        if img1 is None:
            img1 = self._screen_capture.grab_desktop(self._screen_capture.get_gray_mat)

        thread_t0 = time.time()
        time_before_loop = time.time()
        while True:
            try:
                if time_elapsed > timeout_value:
                    return -1

                t0 = time.time()

                img2_color = self._screen_capture.grab_desktop(self._screen_capture.get_color_mat)
                img2_gray = cv2.cvtColor(img2_color, cv2.COLOR_BGR2GRAY)

                #cv2.imwrite('img2.png', img2)

                if time.time() - thread_t0 >= thread_interval:
                    thread_t0 = time.time()
                    if self._flag_thread_started is False:
                        self._flag_thread_started = True
                        self.set_source_image_color(img2_color)
                        self.set_source_image_gray(img2_gray)
                        if self._log_manager.is_log_enable() is True:
                            self._log_manager.delete_all_items(keep_items=20, exclude_item="difference")
                        worker = Thread(target=self.find)
                        worker.setDaemon(True)
                        worker.start()

                if len(self._objects_found) > 0:
                    if self._time_checked_before_exit_start is not None:
                        return self._time_checked_before_exit_start
                    else:
                        return time_of_last_change

                diff_mask = numpy.bitwise_xor(img1, img2_gray)
                #cv2.imwrite("bit.png", diff_mask)

                # find the contours
                contours, hierarchy = cv2.findContours(diff_mask, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

                for cnt in contours:
                    x,y,w,h = cv2.boundingRect(cnt)
                    #cv2.rectangle(img2,(x,y),(x+w,y+h),(0,0,255),3)

                #is_images_equal = not(diff_mask.any())
                if len(contours) < self._min_different_contours:
                #if True:
                    is_images_equal = True
                else:
                    is_images_equal = False

                if is_images_equal is False:
                    if self._log_manager.is_log_enable() is True:
                        self._log_manager.save_image("difference", "old.png", img1)
                    img1 = img2_gray.copy()
                    if self._log_manager.is_log_enable() is True:
                        self._log_manager.save_image("difference", "current.png", img2_gray)
                        self._log_manager.save_image("difference", "mask.png", diff_mask)
                        self._log_manager.delete_all_items(sub_dir="difference", keep_items=20)

                    if self._flag_check_before_exit is False:
                        self._flag_check_before_exit = True
                        self._time_checked_before_exit_start = time_of_last_change
                    elif self._flag_checked_before_exit is True and self._flag_check_before_exit is True:
                        self._flag_check_before_exit = False
                        self._flag_checked_before_exit = False
                        self._flag_thread_have_to_exit = True
                        self._time_checked_before_exit_start = None

                    time_of_last_change = time_elapsed

                #if len(self._objects_found) > 0:
                #    return time_of_last_change

                t1 = time.time() - t0
                time_sleep = check_diff_interval - t1
                if time_sleep < 0:
                    time_sleep = 0

                time.sleep(time_sleep)

                time_elapsed = time.time() - time_before_loop

            except Exception, err:
                #print str(err) + " on line " + str(sys.exc_traceback.tb_lineno)
                self._log_manager.save_exception("ERROR", "an exception has occurred: " + str(err) + " on line " + str(sys.exc_traceback.tb_lineno))
                return None
Exemplo n.º 11
0
class LogManager:

    #__image = None
    #__main_object_points = None
    #__sub_objects_points = []

    def __init__(self):

        self._config_reader = ConfigReader()

        self.__enable_log = self._config_reader.get_log_enable_value()

        self.__set_log_path()

    def set_object_name(self, name):
        """
        set the object name.

        :type name: string
        :param name: the object name
        """

        current_time = datetime.now().strftime("%H_%M_%S.%f")

        current_time = current_time[:-4]

        self.__name = name
        self.__name_with_time = current_time + "_" + name

    def __set_log_path(self, path=None):

        global log_path

        #print "log_path:", root_log_path

        test_case_name = os.getenv("alyvix_test_case_name", "generic")
        #print test_case_name

        #set testcase root log folder
        if log_path is None and self.__enable_log is True:

            day_time = time.strftime("%d-%m-%y")
            hh_mm_ss = time.strftime("%H_%M_%S")

            root_log_path = self._config_reader.get_log_folder()

            #print root_log_path
            path = root_log_path + os.sep + test_case_name + os.sep + day_time + os.sep + hh_mm_ss

            try:
                if not os.path.exists(path):
                    os.makedirs(path)
            except:
                pass

            log_path = path
            #print path

            self.__delete_old_folders(root_log_path + os.sep + test_case_name)

    def __delete_old_folders(self, root_path):

        daily_folders = os.listdir(root_path)

        for daily_folder in daily_folders:

        
            try:
                if not "-" in daily_folder:
                    continue
                daily_folder_datetime = datetime.strptime(daily_folder, "%d-%m-%y")
                current_datetime = datetime.now()

                current_full_path = root_path + os.sep + daily_folder

                log_max_days = os.getenv("alyvix_log_max_days", "7")
                log_max_days_int = int(log_max_days)

                #if log folder are too old, then delete it
                if daily_folder_datetime <= current_datetime + timedelta(days=(log_max_days_int * -1)):
                    shutil.rmtree(current_full_path)
                #otherwise, check if we have to delete hours folder
                elif daily_folder == time.strftime("%d-%m-%y"):
                    minutes_folders = os.listdir(current_full_path)

                    for minutes_folder in minutes_folders:
                        try:

                            if not "-" in minutes_folder:
                                continue

                            #create fake datetime, that because we need only to compare hours
                            minutes_folder_datetime = datetime.strptime(daily_folder + "_" + minutes_folder,
                                                                        "%d-%m-%y_%H_%M_%S")
                            log_max_hours = os.getenv("alyvix_log_max_hours_per_days", "24")
                            log_max_hours_int = int(log_max_hours)

                            #if hours folder are too old, then delete it
                            if minutes_folder_datetime <= current_datetime + timedelta(hours=(log_max_hours_int * -1)):
                                shutil.rmtree(current_full_path + os.sep + minutes_folder)
                        except:
                            pass
            except:
                pass

    def __delete_items_but(self, path, max_items=None, exclude_item=None):
        if max_items is not None:

            if not os.path.exists(path):
                return

            items = os.listdir(path)

            if exclude_item is not None:
                new_items = [item for item in items if item != exclude_item]
            else:
                new_items = items

            while len(new_items) >= max_items:
            
                try:

                    items = os.listdir(path)

                    if exclude_item is not None:
                        new_items = [item for item in items if item != exclude_item]
                    else:
                        new_items = items

                    full_name = path + os.sep + new_items[0]

                    if os.path.isdir(full_name) is True:
                        shutil.rmtree(full_name)
                    else:
                        os.remove(full_name)
                        
                except:
                    pass

    def __delete_files(self, path, max_files=None):

        if not os.path.exists(path):
            return

        if max_files is not None:
            while len(os.listdir(path)) > max_files:
            
                try:

                    files = os.listdir(path)
                    os.remove(path + os.sep + files[0])
                except:
                    pass

    def is_log_enable(self):
        """
        check if log is enabled.

        :rtype: bool
        :return: a boolean
        """
        return self.__enable_log

    def save_exception(self, type, text_data):

        """
        save the exception into the test case log folder.

        :type sub_dir: string
        :param sub_dir: the subdir to create inside the test case log folder
        :type file_name: string
        :param file_name: the name of the image
        :type text_data: string
        :param text_data: the text to write
        """

        global log_path

        if self.__enable_log is True:

            current_time = datetime.now().strftime("%H:%M:%S.%f")

            fullname = log_path + os.sep + "log.txt"
            #print fullname

            if not os.path.exists(log_path):
                os.makedirs(log_path)

            text_file = open(fullname, "a")
            text_file.write(type + "|" + current_time + "|" + self.__name + "|" + text_data)
            text_file.close()

    def save_image(self, sub_dir, image_name, image_data):
        """
        save the image into the test case log folder.

        :type sub_dir: string
        :param sub_dir: the subdir to create inside the test case log folder
        :type image_name: string
        :param image_name: the name of the image
        :type image_data: numpy.ndarray or Image.Image or cv.iplimage
        :param image_data: the image data to save
        """

        try:
            if isinstance(image_data, numpy.ndarray):
                self.__save_numpy_image(sub_dir, image_name, image_data)

            if isinstance(image_data, Image.Image):
                self.__save_pil_image(sub_dir, image_name, image_data)

            if isinstance(image_data, cv.iplimage):
                self.__save_cv_image(sub_dir, image_name, image_data)
        except Exception, err:
            pass