Beispiel #1
0
def start(opsoroapp):
    global loop_t
    global loop_button_t
    global myStream
    myStream.filter(track=twitterWords, async=True)
    loop_t = StoppableThread(target=Loop)
    loop_button_t = StoppableThread(target=LoopButton)
Beispiel #2
0
    def start_update_loop(self):
        if self._dof_t is not None:
            self._dof_t.stop()

        with Hardware.lock:
            Hardware.servo_enable()

        self._dof_t = StoppableThread(target=self.dof_update_loop)
Beispiel #3
0
    def start_update_loop(self):
        Users.broadcast_robot({'dofs': self.get_dof_values(False)}, True)

        if self._dof_t is not None:
            self._dof_t.stop()

        with Hardware.lock:
            Hardware.Servo.enable()

        self._dof_t = StoppableThread(target=self.dof_update_loop)
Beispiel #4
0
    def start_script(self, script):
        """
        Start a new script. This method will create a new runtime, pass the
        script to the runtime, and start a thread to continuously call the
        script's loop function. Can only be used if no other script is running.
        """
        # Check if running
        if self.is_running:
            raise RuntimeError("A script is already running!")

        self._script = script

        callback(self.on_start)()
        self.is_running = True

        # Initialize a new runtime
        self.setup_runtime()

        self.runtime_thread = StoppableThread(target=self._run)
Beispiel #5
0
    def playEmotion(self, tweet):
        """
        start a StoppableThread in order to play all emoticons in a tweet, should not be called directly.

        :param string tweet:    list that has been processed in processJson.
        """
        global loop_E
        global Emoticons
        Emoticons = tweet['text']['emoticon']
        print_info(Emoticons)
        loop_E = StoppableThread(target=self.asyncEmotion)
Beispiel #6
0
def playTweet(tweepyDataModel):
    global playing
    global newTweet
    global loop_PlayTweet
    if not loop_PlayTweet == None:
        loop_PlayTweet.stop()
        print_info('zou ook moeten stoppen')
    global lang
    global tweetArrayToPlay
    playing = True
    lang = tweepyDataModel['text']['lang']
    tweetArrayToPlay = getPlayArray(tweepyDataModel)
    loop_PlayTweet = StoppableThread(
        target=asyncReadTweet)  #start playing Tweet
Beispiel #7
0
    def get_tweet(self, hashtag):
        """
		get a single tweet with hashtag.
        If the hashtag is None the code won't be executed.
        this function starts the streamreader and a StoppableThread

        :param string hashtag:    hashtag to filter by

        """
        global loop_T
        if not (hashtag is None):
            print_info(hashtag)
            self.start_streamreader(hashtag)
            loop_T = StoppableThread(target=self.wait_for_tweet)
        else:
            print_info("no input given")
Beispiel #8
0
    def start_streamreader_amount(self, hashtag, times):
        """
        Starts a streamreader where you will filter by a hashtag for a number of tweets.
        If hashtag is None this function won't be executed.

        stopLoop is set to false so that the StoppableThread can run.

        :param string hashtag:    hashtag to filter by.
        :param string times:    amount of tweets that you want to recieve.

        """
        global myStream
        global loop_TC
        global TweetCount
        global TweetMax
        global stopLoop
        if not (hashtag is None):
            TweetCount = 0
            TweetMax = times
            social_id = []
            social_id.append(hashtag)
            myStream.filter(track=social_id, async=True);
            stopLoop = False
            loop_TC = StoppableThread(target=self.count_tweets)
Beispiel #9
0
def start(opsoroapp):
    global touch_t

    touch_t = StoppableThread(target=TouchLoop)
Beispiel #10
0
 def start_alive_loop(self):
     if self._alive_t is not None:
         self._alive_t.stop()
     self._alive_t = StoppableThread(target=self.alive_loop)
Beispiel #11
0
class _Robot(object):
    def __init__(self):
        self.modules = {}
        self._config = {}
        self.load_config()
        self._dof_t = None
        self._alive_t = None

        self.look_at_position = [0, 0, 0]  # x y z(= depth) -1.0 <-> 1.0

        self.auto_enable_servos = False

        self._alive_count_seed = 1.0
        self._add_seed = 0.2

    def start(self):
        print_info('Start Robot loop')
        with Hardware.lock:
            Hardware.servo_init()
        self.start_update_loop()

        if Preferences.get('alive', 'enabled', False):
            self.start_alive_loop()

    def start_update_loop(self):
        if self._dof_t is not None:
            self._dof_t.stop()

        with Hardware.lock:
            Hardware.servo_enable()

        self._dof_t = StoppableThread(target=self.dof_update_loop)

    def stop_update_loop(self):
        if self._dof_t is not None:
            self._dof_t.stop()

        if self.auto_enable_servos:
            with Hardware.lock:
                Hardware.servo_disable()

    def start_alive_loop(self):
        if self._alive_t is not None:
            self._alive_t.stop()
        self._alive_t = StoppableThread(target=self.alive_loop)

    def stop_alive_loop(self):
        if self._alive_t is not None:
            self._alive_t.stop()

    def stop(self):
        print_info('Stop Robot loop')

        with Hardware.lock:
            Hardware.servo_disable()

        self.stop_alive_loop()
        self.stop_update_loop()

    def config(self, config=None):
        if config is not None and len(config) > 0:
            self._config = json.loads(config)
            # Create all module-objects from data
            self.modules = {}
            modules_count = {}
            for module_data in self._config['modules']:
                if module_data['module'] in MODULES:
                    # Create module object
                    module = MODULES[module_data['module']](module_data)

                    # Count different modules
                    if module_data['module'] not in modules_count:
                        modules_count[module_data['module']] = 0
                    modules_count[module_data['module']] += 1
                    self.modules[module.name] = module

            # print module feedback
            print_info("Modules: " + str(modules_count))
        return self._config

    def set_dof_value(self, module_name, dof_name, dof_value, anim_time=-1):
        if module_name is None:
            for name, module in self.modules.iteritems():
                module.set_dof_value(None, dof_value, anim_time)
        else:
            self.modules[module_name].set_dof_value(dof_name, dof_value,
                                                    anim_time)

        self.start_update_loop()

    def set_dof_values(self, dof_values, anim_time=-1):
        for module_name, dofs in dof_values.iteritems():
            for dof_name, dof_value in dofs.iteritems():
                self.modules[module_name].set_dof_value(
                    dof_name, dof_value, anim_time)

        self.start_update_loop()

    def set_dof_list(self, dof_values, anim_time=-1):
        for name, module in self.modules.iteritems():
            for name, dof in module.dofs.iteritems():
                if hasattr(dof, 'pin') and dof.pin is not None:
                    if dof.pin > 0 and dof.pin < len(dof_values):
                        dof.set_value(dof_values[dof.pin], anim_time)

        self.start_update_loop()

    def get_dof_values(self):
        dofs = []
        for i in range(16):
            dofs.append(0)
        for module_name, module in self.modules.iteritems():
            for dof_name, dof in module.dofs.iteritems():
                if hasattr(dof, 'pin'):
                    dofs[int(dof.pin)] = float(dof.value)

        return dofs

    def apply_poly(self, r, phi, anim_time=-1):
        # print_info('Apply robot poly; r: %f, phi: %f, time: %f' %
        #            (r, phi, anim_time))
        for name, module in self.modules.iteritems():
            module.apply_poly(r, phi, anim_time)

        self.start_update_loop()

    def dof_update_loop(self):
        time.sleep(0.05)  # delay
        if self._dof_t is None:
            return

        while not self._dof_t.stopped():
            if not self.update():
                self.stop_update_loop()
            self._dof_t.sleep(0.02)

    def alive_loop(self):
        time.sleep(0.5)  # delay
        if self._alive_t is None:
            return

        while not self._alive_t.stopped():
            updated = False
            for name, module in self.modules.iteritems():
                if module.alive_trigger(self._alive_count_seed):
                    updated = True
            if updated:
                self._alive_count_seed += self._add_seed
                self.start_update_loop()

            self._alive_t.sleep(0.1)

    def update(self):
        updated = False
        for name, module in self.modules.iteritems():
            if module.update():
                updated = True
        return updated

    def load_config(self, file_name='default.conf'):
        # Load modules from file
        if file_name is None:
            return False

        try:
            with open(get_path("config/" + file_name)) as f:
                self._config = f.read()

            if self._config is None or len(self._config) == 0:
                print_warning("Config contains no data: " + file_name)
                return False
            # print module feedback
            print_info("Modules loaded [" + file_name + "]")
            self.config(self._config)

        except IOError:
            self._config = {}
            print_warning("Could not open " + file_name)
            return False

        return True

    def save_config(self, file_name='default.conf'):
        # Save modules to json file
        if file_name is None:
            return False

        try:
            with open(get_path("config/" + file_name), "w") as f:
                f.write(json.dumps(self._config))
            print_info("Modules saved: " + file_name)
        except IOError:
            print_warning("Could not save " + file_name)
            return False
        return True

    def blink(self, speed):
        for name, module in self.modules.iteritems():
            if hasattr(module, 'blink'):
                module.blink(speed)
Beispiel #12
0
class ScriptHost(object):
    def __init__(self):
        self._script = ""
        self.is_running = False

        self.ui = ScriptUI()

        # Rising/falling edge dict
        self._rising_dict = {}
        self._falling_dict = {}

        self.runtime = None
        self.runtime_thread = None

        # Callbacks
        self.on_print = None
        self.on_error = None
        self.on_start = None
        self.on_stop = None

    def __del__(self):
        if self.is_running:
            self.stop_script()

    def setup_runtime(self):
        """
        Creates a new lua runtime and initializes all globals. Used by
        start_script(), should not be called directly.
        """
        # Create new lua instance
        self.runtime = lupa.LuaRuntime(unpack_returned_tuples=True)

        # Reset keys and button states
        self.ui._keys = {}
        self.ui._buttons = {}

        # Reset rising/falling edge dict
        self._rising_dict = {}
        self._falling_dict = {}

        # Set up API
        g = self.runtime.globals()

        g["Sound"] = Sound
        g["Expression"] = Expression
        g["Robot"] = Robot
        g["Hardware"] = LuaHardware(self.runtime)
        g["Animate"] = LuaAnimate
        g["AnimatePeriodic"] = LuaAnimatePeriodic

        g["Twitter"] = Twitter

        g["UI"] = self.ui

        g["print"] = callback(self.on_print)
        g["sleep"] = self._sleep
        g["rising_edge"] = self._rising_edge
        g["falling_edge"] = self._falling_edge
        g["seconds"] = time.time

        # Basic Arduino functions
        g["delay"] = lambda t: self._sleep(t / 1000)
        g["min"] = min
        g["max"] = max
        g["abs"] = abs
        g["constrain"] = lambda x, a, b: max(a, min(x, b))
        g["map"] = lambda x, in_min, in_max, out_min, out_max: (x - in_min) * (
            out_max - out_min) / (in_max - in_min) + out_min
        g["millis"] = lambda: time.time() * 1000.0

    def start_script(self, script):
        """
        Start a new script. This method will create a new runtime, pass the
        script to the runtime, and start a thread to continuously call the
        script's loop function. Can only be used if no other script is running.
        """
        # Check if running
        if self.is_running:
            raise RuntimeError("A script is already running!")

        self._script = script

        callback(self.on_start)()
        self.is_running = True

        # Initialize a new runtime
        self.setup_runtime()

        self.runtime_thread = StoppableThread(target=self._run)
        # self.runtime_thread.start();

    def stop_script(self):
        """
        Attempts to stop the current script. Returns immediately if no script is
        running. If a script is running, this method will send a stop signal to
        to the script thread, and then block until the thread is stopped. Note
        that the thread's stopped condition is only checked during sleep() and
        at the end of loop() calls, this function will not stop infinite loops.
        """
        if self.is_running and self.runtime_thread is not None:
            self.runtime_thread.stop()
            self.runtime_thread.join()

    def generate_lua_error(self, message):
        """
        If a script is running, this method will generate an error inside the
        script. Useful to signal script errors (e.g. bad parameter) to the user.
        """
        if self.is_running and self.runtime is not None:
            g = self.runtime.globals()
            g["error"](message)

    def _report_error(self, e):
        """
        Helper function that prefixes the type of error to the exception, and
        then sends the error message to the application through the on_error
        callback.
        """
        if type(e) == lupa.LuaSyntaxError:
            callback(self.on_error)("Syntax error: %s" % str(e))
        elif type(e) == lupa.LuaError:
            callback(self.on_error)("Lua error: %s" % str(e))
        else:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            tb_str = "".join(traceback.format_tb(exc_traceback)).replace(
                "\n", "<br>")
            callback(self.on_error)("Python error: %s<br>%s" %
                                    (str(e), tb_str))

    def _sleep(self, time):
        """
        Lua API
        Sleep function that pauses the thread for a number of seconds. This
        sleep function will return immediately if the thread's stop flag is set.
        This means that loop function should come to an end instantaneously,
        after which the thread is ended.
        """
        if self.runtime_thread is not None:
            self.runtime_thread.sleep(time)

    def _rising_edge(self, identifier, status):
        """
        Lua API
        Helper function to detect a rising edge of a signal (e.g. button, key,
        capacitive touch pad, etc). Identifier is an arbitrary string that is
        used to distinguish between different signals. Internally, it's used as
        a key for the dictionary that keeps track of different signals.

        Usage:
        if rising_edge("mybutton", UI:is_key_pressed("up")) then
                -- Do something
        end
        """
        last_status = False
        if identifier in self._rising_dict:
            last_status = self._rising_dict[identifier]

        self._rising_dict[identifier] = status
        return status and not last_status

    def _falling_edge(self, identifier, status):
        """
        Lua API
        Helper function to detect a falling edge of a signal (e.g. button, key,
        capacitive touch pad, etc). Identifier is an arbitrary string that is
        used to distinguish between different signals. Internally, it's used as
        a key for the dictionary that keeps track of different signals.

        Usage:
        if falling_edge("mybutton", UI:is_key_pressed("up")) then
                -- Do something
        end
        """
        last_status = False
        if identifier in self._falling_dict:
            last_status = self._falling_dict[identifier]

        self._falling_dict[identifier] = status
        return last_status and not status

    def _remove_lua_overlays(self):
        # for dofname, dof in Expression.dofs.iteritems():
        #     for overlay in dof.overlays:
        #         if lupa.lua_type(overlay) is not None:
        #             # It's a Lua value, remove it!
        #             dof.overlays.remove(overlay)
        pass

    def _run(self):
        """
        Called by the worker thread when the script is run. First attempts to
        call the script's setup function, then continuously calls the loop
        function. When the thread's stop flag is set, the loop breaks and the
        thread attempts to run the quit function. At any time, if the runtime
        encounters an error, the script is stopped, and the on_error and on_stop
        callbacks are triggered.
        """

        time.sleep(0.05)  # delay

        g = self.runtime.globals()

        # Evaluate code and run setup
        try:
            self.runtime.execute(self._script)
            if g["setup"] is not None:
                g["setup"]()
        except Exception as e:
            self.runtime_thread.stop()
            self._report_error(e)

        if g["loop"] is not None:
            # Continuously run loop, until thread is stopped
            while not self.runtime_thread.stopped():
                try:
                    g["loop"]()
                except Exception as e:
                    self._report_error(e)
                    self.runtime_thread.stop()
                # Delay not really necessary, but can be used to limit CPU time.
                # Without delay, this loop consumes about 70% CPU time on a RPi1.
                # else:
                # 	# 10ms breathing room between loops
                time.sleep(0.01)

        # Run quit
        if g["quit"] is not None:
            try:
                g["quit"]()
            except Exception as e:
                self._report_error(e)

        callback(self.on_stop)()
        self._remove_lua_overlays()
        self.is_running = False
Beispiel #13
0
class _Robot(object):
    class Activation(IntEnum):
        MANUAL = 0  # 0: Manual start/stop
        AUTO = 1  # 1: Start robot automatically (alive feature according to preferences)
        AUTO_ALIVE = 2  # 2: Start robot automatically and enable alive feature
        AUTO_NOT_ALIVE = 3  # 3: Start robot automatically and disable alive feature

    class Connection(IntEnum):
        OFFLINE = 0  # 0: No online capability
        PARTLY = 1  # 1: Needs online for extras, but works without
        ONLINE = 2  # 2: Requires to be online to work

    def __init__(self):
        self.modules = {}
        self.config = {}
        self.load_config()
        self._dof_t = None
        self._alive_t = None

        self.look_at_position = [0, 0, 0]  # x y z(= depth) -1.0 <-> 1.0

        self.auto_enable_servos = False

        self._alive_count_seed = 1.0
        self._add_seed = 0.2

    def start(self):
        print_info('Start Robot loop')
        with Hardware.lock:
            Hardware.Servo.init()
        self.start_update_loop()

        if Preferences.get('behaviour', 'enabled', False):
            self.start_alive_loop()

    def start_update_loop(self):
        Users.broadcast_robot({'dofs': self.get_dof_values(False)}, True)

        if self._dof_t is not None:
            self._dof_t.stop()

        with Hardware.lock:
            Hardware.Servo.enable()

        self._dof_t = StoppableThread(target=self.dof_update_loop)

    def stop_update_loop(self):
        if self._dof_t is not None:
            self._dof_t.stop()

        if self.auto_enable_servos:
            with Hardware.lock:
                Hardware.Servo.disable()

    def start_alive_loop(self):
        if self._alive_t is not None:
            self._alive_t.stop()
        self._alive_t = StoppableThread(target=self.alive_loop)

    def stop_alive_loop(self):
        if self._alive_t is not None:
            self._alive_t.stop()

    def stop(self):
        print_info('Stop Robot loop')

        with Hardware.lock:
            Hardware.Servo.disable()

        self.stop_alive_loop()
        self.stop_update_loop()

    def set_config(self, config=None):
        if config is not None and len(config) > 0:
            save_new_config = (self.config != config)
            self.config = json.loads(config)
            # Create all module-objects from data
            self.modules = {}
            modules_count = {}
            for module_data in self.config['modules']:
                module_type = module_data['type']
                if module_type in MODULES:
                    # Create module object
                    module = MODULES[module_type](module_data)

                    # Count different modules
                    if module_type not in modules_count:
                        modules_count[module_type] = 0
                    modules_count[module_type] += 1

                    if module.name in self.modules:
                        for i in range(1000):
                            if ('%s %i' %
                                (module.name, i)) not in self.modules:
                                module.name = ('%s %i' % (module.name, i))
                                break

                    self.modules[module.name] = module

            # print module feedback
            print_info("Modules: " + str(modules_count))

            if save_new_config:
                self.save_config()
            Users.broadcast_robot({'refresh': True})
        return self.config

    def set_dof(self, tags=[], value=0, anim_time=-1):
        for name, module in self.modules.iteritems():
            module.set_dof(tags, value, anim_time)
        self.start_update_loop()

    def set_dof_value(self, module_name, dof_name, dof_value, anim_time=-1):
        if module_name is None:
            for name, module in self.modules.iteritems():
                module.set_dof_value(None, dof_value, anim_time)
        else:
            self.modules[module_name].set_dof_value(dof_name, dof_value,
                                                    anim_time)

        self.start_update_loop()

    def set_dof_values(self, dof_values, anim_time=-1):
        for module_name, dofs in dof_values.iteritems():
            for dof_name, dof_value in dofs.iteritems():
                self.modules[module_name].set_dof_value(
                    dof_name, dof_value, anim_time)

        self.start_update_loop()

    def set_dof_list(self, dof_values, anim_time=-1):
        for name, module in self.modules.iteritems():
            for name, dof in module.dofs.iteritems():
                if hasattr(dof, 'pin') and dof.pin is not None:
                    if dof.pin >= 0 and dof.pin < len(dof_values):
                        dof.set_value(dof_values[dof.pin], anim_time)

        self.start_update_loop()

    def get_dof_values(self, current=True):
        dofs = []
        for i in range(16):
            dofs.append(0)
        for module_name, module in self.modules.iteritems():
            for dof_name, dof in module.dofs.iteritems():
                if hasattr(dof, 'pin') and dof.pin is not None:
                    if dof.pin >= 0 and dof.pin < len(dofs):
                        if current:
                            dofs[dof.pin] = float(dof.value)
                        else:
                            dofs[dof.pin] = float(dof.to_value)

        return dofs

    def apply_poly(self, r, phi, anim_time=-1):
        for name, module in self.modules.iteritems():
            module.apply_poly(r, phi, anim_time)

        self.start_update_loop()

    def dof_update_loop(self):
        time.sleep(0.05)  # delay
        if self._dof_t is None:
            return

        while not self._dof_t.stopped():
            if not self.update():
                self.stop_update_loop()
            self._dof_t.sleep(0.02)

    def alive_loop(self):
        time.sleep(0.5)  # delay
        if self._alive_t is None:
            return

        while not self._alive_t.stopped():
            updated = False
            for name, module in self.modules.iteritems():
                if module.alive_trigger(self._alive_count_seed):
                    updated = True
            if updated:
                self._alive_count_seed += self._add_seed
                self.start_update_loop()

            self._alive_t.sleep(0.1)

    def update(self):
        updated = False
        for name, module in self.modules.iteritems():
            if module.update():
                updated = True

        return updated

    def load_config(self, file_name='robot_config.conf'):
        # Load modules from file
        if file_name is None:
            return False

        try:
            with open(get_path("config/" + file_name)) as f:
                self.config = f.read()

            if self.config is None or len(self.config) == 0:
                print_warning("Config contains no data: " + file_name)
                return False

            self.set_config(self.config)
            # print module feedback
            print_info("%i modules loaded [%s]" %
                       (len(self.modules), file_name))

        except IOError:
            self.config = {}
            print_warning("Could not open " + file_name)
            return False

        return True

    def save_config(self, file_name='robot_config.conf'):
        # Save modules to json file
        if file_name is None:
            return False

        try:
            with open(get_path("config/" + file_name), "w") as f:
                f.write(json.dumps(self.config))
            print_info("Modules saved: " + file_name)
        except IOError:
            print_warning("Could not save " + file_name)
            return False
        return True

    def blink(self, speed):
        for name, module in self.modules.iteritems():
            if hasattr(module, 'blink'):
                module.blink(speed)

    def sleep(self):
        print_info('Night night... ZZZZzzzz....')
        self.set_dof(['eye', 'lid'], -1)
        pass

    def wake(self):
        print_info('I am awake!')
        self.set_dof(['eye', 'lid'], 1)
        pass
Beispiel #14
0
def handlePostData(data):
    global thread_fb_t
    global fb_params_stringified
    fb_params_stringified = json.loads(data) #doesn't need to be parsed to json because we'll send it back to the js instantly or does it just for python??
    print_info(fb_params_stringified)
    thread_fb_t = StoppableThread(target=thread_fb)