示例#1
0
class DeepSearchHandler(PatternMatchingEventHandler):
	""" Deep file search handler to handle the events gengerated by file changes """
	def __init__(self):	
		self.datahandler = DatabaseHandler()
		self._ignore_directories = False
		self._ignore_patterns = False
		self._ignore_patterns = ["*.log","*.logger"]
		self._case_sensitive = False
		self._patterns = ["*.rb","*.py","*.java","*.mp4","*.mp3","*.txt"]
		print "instance created"


	def on_created(self,event):
		"""Called when a file or directory is created."""
		print "file create event"+str(event)
		self.datahandler.create(event.src_path)		

	def on_modified(self,event):
		""""Called when a file or directory is modified."""
		print "file modify event"+str(event)
		self.datahandler.update(event.src_path)

	def on_deleted(self,event):
		"""" Called when a file or directory is deleted. """
		print "file delete event"+str(event)
		self.datahandler.delete(event.src_path)

	def on_moved(self,event):
		""""Called when a file or a directory is moved or renamed."""
		print "file moved event"+str(event)
		self.datahandler.moved(event.src_path)

	def close_db_connection(self):
		""" call close_connection function of datanadler """
		self.datahandler.close_connection()
def parse_requests(table_name, filename='logs/humans.json'):
    try:
        ips, requests = _extract_http_and_time(
            filename)  ##requests is a list of tuple
        formated_requests = _format_requests(
            requests
        )  #get the requests as a dict in the format the database accepts
        if filename == 'logs/humans.json':
            formated_requests_clean = remove_bot_req(formated_requests)
        else:
            formated_requests_clean = formated_requests

        with DatabaseHandler(table_name) as db:
            db.create_table(table_name)
            for req in formated_requests_clean:
                db.store(req)
        with DatabaseHandler(table_name) as db:
            l = db.cursor.execute(
                "SELECT * FROM {}".format(table_name)).fetchall()
            ips_in_table = []
            for val in l:
                ips_in_table.append(val[1])
        return list(set(ips_in_table))
    except Exception as e:
        raise e
示例#3
0
class DeepSearchHandler(pyinotify.ProcessEvent):
    """ Deep file search handler to handle the events gengerated by file changes """
    def __init__(self):
        self.datahandler = DatabaseHandler()
        print "instance created"

    def process_IN_CREATE(self, event):
        """Called when a file or directory is created."""
        print "file create event" + str(event)
        self.datahandler.create(event.pathname)

    def process_IN_MODIFY(self, event):
        """"Called when a file or directory is modified."""
        print "file modify event" + str(event)
        self.datahandler.update(event.pathname)

    def process_IN_DELETE(self, event):
        """" Called when a file or directory is deleted. """
        print "file delete event" + str(event)
        self.datahandler.delete(event.pathname)

    def process_IN_ACCESS(self, event):
        """" Called when a file or directory is accessed. """
        print "file access event" + str(event.pathname)
        self.datahandler.access(event.pathname)

    def close_db_connection(self):
        """ call close_connection function of datanadler """
        self.datahandler.close_connection()
示例#4
0
    def __init__(self):
        rospy.sleep(
            2
        )  # Delay startup so navigation is finished setting up database file
        self.current_location = None
        self.SCHEDULER_RATE = rospy.Rate(0.05)  #(Hz)
        self.LOW_POWER_THRESHOLD = 20
        self.HOMEDIR = os.path.expanduser("~")
        self.PATH = self.HOMEDIR + "/navigation.db"
        self.MAP_NAME = "glassgarden.map"
        self.current_state = "idle"

        self.publisher_event = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.subscriber_current_location = rospy.Subscriber(
            "cyborg_navigation/current_location", String,
            self.callback_current_location)
        self.subscriber_state = rospy.Subscriber(
            "/cyborg_controller/state_change",
            SystemState,
            self.callback_subscriber_state,
            queue_size=100)
        self.subscriber_battery_status = rospy.Subscriber(
            "/rosarnl_node/battery_status",
            BatteryStatus,
            callback=self.callback_battery_status,
            queue_size=10)

        self.database_handler = DatabaseHandler(filename=self.PATH)
        self.scheduler_thread = threading.Thread(target=self.scheduler)
        self.scheduler_thread.daemon = True  # Thread terminates when main thread terminates
        self.scheduler_thread.start()
示例#5
0
    def __init__(self, database_file=""):
        self.action_name = rospy.get_name()
        self.MAP_NAME = "glassgarden.map"
        self.PLANNING_TIMEOUT = 10
        self.RATE_ACTIONLOOP = rospy.Rate(4)  # Hz

        self.next_location = ""
        self.current_emotional_state = "neutral"
        self.current_state = ""
        self.database_handler = DatabaseHandler(filename=database_file)

        self.publisher_emotional_feedback = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)
        self.subscriber_emotional_state = rospy.Subscriber(
            "/cyborg_controller/emotional_state",
            EmotionalState,
            self.emotional_callback,
            queue_size=10)
        self.publisher_event = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.publisher_location_command = rospy.Publisher(
            "/cyborg_behavior/command_location", String, queue_size=10)

        self.client_behavior = actionlib.SimpleActionClient(
            "/cyborg_behavior", StateMachineAction)
        self.server_primary_states = actionlib.SimpleActionServer(
            self.action_name,
            StateMachineAction,
            execute_cb=self.callback_server_primary_states,
            auto_start=False)
        self.server_primary_states.start()
        rospy.loginfo("PrimaryStatesServer: Initiated")
示例#6
0
	def __init__(self):	
		self.datahandler = DatabaseHandler()
		self._ignore_directories = False
		self._ignore_patterns = False
		self._ignore_patterns = ["*.log","*.logger"]
		self._case_sensitive = False
		self._patterns = ["*.rb","*.py","*.java","*.mp4","*.mp3","*.txt"]
		print "instance created"
    def __init__(self, log_file_handler, live=False):
        self.is_live = live
        
        # Logger setup
        if self.is_live:
            self.logger = logging.getLogger('PCPPHelperBot')
        else:
            self.logger = logging.getLogger('PCPPHelperBot-DEBUG')
            
        self.logger.addHandler(log_file_handler)
        now_str = datetime.now().strftime('%H:%M:%S')
        self.logger.info(f'STARTING {now_str}')
        
        # Database setup
        if self.is_live:
            self.db_handler = DatabaseHandler()
        else:
            self.db_handler = DatabaseHandler(debug=True)
        
        self.db_handler.connect()
        self.db_handler.create_table()

        # Retrieve environment vars for secret data
        username = os.environ.get('REDDIT_USERNAME')
        password = os.environ.get('REDDIT_PASSWORD')
        client_id = os.environ.get('CLIENT_ID')
        secret = os.environ.get('CLIENT_SECRET')
        
        version = 0.1
        user_agent = f"web:pcpp-helper-bot:v{version} (by u/pcpp-helper-bot)"
        
        # Utilize PRAW wrapper
        self.reddit = praw.Reddit(user_agent=user_agent,
                                  client_id=client_id, client_secret=secret,
                                  username=username, password=password)
        
        # Only look at submissions with one of these flairs
        # TODO: Are these the best submission flairs to use?
        self.pertinent_flairs = ['Build Complete', 'Build Upgrade',
                                 'Build Help', 'Build Ready', None]
        
        self.pcpp_parser = PCPPParser(log_file_handler)
        self.table_creator = TableCreator()
        self.MAX_TABLES = 2
        self.subreddit_name = None
        
        # Read in the templates
        with open('./templates/replytemplate.md', 'r') as template:
            self.REPLY_TEMPLATE = template.read()
        
        with open('./templates/idenlinkfound.md', 'r') as template:
            self.IDENTIFIABLE_TEMPLATE = template.read()
        
        with open('./templates/tableissuetemplate.md', 'r') as template:
            self.TABLE_TEMPLATE = template.read()
示例#8
0
    def __init__(self, database_file=""):
        self.scheduler_rate = rospy.Rate(1)  # (hz)
        self.server_rate = rospy.Rate(0.5)  # (hz)

        self.server_planing = actionlib.SimpleActionServer(
            rospy.get_name() + "/planing",
            StateMachineAction,
            execute_cb=self.server_planing_callback,
            auto_start=False)
        self.server_moving = actionlib.SimpleActionServer(
            rospy.get_name() + "/moving",
            StateMachineAction,
            execute_cb=self.server_moving_callback,
            auto_start=False)
        self.server_talking = actionlib.SimpleActionServer(
            rospy.get_name() + "/talking",
            StateMachineAction,
            execute_cb=self.server_talking_callback,
            auto_start=False)
        self.server_go_to = actionlib.SimpleActionServer(
            rospy.get_name() + "/go_to",
            NavigationGoToAction,
            execute_cb=self.server_go_to_callback,
            auto_start=False)
        self.server_planing.start()
        self.server_moving.start()
        self.server_talking.start()
        self.server_go_to.start()
        self.client_base = actionlib.SimpleActionClient(
            "/rosarnl_node/move_base", MoveBaseAction)
        self.emotion_publisher = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)
        self.event_publisher = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.speech_publisher = rospy.Publisher(
            "/cyborg_text_to_speech/text_to_speech", String, queue_size=100)
        self.database_handler = DatabaseHandler(filename=database_file)
        self.location_subscriber = rospy.Subscriber("/rosarnl_node/amcl_pose",
                                                    PoseWithCovarianceStamped,
                                                    self.location_callback)
        self.emotion_subscriber = rospy.Subscriber(
            "/cyborg_controller/emotional_state",
            EmotionalState,
            self.emotion_callback,
            queue_size=100)
        self.text_subscriber = rospy.Subscriber("/text_from_speech",
                                                String,
                                                self.text_callback,
                                                queue_size=100)
        self.scheduler_thread = threading.Thread(target=self.scheduler)
        self.scheduler_thread.daemon = True  # Thread terminates when main thread terminates
        self.scheduler_thread.start()
        rospy.loginfo("NavigationServer: Activated.")
def get_unique_ips(table_name):
    with DatabaseHandler(table_name) as db:
        l = db.cursor.execute("SELECT * FROM {}".format(table_name)).fetchall()
        ips_in_table = []
        for val in l:
            ips_in_table.append(val[1])
    return list(set(ips_in_table))
示例#10
0
    def scanSystem(self):

        self.DatabaseHandler_instance = DatabaseHandler(os.getcwd())
        scanDialog = QtWidgets.QDialog()
        scanDialogui = Ui_Dialog_()
        scanDialogui.setupUi_(scanDialog)
        scanDialog.show()
        scanDialog.exec_()
    def __init__(self, database_file=""):
        self.MAP_NAME = "glassgarden.map"
        self.TIMEOUT_GOTO = 300  # (S)
        self.TIMEOUT_WANDERING = 600  # (S)
        self.EMOTIONAL_FEEDBACK_CYCLE = 15  # (s)
        self.SERVER_RATE = rospy.Rate(10)  #(Hz)

        self.client_base_feedback = StateMachineFeedback()
        self.client_base_result = StateMachineResult()

        self.current_x = 0.0
        self.current_y = 0.0
        self.next_location = None
        self.current_location = None
        self.current_location_name = None
        self.base_canceled = False
        self.base_succeeded = False

        self.location_subscriber = rospy.Subscriber("/rosarnl_node/amcl_pose",
                                                    PoseWithCovarianceStamped,
                                                    self.location_callback)
        self.publisher_current_location = rospy.Publisher(rospy.get_name() +
                                                          "/current_location",
                                                          String,
                                                          queue_size=10)
        self.emotion_publisher = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)

        self.server_navigation = actionlib.SimpleActionServer(
            rospy.get_name() + "/navigation",
            NavigationAction,
            execute_cb=self.navigationserver_callback,
            auto_start=False)
        self.server_navigation.start()
        self.client_base = actionlib.SimpleActionClient(
            "/rosarnl_node/move_base", MoveBaseAction)

        self.database_handler = DatabaseHandler(filename=database_file)
        self.location_updater_thread = threading.Thread(
            target=self.location_updater)
        self.location_updater_thread.daemon = True
        self.location_updater_thread.start()
        rospy.loginfo("NavigationServer: Activated.")
示例#12
0
 def __init__(self, database_file=""):
     self.event_publisher = rospy.Publisher(rospy.get_name() +
                                            "/register_event",
                                            String,
                                            queue_size=100)
     self.emotion_publisher = rospy.Publisher(rospy.get_name() +
                                              "/emotional_feedback",
                                              EmotionalFeedback,
                                              queue_size=100)
     self.emotion_subscriber = rospy.Subscriber(rospy.get_name() +
                                                "/emotional_state",
                                                EmotionalState,
                                                self.emotion_callback,
                                                queue_size=100)
     self.state_subscriber = rospy.Subscriber(rospy.get_name() +
                                              "/state_change",
                                              SystemState,
                                              self.state_callback,
                                              queue_size=100)
     self.rate = rospy.Rate(.5)  # (hz), looping speed
     self.database_handler = DatabaseHandler(filename=database_file)
     self.database_handler.reset_event_values()
示例#13
0
def main():
    rospy.init_node("cyborg_controller")

    # Create emotions
    emotion_system = EmotionSystem()
    emotion_system.add_emotion(name="angry",
                               pleasure=-0.51,
                               arousal=0.59,
                               dominance=0.25)
    emotion_system.add_emotion(name="bored",
                               pleasure=-0.65,
                               arousal=-0.62,
                               dominance=-0.33)
    emotion_system.add_emotion(name="curious",
                               pleasure=0.22,
                               arousal=0.62,
                               dominance=-0.10)
    emotion_system.add_emotion(name="dignified",
                               pleasure=0.55,
                               arousal=0.22,
                               dominance=0.61)
    emotion_system.add_emotion(name="elated",
                               pleasure=0.50,
                               arousal=0.42,
                               dominance=0.23)  # Happy
    emotion_system.add_emotion(name="inhibited",
                               pleasure=-0.54,
                               arousal=-0.04,
                               dominance=-0.41)  # Sadness
    emotion_system.add_emotion(name="puzzled",
                               pleasure=-0.41,
                               arousal=0.48,
                               dominance=-0.33)  # Surprized
    emotion_system.add_emotion(name="loved",
                               pleasure=0.89,
                               arousal=0.54,
                               dominance=-0.18)
    emotion_system.add_emotion(name="unconcerned",
                               pleasure=-0.13,
                               arousal=-0.41,
                               dominance=0.08)

    homedir = os.path.expanduser("~")
    path = homedir + "/controller.db"

    # Fill database with default values
    if (os.path.exists(path) == False):
        event_cost = 0.6  #
        database_handler = DatabaseHandler(filename=path)
        database_handler.create()
        database_handler.add_event(state="idle",
                                   event="music_play",
                                   reward_pleasure=0.08,
                                   reward_arousal=0.02,
                                   reward_dominance=-0.03,
                                   event_cost=event_cost * 2)
        database_handler.add_event(state="idle",
                                   event="astrolanguage",
                                   reward_pleasure=0.04,
                                   reward_arousal=0.05,
                                   reward_dominance=0.04,
                                   event_cost=event_cost * 1.5)
        database_handler.add_event(state="idle",
                                   event="navigation_emotional",
                                   reward_pleasure=0.02,
                                   reward_arousal=0.04,
                                   reward_dominance=-0.02,
                                   event_cost=event_cost)
        database_handler.add_event(state="idle",
                                   event="show_off_mea",
                                   reward_pleasure=0.02,
                                   reward_arousal=0.01,
                                   reward_dominance=0.01,
                                   event_cost=event_cost / 2)
        database_handler.add_event(state="idle",
                                   event="convey_emotion",
                                   reward_pleasure=0.01,
                                   reward_arousal=-0.01,
                                   reward_dominance=0.02,
                                   event_cost=event_cost / 3)

    # Create motivator
    motivator = Motivator(database_file=path)
    motivator.start()

    # Create a SMACH state machine
    sm = smach.StateMachine(outcomes=["error"])

    sm.userdata.state_machine_events = []
    sm.userdata.last_state = "initializing"
    sm.userdata.last_event = "start_up"

    with sm:
        sm_remapping = {
            "input_events": "state_machine_events",
            "output_events": "state_machine_events",
            "previous_state": "last_state",
            "current_state": "last_state",
            "previous_event": "last_event",
            "current_event": "last_event"
        }

        idle_transitions = {
            "navigation_schedular": "navigation",
            "navigation_emotional": "navigation",
            "convey_emotion": "conveying_emotional_state",
            "show_off_mea": "show_off_mea",
            "music_play": "music_horror",
            "astrolanguage": "astrolanguage",
            "aborted": "idle",
            "power_low": "exhausted",
            "bedtime": "sleepy"
        }
        idle_resources = {}  # Idle does not require any resources

        smach.StateMachine.add(
            "idle",
            Module("idle", "cyborg_primary_states", idle_transitions,
                   idle_resources), idle_transitions, sm_remapping)

        sleepy_transitions = {"aborted": "idle", "succeeded": "sleeping"}
        sleepy_resources = {}
        show_off_mea_transitions = {"aborted": "idle", "succeeded": "idle"}
        smach.StateMachine.add(
            "show_off_mea",
            Module("show_off_mea", "cyborg_behavior", show_off_mea_transitions,
                   sleepy_resources), show_off_mea_transitions, sm_remapping)

        smach.StateMachine.add(
            "sleepy",
            Module("sleepy", "cyborg_behavior", sleepy_transitions,
                   sleepy_resources), sleepy_transitions, sm_remapping)

        exhausted_transitions = {"aborted": "idle", "succeeded": "sleeping"}
        exhausted_resources = {}
        smach.StateMachine.add(
            "exhausted",
            Module("exhausted", "cyborg_behavior", exhausted_transitions,
                   exhausted_resources), exhausted_transitions, sm_remapping)

        sleeping_transitions = {
            "preempted": "idle",
            "cyborg_wake_up": "waking_up"
        }

        sleeping_resources = {}
        smach.StateMachine.add(
            "sleeping",
            Module("sleeping", "cyborg_primary_states", sleeping_transitions,
                   sleeping_resources), sleeping_transitions, sm_remapping)

        waking_up_transitions = {"aborted": "idle", "succeeded": "idle"}
        waking_up_resources = {}

        smach.StateMachine.add(
            "waking_up",
            Module("waking_up", "cyborg_behavior", waking_up_transitions,
                   waking_up_resources), waking_up_transitions, sm_remapping)

        conveying_emotion_transitions = {
            "aborted": "idle",
            "succeeded": "idle"
        }
        conveying_emotion_resources = {}

        smach.StateMachine.add(
            "conveying_emotional_state",
            Module("conveying_emotional_state", "cyborg_behavior",
                   conveying_emotion_transitions, conveying_emotion_resources),
            conveying_emotion_transitions, sm_remapping)

        sm_nav = smach.StateMachine(
            outcomes=["succeeded", "aborted", "power_low"])

        with sm_nav:

            navigation_planning_transitions = {
                "navigation_start_moving_schedular":
                "navigation_go_to_schedular",
                "navigation_start_moving_emotional":
                "navigation_go_to_emotional",
                "navigation_start_wandering": "wandering_emotional",
                "aborted": "aborted"
            }
            navigation_planning_resources = {}

            smach.StateMachine.add(
                "navigation_planning",
                Module("navigation_planning", "cyborg_primary_states",
                       navigation_planning_transitions,
                       navigation_planning_resources),
                navigation_planning_transitions, sm_remapping)

            navigation_go_to_transitions = {
                "succeeded": "succeeded",
                "aborted": "aborted",
                "preempted": "aborted"
            }

            smach.StateMachine.add(
                "navigation_go_to_emotional",
                statemachines.sequence_navigation_go_to_emotional,
                transitions=navigation_go_to_transitions,
                remapping=sm_remapping)

            navigation_go_to_schedular_resources = {}
            smach.StateMachine.add(
                "navigation_go_to_schedular",
                Module("navigation_go_to_schedular", "cyborg_behavior",
                       navigation_go_to_transitions,
                       navigation_go_to_schedular_resources),
                navigation_go_to_transitions, sm_remapping)

            navigation_wandering_emotional_transitions = {
                "navigation_wandering_complete": "succeeded",
                "aborted": "aborted",
                "power_low": "power_low"
            }
            navigation_wandering_emotional_resources = {}

            smach.StateMachine.add(
                "wandering_emotional",
                Module("wandering_emotional", "cyborg_primary_states",
                       navigation_wandering_emotional_transitions,
                       navigation_wandering_emotional_resources),
                navigation_wandering_emotional_transitions, sm_remapping)

        sm_nav_transitions = {
            "aborted": "idle",
            "succeeded": "idle",
            "power_low": "exhausted"
        }
        smach.StateMachine.add("navigation", sm_nav, sm_nav_transitions,
                               sm_remapping)

        music_transitions = {"aborted": "idle", "succeeded": "idle"}
        music_resources = {}
        smach.StateMachine.add(
            "music_horror",
            Module("music_horror", "cyborg_behavior", music_transitions,
                   music_resources), music_transitions, sm_remapping)

        astrolanguage_transitions = {"aborted": "idle", "succeeded": "idle"}
        astrolanguage_resources = {}
        smach.StateMachine.add(
            "astrolanguage",
            Module("astrolanguage", "cyborg_behavior",
                   astrolanguage_transitions, astrolanguage_resources),
            astrolanguage_transitions, sm_remapping)

        sm.register_io_keys(
            {"state_machine_events", "last_state", "last_event"})
        sm_nav.register_io_keys(
            {"state_machine_events", "last_state", "last_event"})

    rospy.sleep(3)
    sis = smach_ros.IntrospectionServer('controller_viewer', sm,
                                        '/controller_viewer')
    sis.start()

    smach_thread = threading.Thread(target=sm.execute)
    smach_thread.daemon = True
    smach_thread.start()
    # Start ROS main looping
    rospy.loginfo("Controller: Activated...")
    rospy.spin()
    sis.stop()
    rospy.loginfo("Controller: Terminated...")
示例#14
0
class PrimaryStatesServer():
    """Primary States Server"""
    def __init__(self, database_file=""):
        self.action_name = rospy.get_name()
        self.MAP_NAME = "glassgarden.map"
        self.PLANNING_TIMEOUT = 10
        self.RATE_ACTIONLOOP = rospy.Rate(4)  # Hz

        self.next_location = ""
        self.current_emotional_state = "neutral"
        self.current_state = ""
        self.database_handler = DatabaseHandler(filename=database_file)

        self.publisher_emotional_feedback = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)
        self.subscriber_emotional_state = rospy.Subscriber(
            "/cyborg_controller/emotional_state",
            EmotionalState,
            self.emotional_callback,
            queue_size=10)
        self.publisher_event = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.publisher_location_command = rospy.Publisher(
            "/cyborg_behavior/command_location", String, queue_size=10)

        self.client_behavior = actionlib.SimpleActionClient(
            "/cyborg_behavior", StateMachineAction)
        self.server_primary_states = actionlib.SimpleActionServer(
            self.action_name,
            StateMachineAction,
            execute_cb=self.callback_server_primary_states,
            auto_start=False)
        self.server_primary_states.start()
        rospy.loginfo("PrimaryStatesServer: Initiated")

    def callback_server_primary_states(self, goal):
        self.state_goal = goal
        if self.state_goal.current_state == "wandering_emotional":
            self.wandering_emotional()
        elif self.state_goal.current_state == "navigation_planning":
            self.navigation_planning_state(self.state_goal)

    def emotional_callback(self, message):
        self.current_emotional_state = message.to_emotional_state

    def create_and_send_behavior_goal(self, behavior, location=None):
        # Create and send goal to behaviorserver
        goal = StateMachineGoal()
        goal.current_state = behavior
        if location != None:
            goal.order = location
        self.client_behavior.send_goal(goal)

    # Check execution of action
    def actionloop_check(self):
        # Check if preempt is requested
        if self.server_primary_states.is_preempt_requested():
            self.client_behavior.cancel_all_goals()
            self.server_primary_states.set_preempted()
            rospy.loginfo("PrimaryStatesServer: %s state preempted.",
                          self.current_state)
            return True
        else:
            # Check behaviorserver state
            behaviorserver_state = self.client_behavior.get_state()
            # not active
            if behaviorserver_state == 3:
                # succeeded
                rospy.loginfo(
                    "PrimaryStatesServer: %s state BehaviorServer goal succeeded. ",
                    self.current_state)
                self.server_primary_states.set_succeeded()
                return True
            elif behaviorserver_state == 2:
                # Preempted
                rospy.loginfo(
                    "PrimaryStatesServer: %s state BehaviorServer goal was preempted. ",
                    self.current_state)
                self.server_primary_states.set_preempted()
                return True
            elif behaviorserver_state == 4:
                # aborted
                rospy.loginfo(
                    "PrimaryStatesServer: %s state BehaviorServer goal aborted. ",
                    self.current_state)
                self.server_primary_states.set_aborted()
                return True

    def wandering_emotional(self):
        rospy.loginfo("PrimaryStatesServer: Executing wander emotional state.")
        #connect to server and send goal
        goal = "wandering_emotional"
        self.create_and_send_behavior_goal(goal)
        while not rospy.is_shutdown():
            if self.actionloop_check() == True:
                return
            elif self.current_emotional_state not in [
                    "bored", "curious", "unconcerned"
            ]:  # emotions currently not integrated in server
                self.client_behavior.cancel_all_goals()
                rospy.sleep(2)
                self.server_primary_states.set_succeeded()
                rospy.loginfo(
                    "PrimaryStatesServer: wandering complete, preempted.")
                return
            self.RATE_ACTIONLOOP.sleep()
        # set terminal goal status in case of shutdown
        self.server_primary_states.set_aborted()

    # Called when the controller (state machine) sets the navigation_planning state as active
    def navigation_planning_state(self, goal):
        rospy.loginfo(
            "PrimaryStatesServer: Executing navigation_planning state.")
        time.sleep(1)  # let roscore update connections
        self.next_location = None
        if goal.event == "navigation_schedular":
            if self.current_emotional_state == "angry":
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.MAP_NAME, crowded=False)
                message = String(data=self.next_location.location_name)
                self.publisher_location_command.publish(message)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving_schedular")
            else:
                self.next_location = self.database_handler.search_ongoing_events(
                    robot_map_name=self.MAP_NAME,
                    current_date=datetime.datetime.now())
                message = String(data=self.next_location.location_name)
                self.publisher_location_command.publish(message)
                self.send_emotion(pleasure=0, arousal=0, dominance=-0.1)
                self.change_state(event="navigation_start_moving_schedular")

        elif goal.event == "navigation_emotional":
            if self.current_emotional_state in [
                    "angry", "sad", "fear", "inhibited"
            ]:
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.MAP_NAME, crowded=False)
                message = String(data=self.next_location.location_name)
                self.publisher_location_command.publish(message)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving_emotional")

            elif self.current_emotional_state in [
                    "happy", "loved", "dignified", "neutral", "elated"
            ]:
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.MAP_NAME, crowded=True)
                message = String(data=self.next_location.location_name)
                self.publisher_location_command.publish(message)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving_emotional")

            elif self.current_emotional_state in [
                    "bored", "curious", "unconcerned"
            ]:
                self.next_location = "wandering"
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_wandering")

    def change_state(self, event=None):
        if event == None:
            self.server_primary_states.set_aborted()
            return
        else:
            if event == "navigation_start_moving":
                if self.next_location != None:
                    self.publisher_event.publish(event)
            else:
                self.publisher_event.publish(event)
        # wait until state is preempted, or abort if it takes too long
        started_waiting = time.time()
        while not rospy.is_shutdown():
            if self.server_primary_states.is_preempt_requested():
                self.server_primary_states.set_preempted()
                return
            elif (time.time() - started_waiting > self.PLANNING_TIMEOUT):
                self.server_primary_states.set_aborted()
                return
            self.RATE_ACTIONLOOP.sleep()
        # set terminal goal status in case of shutdown
        self.server_primary_states.set_aborted()

    # Sends the emotional change to the controller
    def send_emotion(self, pleasure, arousal, dominance):
        msg = EmotionalFeedback()
        msg.delta_pleasure = pleasure
        msg.delta_arousal = arousal
        msg.delta_dominance = dominance
        self.publisher_emotional_feedback.publish(msg)
class NavigationServer():
    """NavigationServer"""
    def __init__(self, database_file=""):
        self.MAP_NAME = "glassgarden.map"
        self.TIMEOUT_GOTO = 300  # (S)
        self.TIMEOUT_WANDERING = 600  # (S)
        self.EMOTIONAL_FEEDBACK_CYCLE = 15  # (s)
        self.SERVER_RATE = rospy.Rate(10)  #(Hz)

        self.client_base_feedback = StateMachineFeedback()
        self.client_base_result = StateMachineResult()

        self.current_x = 0.0
        self.current_y = 0.0
        self.next_location = None
        self.current_location = None
        self.current_location_name = None
        self.base_canceled = False
        self.base_succeeded = False

        self.location_subscriber = rospy.Subscriber("/rosarnl_node/amcl_pose",
                                                    PoseWithCovarianceStamped,
                                                    self.location_callback)
        self.publisher_current_location = rospy.Publisher(rospy.get_name() +
                                                          "/current_location",
                                                          String,
                                                          queue_size=10)
        self.emotion_publisher = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)

        self.server_navigation = actionlib.SimpleActionServer(
            rospy.get_name() + "/navigation",
            NavigationAction,
            execute_cb=self.navigationserver_callback,
            auto_start=False)
        self.server_navigation.start()
        self.client_base = actionlib.SimpleActionClient(
            "/rosarnl_node/move_base", MoveBaseAction)

        self.database_handler = DatabaseHandler(filename=database_file)
        self.location_updater_thread = threading.Thread(
            target=self.location_updater)
        self.location_updater_thread.daemon = True
        self.location_updater_thread.start()
        rospy.loginfo("NavigationServer: Activated.")

    # Updates the current position when the position subscriber receives data
    def location_callback(self, data):
        self.current_x = data.pose.pose.position.x
        self.current_y = data.pose.pose.position.y

    # Updates current location based on position and publishes to other nodes
    def location_updater(self):  # Threaded
        rospy.sleep(1)
        while not rospy.is_shutdown():
            self.current_location = self.database_handler.find_location(
                robot_map_name=self.MAP_NAME,
                location_x=self.current_x,
                location_y=self.current_y)
            self.current_location_name = self.current_location.location_name if self.current_location != None else ""
            self.publisher_current_location.publish(
                data=self.current_location_name)
            rospy.sleep(1)

    # Called once when the robot base (ROSARNL) goal completes
    def client_base_done_callback(self, state, result):
        if self.is_controlling_base:
            if (state == 3):  # Succeeded aka arrived at location
                self.base_succeeded = True
            elif (state == 2):  # Happens when we cancel goals aka preempted
                self.base_canceled = True
            elif (state == 1):  # Canceled?
                self.base_canceled = True
            elif (state == 4):  # aborted
                self.base_canceled = True
            self.client_base_state = state
            self.client_base_result = result
            rospy.logdebug(
                "NavigationServer: Base has completed its execution with " +
                str(state) + " and result " + str(result) + ".")

    # Called once when the robot base (ROSARNL) goal becomes active
    def client_base_active_callback(self):
        rospy.logdebug("NavigationServer: Base goal has gone active.")
        self.is_controlling_base = True

    # Called every time feedback is received for the goal for the robot base (ROSARNL)
    def client_base_feedback_callback(self, feedback):
        rospy.logdebug("NavigationServer: Received feedback from base - " +
                       str(feedback) + ".")
        self.client_base_feedback = feedback

    #Callback for navigation, used for initiating wandering, docking, or go to location
    def navigationserver_callback(self, goal):
        self.base_canceled = False
        self.base_succeeded = False
        rospy.loginfo("NavigationServer Callback initiating:" +
                      str(goal.order) + " order, and " +
                      str(goal.location_name) + " location.")
        self.is_controlling_base = False

        if goal.order == "navigation_wander":
            self.start_wandering()
        elif goal.order == "navigation_go_to" and goal.location_name != None:
            self.navigation_go_to(goal)
        elif goal.order == "navigation_dock":
            self.navigation_dock()
        else:
            self.server_navigation.set_aborted()
            rospy.logdebug(
                "NavigationServer: Received event that cant be handled - " +
                str(goal.order) + ".")

    # This can be used by other nodes for moving the cyborg to a known location.
    # Preemptable, ends in Succeeded, Aborted or Preempted.
    # Increases PAD values while moving
    def navigation_go_to(self, goal):
        self.goal = goal
        rospy.loginfo("NavigationServer: go to server received a goal - " +
                      str(self.goal.location_name))
        self.next_location = self.database_handler.search_for_location(
            location_name=self.goal.location_name)
        if self.next_location != None:
            self.check_and_send_goal(location=self.next_location)
            start_time = time.time()
            feedback_timer = time.time()
            # Wait until state is preempted or succeeded
            while not rospy.is_shutdown():
                if self.base_succeeded:
                    self.send_emotion(pleasure=self.next_location.environment,
                                      arousal=0,
                                      dominance=0.0)
                    self.server_navigation.set_succeeded()
                    self.next_location = None
                    return
                if self.server_navigation.is_preempt_requested():
                    self.client_base.cancel_all_goals()
                    self.server_navigation.set_preempted
                    return
                if self.base_canceled:
                    self.server_navigation.set_aborted()
                    return
                else:
                    server_feedback = NavigationFeedback(status="moving")
                    self.server_navigation.publish_feedback(server_feedback)
                if (time.time() - start_time >
                        self.TIMEOUT_GOTO):  #prevent eternal looping of state
                    self.client_base.cancel_all_goals()
                    self.server_navigation.set_aborted()
                    return
                #give emotional feedback
                if (time.time() - feedback_timer >
                        self.EMOTIONAL_FEEDBACK_CYCLE):
                    self.send_emotion(pleasure=0.0,
                                      arousal=0.02,
                                      dominance=-0.01)
                    feedback_timer = time.time()
                    #return
                self.SERVER_RATE.sleep()
            # set terminal goal status in case of shutdown
            self.server_navigation.set_aborted()
        else:
            rospy.logdebug(
                "NavigationServer: Go to server received a location with unrecognized name - "
                + str(goal.location_name))
            self.server_navigation.set_aborted()

    # Sends the location to the ROSARNL node (Pioneer XL robot base)
    # Added check path of goal before sending
    def check_and_send_goal(self, location):
        if (self.client_base.wait_for_server(
                rospy.Duration.from_sec(5.0)) == False):
            rospy.logwarn(
                "NavigationServer: ERROR - Unable to connect to Pioneer XL.")
            self.base_canceled = True
            return
        pose = geometry_msgs.msg.Pose()
        pose.position.x = location.x
        pose.position.y = location.y
        pose.position.z = location.z
        q = tf.transformations.quaternion_from_euler(location.p, location.j,
                                                     location.r)
        pose.orientation = geometry_msgs.msg.Quaternion(*q)
        goal = MoveBaseGoal()
        goal.target_pose.pose = pose
        goal.target_pose.header.frame_id = location.robot_map_name
        goal.target_pose.header.stamp = rospy.Time.now()
        rospy.wait_for_service("/rosarnl_node/make_plan")
        baseCheckPath = rospy.ServiceProxy("/rosarnl_node/make_plan",
                                           MakePlan())
        makeplan = MakePlan()
        makeplan.position = location
        makeplan.orientation = pose.orientation
        try:
            path = baseCheckPath(makeplan)
            if (len(path.path) > 0):
                goal.target_pose.header.stamp = rospy.Time.now()
                self.client_base.send_goal(goal,
                                           self.client_base_done_callback,
                                           self.client_base_active_callback,
                                           self.client_base_feedback_callback)
                rospy.loginfo("NavigationServer: Path OK.")
                rospy.logdebug("NavigationServer: Location goal is - " +
                               str(self.next_location))
            else:
                rospy.logdebug("NavigationServer: Could not compute path to " +
                               str(self.next_location) + ".")
                self.next_location = None
                self.base_canceled = True
        except rospy.ServiceException as exc:
            rospy.logdebug(
                "NavigationServer: Make plan service did not process request: "
                + str(exc))
            self.next_location = None
            self.base_canceled = True
            return

    # The robot base starts to wander and keeps wandering until it is preempted
    def start_wandering(self):
        # Tell base to start wandering
        rospy.logdebug("NavigationServer: Waiting for base wandering service.")
        rospy.wait_for_service("/rosarnl_node/wander")
        rospy.logdebug("NavigationServer: wandering service available.")
        try:
            baseStartWandering = rospy.ServiceProxy("/rosarnl_node/wander",
                                                    Empty)
            baseStartWandering()
        except rospy.ServiceException, e:
            rospy.logdebug("NavigationServer: wandering service error - " +
                           str(e))

        started_waiting = time.time()  # Prevent eternal looping
        feedback_timer = time.time()
        while not rospy.is_shutdown():
            if self.server_navigation.is_preempt_requested():
                self.client_base.cancel_all_goals()
                try:
                    baseStop = rospy.ServiceProxy("/rosarnl_node/stop", Empty)
                    baseStop()
                except rospy.ServiceException, e:
                    rospy.logdebug("NavigationServer: stop service error - " +
                                   str(e))
                self.server_navigation.set_preempted()
                return
            # Check wandering timeout to prevent eternal looping
            if (time.time() - started_waiting > self.TIMEOUT_WANDERING):
                rospy.loginfo("NavigationServer: Timed out, aborting.")
                self.client_base.cancel_all_goals()
                try:
                    baseStop = rospy.ServiceProxy("/rosarnl_node/stop", Empty)
                    baseStop()
                except rospy.ServiceException, e:
                    rospy.logdebug("NavigationServer: stop service error - " +
                                   str(e))
                self.server_navigation.set_aborted()
                return
示例#16
0
def main():
    rospy.init_node("cyborg_controller")

    # Create emotions
    emotion_system = EmotionSystem()
    emotion_system.add_emotion(name="angry",
                               pleasure=-0.51,
                               arousal=0.59,
                               dominance=0.25)
    emotion_system.add_emotion(name="bored",
                               pleasure=-0.65,
                               arousal=-0.62,
                               dominance=-0.33)
    emotion_system.add_emotion(name="curious",
                               pleasure=0.22,
                               arousal=0.62,
                               dominance=-0.10)
    emotion_system.add_emotion(name="dignified",
                               pleasure=0.55,
                               arousal=0.22,
                               dominance=0.61)
    emotion_system.add_emotion(name="elated",
                               pleasure=0.50,
                               arousal=0.42,
                               dominance=0.23)  # Happy
    emotion_system.add_emotion(name="inhibited",
                               pleasure=-0.54,
                               arousal=-0.04,
                               dominance=-0.41)  # Sadness
    emotion_system.add_emotion(name="puzzled",
                               pleasure=-0.41,
                               arousal=0.48,
                               dominance=-0.33)  # Suprized
    emotion_system.add_emotion(name="loved",
                               pleasure=0.89,
                               arousal=0.54,
                               dominance=-0.18)
    emotion_system.add_emotion(name="unconcerned",
                               pleasure=-0.13,
                               arousal=-0.41,
                               dominance=0.08)

    homedir = os.path.expanduser("~")
    path = homedir + "/controller.db"

    # Fill database with default values
    if (os.path.exists(path) == False):
        event_cost = 0.45
        database_handler = DatabaseHandler(filename=path)
        database_handler.create()
        database_handler.add_event(state="idle",
                                   event="music_play",
                                   reward_pleasure=0.08,
                                   reward_arousal=0.01,
                                   reward_dominance=-0.02,
                                   event_cost=event_cost)
        database_handler.add_event(state="idle",
                                   event="navigation_emotional",
                                   reward_pleasure=0.00,
                                   reward_arousal=0.05,
                                   reward_dominance=-0.01,
                                   event_cost=event_cost)

        database_handler.add_event(state="conversation",
                                   event="weather_tell",
                                   reward_pleasure=0.05,
                                   reward_arousal=0.00,
                                   reward_dominance=0.00,
                                   event_cost=event_cost)
        database_handler.add_event(state="conversation",
                                   event="joke_tell",
                                   reward_pleasure=0.05,
                                   reward_arousal=0.02,
                                   reward_dominance=0.00,
                                   event_cost=event_cost)
        database_handler.add_event(state="conversation",
                                   event="selfie_take",
                                   reward_pleasure=0.05,
                                   reward_arousal=-0.02,
                                   reward_dominance=0.01,
                                   event_cost=event_cost * 1.5)
        database_handler.add_event(state="conversation",
                                   event="simon_says_play",
                                   reward_pleasure=0.00,
                                   reward_arousal=0.00,
                                   reward_dominance=0.10,
                                   event_cost=event_cost)
        database_handler.add_event(state="conversation",
                                   event="follower_follow",
                                   reward_pleasure=0.00,
                                   reward_arousal=0.05,
                                   reward_dominance=-0.05,
                                   event_cost=event_cost)

    # Create motivator
    motivator = Motivator(database_file=path)
    motivator.start()

    # Create a SMACH state machine
    state_machine = smach.StateMachine(outcomes=["error"])
    state_machine.userdata.state_machine_events = []
    state_machine.userdata.last_state = "initializing"
    state_machine.userdata.last_event = "start_up"

    # Open the container
    with state_machine:
        # Remapp outputs, so userdata can be moved between states
        state_machine_remapping = {
            "input_events": "state_machine_events",
            "output_events": "state_machine_events",
            "previous_state": "last_state",
            "current_state": "last_state",
            "previous_event": "last_event",
            "current_event": "last_event"
        }

        # Add states to the container
        idle_transitions = {
            "conversation_interest": "conversation",
            "navigation_schedualer": "navigation_planing",
            "navigation_emotional": "navigation_planing",
            "aborted": "idle",
            "navigation_command": "navigation_planing",
            "music_play": "music"
        }
        idle_resources = {}  # Idle does not require any resources
        smach.StateMachine.add(label="idle",
                               state=Module(state_name="idle",
                                            actionlib_name="cyborg_idle/idle",
                                            transitions=idle_transitions,
                                            resources=idle_resources),
                               transitions=idle_transitions,
                               remapping=state_machine_remapping)

        conversation_transitions = {
            "aborted": "idle",
            "succeded": "idle",
            "navigation_feedback": "navigation_talking",
            "navigation_command": "navigation_talking",
            "navigation_information": "navigation_talking",
            "simon_says_play": "simon_says",
            "selfie_take": "selfie",
            "follower_follow": "follower",
            "weather_tell": "weather",
            "joke_tell": "joke"
        }
        conversation_resources = {"trollface": "cyborg_conversation"}
        smach.StateMachine.add(
            label="conversation",
            state=Module(state_name="conversation",
                         actionlib_name="cyborg_conversation/conversation",
                         transitions=conversation_transitions,
                         resources=conversation_resources),
            transitions=conversation_transitions,
            remapping=state_machine_remapping)

        navigation_transitions = {
            "aborted": "navigation_talking",
            "navigation_start_wandering": "navigation_moving",
            "navigation_start_moving": "navigation_moving",
            "succeded": "navigation_talking"
        }
        navigation_resources = {"base": "cyborg_navigation"}
        smach.StateMachine.add(label="navigation_planing",
                               state=Module(
                                   state_name="navigation_planing",
                                   actionlib_name="cyborg_navigation/planing",
                                   transitions=navigation_transitions,
                                   resources=navigation_resources),
                               transitions=navigation_transitions,
                               remapping=state_machine_remapping)

        navigation_transitions = {
            "aborted": "navigation_talking",
            "succeded": "navigation_talking",
            "navigation_wandering_completed": "idle"
        }
        navigation_resources = {"base": "cyborg_navigation"}
        smach.StateMachine.add(label="navigation_moving",
                               state=Module(
                                   state_name="navigation_moving",
                                   actionlib_name="cyborg_navigation/moving",
                                   transitions=navigation_transitions,
                                   resources=navigation_resources),
                               transitions=navigation_transitions,
                               remapping=state_machine_remapping)

        navigation_transitions = {
            "aborted": "idle",
            "succeded": "idle",
            "navigation_feedback_completed": "conversation",
            "navigation_command": "navigation_planing"
        }
        navigation_resources = {
            "base": "cyborg_navigation",
            "trollface": "cyborg_navigation"
        }
        smach.StateMachine.add(label="navigation_talking",
                               state=Module(
                                   state_name="navigation_talking",
                                   actionlib_name="cyborg_navigation/talking",
                                   transitions=navigation_transitions,
                                   resources=navigation_resources),
                               transitions=navigation_transitions,
                               remapping=state_machine_remapping)

        music_transitions = {
            "aborted": "idle",
            "succeded": "idle",
            "conversation_interest": "conversation"
        }
        music_resources = {}
        smach.StateMachine.add(label="music",
                               state=Module(
                                   state_name="music",
                                   actionlib_name="cyborg_music/music",
                                   transitions=music_transitions,
                                   resources=music_resources),
                               transitions=music_transitions,
                               remapping=state_machine_remapping)

        smach.StateMachine.add(
            label="simon_says",
            state=Module(state_name="simon_says",
                         actionlib_name="cyborg_conversation/simon_says",
                         transitions={
                             "aborted": "conversation",
                             "succeded": "conversation"
                         },
                         resources={"trollface": "cyborg_simon_says"}),
            transitions={
                "aborted": "conversation",
                "succeded": "conversation"
            },
            remapping=state_machine_remapping)

        smach.StateMachine.add(label="selfie",
                               state=Module(
                                   state_name="selfie",
                                   actionlib_name="cyborg_conversation/selfie",
                                   transitions={
                                       "aborted": "conversation",
                                       "succeded": "conversation"
                                   },
                                   resources={"trollface": "cyborg_selfie"}),
                               transitions={
                                   "aborted": "conversation",
                                   "succeded": "conversation"
                               },
                               remapping=state_machine_remapping)

        smach.StateMachine.add(
            label="follower",
            state=Module(state_name="follower",
                         actionlib_name="cyborg_conversation/follower",
                         transitions={
                             "aborted": "conversation",
                             "succeded": "conversation"
                         },
                         resources={"trollface": "cyborg_follower"}),
            transitions={
                "aborted": "conversation",
                "succeded": "conversation"
            },
            remapping=state_machine_remapping)

        smach.StateMachine.add(
            label="weather",
            state=Module(state_name="weather",
                         actionlib_name="cyborg_conversation/weather",
                         transitions={
                             "aborted": "conversation",
                             "succeded": "conversation"
                         },
                         resources={"trollface": "cyborg_weather"}),
            transitions={
                "aborted": "conversation",
                "succeded": "conversation"
            },
            remapping=state_machine_remapping)

        smach.StateMachine.add(
            label="joke",  # name on state
            state=Module(
                state_name="joke",  # name on state
                actionlib_name="cyborg_conversation/joke",  # actionlib name
                transitions={
                    "aborted": "conversation",
                    "succeded": "conversation"
                },  #event name:state - events that leads away from state
                resources={"trollface": "cyborg_joke"
                           }),  # for gatekeepers: resource_name:node_name
            transitions={
                "aborted": "conversation",
                "succeded": "conversation"
            },
            remapping=state_machine_remapping)

        ################################################### ADD MORE STATES BELOW ###################################################

        ################################################### STOP ADDING YOUR STATES ###################################################

    # Create a state machine monitorer
    smm = StateMachineMonitor(state_machine, display_all=True)
    rospy.loginfo("Controller: State Machine Monitor Activated...")

    import smach_ros
    sis = smach_ros.IntrospectionServer('controler_viewer', state_machine,
                                        '/controler_viewer')
    sis.start()

    # Create a thread to execute the smach
    smach_thread = threading.Thread(target=state_machine.execute)
    smach_thread.daemon = True
    smach_thread.start()
    rospy.loginfo("Controller: SMACH activated...")

    # Start ROS main looping
    rospy.loginfo("Controller: Activated...")
    rospy.spin()
    sis.stop()
    rospy.loginfo("Controller: Terminated...")
class PCPPHelperBot:
    """Posts PC Part Picker markup tables when applicable.
    
    This utilizes the PRAW wrapper for interacting with Reddit. It streams
    new submissions in order to look for submissions with a PC Part Picker
    list URL. If the post already has a table, no action will be taken. If
    not, or it is malformed, a reply containing the table will be posted.
    """
    
    def __init__(self, log_file_handler, live=False):
        self.is_live = live
        
        # Logger setup
        if self.is_live:
            self.logger = logging.getLogger('PCPPHelperBot')
        else:
            self.logger = logging.getLogger('PCPPHelperBot-DEBUG')
            
        self.logger.addHandler(log_file_handler)
        now_str = datetime.now().strftime('%H:%M:%S')
        self.logger.info(f'STARTING {now_str}')
        
        # Database setup
        if self.is_live:
            self.db_handler = DatabaseHandler()
        else:
            self.db_handler = DatabaseHandler(debug=True)
        
        self.db_handler.connect()
        self.db_handler.create_table()

        # Retrieve environment vars for secret data
        username = os.environ.get('REDDIT_USERNAME')
        password = os.environ.get('REDDIT_PASSWORD')
        client_id = os.environ.get('CLIENT_ID')
        secret = os.environ.get('CLIENT_SECRET')
        
        version = 0.1
        user_agent = f"web:pcpp-helper-bot:v{version} (by u/pcpp-helper-bot)"
        
        # Utilize PRAW wrapper
        self.reddit = praw.Reddit(user_agent=user_agent,
                                  client_id=client_id, client_secret=secret,
                                  username=username, password=password)
        
        # Only look at submissions with one of these flairs
        # TODO: Are these the best submission flairs to use?
        self.pertinent_flairs = ['Build Complete', 'Build Upgrade',
                                 'Build Help', 'Build Ready', None]
        
        self.pcpp_parser = PCPPParser(log_file_handler)
        self.table_creator = TableCreator()
        self.MAX_TABLES = 2
        self.subreddit_name = None
        
        # Read in the templates
        with open('./templates/replytemplate.md', 'r') as template:
            self.REPLY_TEMPLATE = template.read()
        
        with open('./templates/idenlinkfound.md', 'r') as template:
            self.IDENTIFIABLE_TEMPLATE = template.read()
        
        with open('./templates/tableissuetemplate.md', 'r') as template:
            self.TABLE_TEMPLATE = template.read()
    
    def monitor_subreddit(self, subreddit_name: str):
        """Monitors the subreddit provided (mainly r/buildapc) for new
        submissions.
        
        Args:
            subreddit_name (str): The name of the subreddit
        """
        continue_monitoring = True
        self.subreddit_name = subreddit_name
        
        # skip_existing will skip the posts made BEFORE the bot starts observing
        # By default, up to 100 historical submissions/comments would be returned
        # See PRAW.reddit.SubredditStream #3147
        subreddit = self.reddit.subreddit(subreddit_name)
        
        # Stream in new submissions from the subreddit
        while continue_monitoring:
            try:
                for submission in subreddit.stream.submissions(skip_existing=True):
                    unpaired_urls, iden_anon_urls, table_data = self.read_submission(submission)
                    
                    # If there are missing/broken tables or identifiable links
                    if len(unpaired_urls) != 0 or len(iden_anon_urls) != 0:
                        self.logger.info('FOUND TABLELESS OR IDENTIFIABLE URLS')
                        self.logger.info(f'SUBMISSION TEXT: {submission.selftext}')
                        
                        self.reply(submission, unpaired_urls, iden_anon_urls, table_data)

                    should_stop, reason = self._check_inbox_for_stop()
                    if should_stop:
                        self.logger.info(f'STOPPING BY REQUEST. REASON: {reason}')
                        continue_monitoring = False
                        break
                        
            except Exception as e:
                self.logger.critical('Problem connecting to Reddit or in creating reply')
                self.logger.critical('Exception data: ', exc_info=True)
                
            # TODO: Catch any exceptions for when Reddit is down or PRAW has issues
        self._cleanup_database()

    def read_submission(self, submission: praw.reddit.Submission):
        """Reads a submission from Reddit.
        
        Args:
            submission ('obj': praw.reddit.Submission): A PRAW Submission object.
        
        Returns:
            (urls without tables, (identifiable, anonymous) pair list,
            {'total', 'valid', 'invalid', 'bad_markdown'} dict  of table
            data).
        """
        
        flair = submission.link_flair_text
        tableless_urls = []
        iden_anon_urls = []
        table_data = {'total': 0, 'valid': 0, 'invalid': 0, 'bad_markdown': False}
    
        if self._already_replied(submission.id):
            self.logger.info('Already replied to this submission.')
    
        # Only look at text submissions and with the appropriate flairs
        elif flair in self.pertinent_flairs and submission.is_self:
            self.logger.info(f'CHECKING SUBMISSION: {submission.url}')
        
            # Parse pertinent info from the submission
            tableless_urls, iden_anon_urls, table_data \
                = parse_submission(submission.selftext_html, submission.selftext, self.pcpp_parser)
                
        return tableless_urls, iden_anon_urls, table_data
        
    def reply(self, submission, unpaired_urls, iden_anon_urls, table_data):
        """Replies to a Reddit submission.
        
        Args:
            submission (`obj`: praw.Reddit.Submission): PRAW Submission object.
            unpaired_urls (list): urls without an accompanying table.
            iden_anon_urls (list): Pairs of identifiable, anonymous list urls.
            table_data (dict): Holds information about table data in submission.
            
        Returns:
            Reply message string if NOT live, otherwise PRAW.reddit.Comment object.
        """
    
        # Create the reply with this information
        reply_message = self._make_reply(unpaired_urls,
                                        iden_anon_urls,
                                        table_data)
    
        # Only if the bot is 'live' on Reddit or not
        if self.is_live:
            # Post the reply!
            reply = submission.reply(reply_message)
            self._save_reply_db(reply, submission, table_data, iden_anon_urls, unpaired_urls)
            return reply
        else:
            return reply_message

    def _make_reply(self, tableless_urls: list, iden_anon_urls: list, table_data: dict):
        """Creates the full reply message.
        
        Args:
            tableless_urls (list): List of urls that don't have an accompanying
                                    table.
            iden_anon_urls (list): List of (identifiable, anonymous) urls found.
            table_data (dict): Dictionary describing the table data found
                                in the submission.
                                
        Returns:
            The entire reply message, ready to be posted.
        """
        
        table_markdown = self._make_table_markdown(tableless_urls, table_data)
        iden_markdown = self._make_identifiable_markdown(iden_anon_urls)
        
        if len(table_markdown) == 0 and len(tableless_urls) != 0:
            self.logger.error('Failed to make table markdown for urls: {tableless_urls}')
            
        if len(iden_anon_urls) != 0 and len(iden_markdown) == 0:
            self.logger.error(f'Failed to make identifiable markdown for urls: {iden_anon_urls}')
        
        reply_message = self._put_message_together(table_markdown,
                                                   iden_markdown)
        
        if len(reply_message) == 0:
            self.logger.error('Failed to create a message.')
        else:
            self.logger.info(f'Reply: {reply_message}')
        
        return reply_message
    
    def _put_message_together(self, table_markdown: str, iden_markdown: str):
        """Puts together the variable data into a message.
        
        Args:
            table_markdown (str): Contains the markdown for the table data.
            iden_markdown (str): Contains the markdown for the identifiable
                                    message and data.
                                    
        Returns:
            A string containing the combined reply message.
        """
        
        reply_message = ''
        message_markdown = []
        
        if len(table_markdown) != 0:
            message_markdown.append(table_markdown)
        
        if len(iden_markdown) != 0:
            message_markdown.append(iden_markdown)
        
        if len(message_markdown) != 0:
            message_markdown = '\n\n'.join(message_markdown)
            reply_message = self.REPLY_TEMPLATE.replace(':message:', message_markdown)
        
        return reply_message
    
    def _make_table_markdown(self, urls: list, table_data: dict):
        """Put together the table markdown. This could be up to self.MAX_TABLES.
        
        Args:
            urls (list): List of PCPP urls to make tables for.
            table_data (dict): Dictionary describing the table data found
                                in the submission.
            
        Returns:
            A string containing the markdown for the tables for the PCPP lists.
        """
        
        table_message = ''
        issues = []
        
        if urls and 0 < len(urls) <= self.MAX_TABLES:
            all_table_markdown = []
            
            # Create the table markup for each list url
            for pcpp_url in urls:
                list_html = self.pcpp_parser.request_page_data(pcpp_url)
                parts_list, total = self.pcpp_parser.parse_page(list_html)
                table_markdown = self.table_creator.create_markdown_table(pcpp_url, parts_list, total)
                all_table_markdown.append(table_markdown)
            
            # Put the table(s) together
            all_table_markdown = '\n\n\n'.join(all_table_markdown)
            
            lists_without_tables = abs(table_data['total'] - len(urls))
            # Check which issue(s) occurred (at least one will match)
            if table_data['total'] == 0 or lists_without_tables != 0:
                issues.append('a missing table')
            if table_data['invalid'] != 0:
                issues.append('a broken or partial table')
            if table_data['bad_markdown']:
                issues.append('escaped or broken markdown')
            
            issues_markdown = ', '.join(issues)
            
            # Input the message data into the template
            table_message = self.TABLE_TEMPLATE.replace(':issues:', issues_markdown)
            table_message = table_message.replace(':table:', all_table_markdown)
        
        return table_message
    
    def _make_identifiable_markdown(self, iden_anon_urls: list):
        """Creates the message for when identifiable list urls are found.
        
        Args:
            iden_anon_urls (list): List of (identifiable, anonymous) urls found.
            
        Returns:
            A string containing the markdown message for when identifiable
            urls are found.
        """
        
        iden_markdown = ''
        
        if iden_anon_urls and len(iden_anon_urls) > 0:
            list_items = []
            
            # Create a bullet point showing the anonymous list url for
            # each identifiable list url found.
            for iden_url, anon_url in iden_anon_urls:
                # identifiable -> anonymous
                list_items.append(f'* {iden_url} &#8594; {anon_url}')
            
            list_markdown = '\n'.join(list_items)
            
            # Put the list into the template
            iden_markdown = self.IDENTIFIABLE_TEMPLATE.replace(':urls:', list_markdown)
        
        return iden_markdown

    def _save_reply_db(self, reply: praw.reddit.Comment,
                      submission: praw.reddit.Submission,
                      table_data: dict,
                      iden_anon_urls: list,
                      urls: list):
        """Save the reply data into the database.
        
        Args:
            reply (PRAW.Reddit.Comment): The reply left by the bot
            submission (PRAW.Reddit.Submission): Submission the bot replied to
            table_data (dict): Holds data about the tables
            iden_anon_urls (list): List of identifiable links
            urls (list): List of the PCPP urls I made tables for
        """
        
        flair = submission.link_flair_text
        had_identifiable = len(iden_anon_urls) != 0
        missing_table = table_data['total'] == 0
        
        # Reddit id's are in base 36
        reply_id = int(reply.id, 36)
        submission_id = int(submission.id, 36)
    
        try:
            self.db_handler.insert_reply(reply_id, reply.created_utc,
                                         submission_id, flair,
                                         submission.url,
                                         submission.created_utc,
                                         str(urls),
                                         had_identifiable,
                                         table_data['bad_markdown'],
                                         table_data['invalid'],
                                         missing_table,
                                         len(urls)
                                         )
        except mysql_errors.IntegrityError as e:
            self.logger.error('MySql insertion error: %s', e.msg)
        
    def _cleanup_database(self):
        """Cleanup."""
        
        # Want to cleanup the table if just testing.
        if not self.is_live:
            self.db_handler.clear_table()

        self.db_handler.disconnect()

    def _already_replied(self, submission_id: str):
        """Check if the bot has replied already to this submission."""
        
        id_as_int = int(submission_id, 36)
        reply = self.db_handler.select_reply(id_as_int)
        
        return reply is not None
    
    def _check_inbox_for_stop(self):
        """Checks if a moderator messaged the bot to stop running.
        The subject must be 'stop', and the body of the message
        contains an optional reason for stopping the bot.
        
        Returns:
            (boolean on if to stop, a string containing the reason).
        """
        
        should_stop = False
        reason = ''
        
        for item in self.reddit.inbox.unread():
            # Check if it is a message, not a mention or something else
            if isinstance(item, Message):
                author = item.author
                
                # Check if the messenger is a moderator of r/buildapc
                if not author.is_suspended and author.is_mod and self.subreddit_name in author.moderated():
                    subject = item.subject
                    
                    # Did they tell me to stop?
                    if 'stop' in subject.lower():
                        reason = item.body
                        should_stop = True
                        item.mark_read()
                        
        return should_stop, reason
示例#18
0
def _get_all_rows(ip,table):
    with DatabaseHandler(table) as db:
        return db.read(ip)
class QueryBuilder(Exception):
    def __init__(self):
        """ Initialize """
        self.databasehandler = DatabaseHandler()
        self.helper = Helper()
        print("Hello there..! Query about your system files..")

    def builder(self, user_query):
        """ Build db query parsing user's query """
        file_tense = self.find_tense(user_query)  # Return +1/-1
        timestamp, timestamp_query = self.find_time_query(
            user_query)  # Return date & [day/month/year]
        file_mode = self.find_file_mode(
            user_query)  # Return [create/modify/delete]=[0,4,9]
        result = self.build_query(file_tense, timestamp, timestamp_query,
                                  file_mode)
        if result:
            for doc in result:
                print(doc["name"])
        else:
            print("Sorry, I don't found any related files")

    def build_query(self, file_tense, timestamp, timestamp_query, file_mode):
        """ Build mongodb query """
        if file_tense < 0:
            timestamp -= 1

        if file_mode == 0:
            # db.meta.aggregate({$project:{name:1,month:{$month:'$create'}}},{$match:{month:11}})
            return self.databasehandler.execute_query(timestamp_query,
                                                      "$" + timestamp_query,
                                                      "$create", timestamp)
        elif file_mode == 4:
            return self.databasehandler.execute_query(timestamp_query,
                                                      "$" + timestamp_query,
                                                      "$modify", timestamp)
        elif file_mode == 9:
            return self.databasehandler.execute_query(timestamp_query,
                                                      "$" + timestamp_query,
                                                      "$delete", timestamp)

    def find_time_query(self, user_query):
        """ Return time"""
        if "day" in user_query:
            return self.helper.get_present_day(), "dayOfMonth"
        elif "month" in user_query:
            return self.helper.get_present_month(), "month"
        elif "year" in user_query:
            return self.helper.get_present_year(), "year"
        else:
            raise Exception("Specify search date operator i.e day,month,year")

    def find_tense(self, user_query):
        """ Find the tense of user query """
        past_tense_literals = ["last", "previous", "ago"]
        present_tense_literals = ["this", "present", "today"]
        if any(literal in user_query for literal in past_tense_literals):
            return -1
        elif any(literal in user_query for literal in present_tense_literals):
            return 1
        else:
            raise Exception("Specify tense i.e previous,today etc.")

    def find_file_mode(self, user_query):
        """ Return file search mode """
        if "create" in user_query:
            return 0
        elif "modif" in user_query:
            return 4
        elif "delete" in user_query:
            return 9
        else:
            raise Exception("Specify file mode i.e create,modify,delete")
 def __init__(self):
     """ Initialize """
     self.databasehandler = DatabaseHandler()
     self.helper = Helper()
     print("Hello there..! Query about your system files..")
示例#21
0
class EventScheduler():
    """EventScheduler"""

    current_location = None

    def __init__(self):
        rospy.sleep(
            2
        )  # Delay startup so navigation is finished setting up database file
        self.current_location = None
        self.SCHEDULER_RATE = rospy.Rate(0.05)  #(Hz)
        self.LOW_POWER_THRESHOLD = 20
        self.HOMEDIR = os.path.expanduser("~")
        self.PATH = self.HOMEDIR + "/navigation.db"
        self.MAP_NAME = "glassgarden.map"
        self.current_state = "idle"

        self.publisher_event = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.subscriber_current_location = rospy.Subscriber(
            "cyborg_navigation/current_location", String,
            self.callback_current_location)
        self.subscriber_state = rospy.Subscriber(
            "/cyborg_controller/state_change",
            SystemState,
            self.callback_subscriber_state,
            queue_size=100)
        self.subscriber_battery_status = rospy.Subscriber(
            "/rosarnl_node/battery_status",
            BatteryStatus,
            callback=self.callback_battery_status,
            queue_size=10)

        self.database_handler = DatabaseHandler(filename=self.PATH)
        self.scheduler_thread = threading.Thread(target=self.scheduler)
        self.scheduler_thread.daemon = True  # Thread terminates when main thread terminates
        self.scheduler_thread.start()

    def callback_current_location(self, data):
        if self.current_location != data.data and data.data != "":
            self.current_location = data.data

# Thread, updating current location name based on current position, checks for ongoing events and current position compared to the event, if ongoing event is an other location it publish a navigation_schedulaer event for the state machine

    def scheduler(self):  # Threaded
        rospy.loginfo("EventScheduler: Activated.")
        while not rospy.is_shutdown():
            event = self.database_handler.search_ongoing_events(
                robot_map_name=self.MAP_NAME,
                current_date=datetime.datetime.now())
            if event != None:
                if event.location_name != self.current_location:
                    self.publisher_event.publish("navigation_schedular")
            self.SCHEDULER_RATE.sleep()

    # Updates the current system state when the system state subscriber receives data
    def callback_subscriber_state(self, data):
        if data.to_system_state != None:
            self.current_state = data.to_system_state

    # Monitor battery percentage and publish power_low event when triggered
    def callback_battery_status(self, BatteryStatus):
        # charge_percent [0,100]
        # charge_state [-1, 4], charging_unknown, charging_bulk, charging_overcharge, charging_float, charging_balance
        if (BatteryStatus.charge_percent < self.LOW_POWER_THRESHOLD) and (
                self.current_state not in ["exhausted", "sleepy", "sleeping"]):
            self.publisher_event.publish("power_low")
示例#22
0
                continue
            task: bool = False
            # determine whether the sample contains a task
            if bisect.bisect_left(all_interactions, output_messages[i]) != bisect.bisect_left(all_interactions, output_messages[i] + sample_duration):
                matches_task += 1
            else:
                matches_notask += 1
    #print("\nReturning matches_task = {} and matches_notask = {} for sample {}".format(matches_task, matches_notask, sample))
    return matches_task, matches_notask


# split systems, from crdt/stats.py
if len(sys.argv) < 2:
    print("Usage: ned.py <database>")
    sys.exit(255)
dbh: DatabaseHandler = DatabaseHandler(sys.argv[-1])
systems: List[System] = list(dbh.systems())

sys2 = systems[1]
sys21 = System(sys2._dbh, "2.1", "System 2.1")
setattr(sys21, "messages", functools.partial(sys2.messages, to_timestamp=1352588400))
setattr(sys21, "timespan", functools.partial(sys2.timespan, override_to=1352588400))
sys22 = System(sys2._dbh, "2.2", "System 2.2")
setattr(sys22, "messages", functools.partial(sys2.messages, from_timestamp=1352588400))
setattr(sys22, "timespan", functools.partial(sys2.timespan, override_from=1352588400))
systems[1:2] = [sys21, sys22]

# print LaTeX table header
output_file_suffix: str = ""
if len(sys.argv) > 2:
    output_file_suffix = "-" + sys.argv[1]
示例#23
0
class MyTestCase(unittest.TestCase):
    @classmethod
    def setUpClass(self):
        self.db = DatabaseHandler(debug=True)
        self.db.connect()
        self.db.create_table()

    @classmethod
    def tearDownClass(self):
        self.db.clear_table()
        self.db.disconnect()

    def test_database_insert_read(self):
        reply_id = 123
        posted_time = 1610990729
        submission_id = 456
        submission_flair = None
        submission_url = "http://testing.com/sub/123"
        submission_time = 1610990729
        list_url = "http://listing.com/list/123"
        had_identifiable = True
        bad_markdown = False
        bad_html = 2
        missing_table = True
        tables_made = 2

        self.db.insert_reply(reply_id, posted_time, submission_id,
                             submission_flair, submission_url, submission_time,
                             list_url, had_identifiable, bad_markdown,
                             bad_html, missing_table, tables_made)

        reply = self.db.select_reply(456)

        self.assertIsNotNone(reply)
示例#24
0
 def setUpClass(self):
     self.db = DatabaseHandler(debug=True)
     self.db.connect()
     self.db.create_table()
示例#25
0
class Motivator():
    """Motivator for the controller.

	Generate events based on reward/cost functions.

	Usage:
		motivator = Motivator()
		motivator.start()

	Add more events (possible actions):
		Add more events to the sqlitedatabase.
	"""

    current_pleasure = 0
    current_arousal = 0
    current_dominance = 0
    current_emotion = "neutral"
    current_state = "idle"

    state_timer = 0  # When arrived in the current system state
    max_time = 60  # Used for calculating cost

    # Priority functions
    priority_pleasure = 0.6
    priority_arousal = 0.6
    priority_dominance = 0.6
    priority_cost = 0.7

    #counter_reduced_social_cost = 0

    def __init__(self, database_file=""):
        self.event_publisher = rospy.Publisher(rospy.get_name() +
                                               "/register_event",
                                               String,
                                               queue_size=100)
        self.emotion_publisher = rospy.Publisher(rospy.get_name() +
                                                 "/emotional_feedback",
                                                 EmotionalFeedback,
                                                 queue_size=100)
        self.emotion_subscriber = rospy.Subscriber(rospy.get_name() +
                                                   "/emotional_state",
                                                   EmotionalState,
                                                   self.emotion_callback,
                                                   queue_size=100)
        self.state_subscriber = rospy.Subscriber(rospy.get_name() +
                                                 "/state_change",
                                                 SystemState,
                                                 self.state_callback,
                                                 queue_size=100)
        self.rate = rospy.Rate(.5)  # (hz), looping speed
        self.database_handler = DatabaseHandler(filename=database_file)
        self.database_handler.reset_event_values()

    # Starts the motivator in a seperate daemon thread
    def start(self):
        motivator_thread = threading.Thread(target=self.run)
        motivator_thread.daemon = True
        motivator_thread.start()

    # The running thread called when Motivator starts
    def run(self):  # Threaded
        rospy.loginfo("Motivator: Activated...")
        timer_sc = time.time()
        while not rospy.is_shutdown():
            event = self.find_event()
            if event != None:
                self.send_emotion(pleasure=event.reward_pleasure,
                                  arousal=event.reward_arousal,
                                  dominance=event.reward_dominance)
                event_value = event.event_value + event.event_cost if event.event_value + event.event_cost >= 0 else 0
                event_value = event_value if event_value <= 1 else 1
                self.database_handler.update_event_value(
                    event_id=event.event_id, event_value=event_value)
                self.database_handler.update_all_event_values(
                    delta_event_value=-0.05)
                self.event_publisher.publish(event.event)
                rospy.logdebug("Motivator: Current state is " +
                               self.current_state + " and the event " +
                               event.event + " was generated...")
            self.rate.sleep()

            if self.current_state == "idle" and time.time(
            ) - self.state_timer > 3 * 60:
                self.database_handler.reset_event_values()

            if time.time() - timer_sc > 10:
                timer_sc = time.time()
                self.database_handler.update_all_event_values(
                    delta_event_value=-0.01)

    # Finds and returns the event to generate (or None if None to generate)
    def find_event(self):
        events = self.database_handler.get_all_events(state=self.current_state)
        reward = 0
        solution = None

        # A cost or minimum reward. Decreses with time spendt in current state.
        time_in_state = time.time() - self.state_timer
        k_s = 1 - (time_in_state * 5 / self.max_time)**math.tan(
            (self.priority_cost * math.pi) / 2.0)
        c_s = k_s * 1
        reward = c_s
        reward = reward if reward > 0 else 0.003

        # Find best reward grater then cost
        for event in events:
            p_p = 1 - self.current_pleasure**3
            r_p = p_p * ((self.current_pleasure + (
                (event.reward_pleasure) / 2.0)) - self.current_pleasure)

            p_a = 1 - self.current_arousal**3
            r_a = p_a * ((self.current_arousal + (
                (event.reward_arousal) / 2.0)) - self.current_arousal)

            p_d = 1 - self.current_dominance**3
            r_d = p_d * ((self.current_dominance + (
                (event.reward_dominance) / 2.0)) - self.current_dominance)

            p_e = event.event_value**(1.0 / 3.0)
            c_e = p_e * ((event.reward_pleasure / 2.0) +
                         (event.reward_arousal / 2.0) +
                         (event.reward_dominance / 2.0))

            r = r_p + r_a + r_d - c_e
            print(event.event, r + c_e, -c_e, r)
            solution = event if r > reward else solution
            reward = r if r > reward else reward
        return solution

    # Send the change (delta) in the emotional state to the emotion system
    def send_emotion(self, pleasure, arousal, dominance):
        msg = EmotionalFeedback()
        msg.delta_pleasure = pleasure
        msg.delta_arousal = arousal
        msg.delta_dominance = dominance
        self.emotion_publisher.publish(msg)

    # Updates the current emotion when the emotion subscriber recives data
    # Normalizes the data.
    def emotion_callback(self, data):
        self.current_emotion = data.to_emotional_state
        self.current_pleasure = (data.current_pleasure + 1) / 2.0
        self.current_arousal = (data.current_arousal + 1) / 2.0
        self.current_dominance = (data.current_dominance + 1) / 2.0

    # Updates the current system state when the system state subscriber recieves data
    def state_callback(self, data):
        self.current_state = data.to_system_state
        self.state_timer = time.time()
示例#26
0
def main():

    homedir = os.path.expanduser("~")
    path = homedir + "/navigation.db"

    if (os.path.exists(path) == False):
        database_handler = DatabaseHandler(filename=path)
        database_handler.create()
        database_handler.add_location(location_name="entrance", robot_map_name="ntnu2.map", x=-18.440, y=6.500, z=0, p=0, j=0, r=2, threshold=3, crowded=False,enviorment=-0.10)
        database_handler.add_location(location_name="home", robot_map_name="ntnu2.map", x=-29.500, y=8.700, z=0, p=0, j=0, r=2, threshold=3, crowded=False, enviorment=0.20)
        database_handler.add_location(location_name="waiting area", robot_map_name="ntnu2.map", x=-33.600, y=10.600, z=0, p=0, j=0, r=2, threshold=3, crowded=False, enviorment=-0.10)
        database_handler.add_location(location_name="cafeteria", robot_map_name="ntnu2.map", x=-33.090, y=-55.700, z=0, p=0, j=0, r=2, threshold=3, crowded=True, enviorment=0.20)
        database_handler.add_location(location_name="elevator", robot_map_name="ntnu2.map", x=-29.500, y=-50.200, z=0, p=0, j=0, r=2, threshold=3, crowded=True, enviorment=-0.02)
        database_handler.add_location(location_name="entrance 2", robot_map_name="ntnu2.map", x=-18.300, y=-66.000, z=0, p=0, j=0, r=33, threshold=3, crowded=True, enviorment=0.05)
        database_handler.add_location(location_name="information", robot_map_name="ntnu2.map", x=-33.490, y=1.160, z=0, p=0, j=0, r=2, threshold=3, crowded=True, enviorment=0.05)
        database_handler.add_location(location_name="el5", robot_map_name="ntnu2.map", x=-33.720, y=-32.500, z=0, p=0, j=0, r=-2, threshold=3, crowded=True, enviorment=0.00)
        database_handler.add_location(location_name="el6", robot_map_name="ntnu2.map", x=-30.300, y=-12.840, z=0, p=0, j=0, r=2, threshold=3, crowded=True, enviorment=0.00)
        database_handler.add_location(location_name="bridge", robot_map_name="ntnu2.map", x=-28.090, y=-63.500, z=0, p=0, j=0, r=2, threshold=3, crowded=True, enviorment=0.00)
        
        database_handler.add_event(event_name="welcome_time", location_name="entrance", start_date=datetime.datetime(2017, 1, 18, 11, 0, 0, 1), end_date=datetime.datetime(2017, 1, 18, 11, 4, 0, 1), ignore=False)
        database_handler.add_event(event_name="dinner_time", location_name="cafeteria", start_date=datetime.datetime(2017, 1, 18, 15, 0, 7, 1) , end_date=datetime.datetime(2017, 1, 18, 15, 59, 0, 1), ignore=False)
        database_handler.add_event(event_name="wait_time", location_name="waiting area", start_date=datetime.datetime(2017, 1, 18, 8, 0, 1, 1) , end_date=datetime.datetime(2017, 1, 18, 8, 46, 0, 1), ignore=False)
        database_handler.add_event(event_name="lunch_time", location_name="cafeteria", start_date=datetime.datetime(2017, 1, 18, 7, 0, 1, 1) , end_date=datetime.datetime(2017, 1, 18, 7, 0, 0, 1), ignore=False)
        database_handler.add_event(event_name="goodbye_time", location_name="entrance 2", start_date=datetime.datetime(2017, 1, 18, 9, 0, 1, 1), end_date=datetime.datetime(2017, 1, 18, 9, 0, 0, 1), ignore=False)
        
        database_handler.add_response( message="I love LOCATION", response_type="navigation_response", emotion="love")
        database_handler.add_response( message="I am happy about LOCATION", response_type="navigation_response", emotion="elated")
        database_handler.add_response( message="I like LOCATION", response_type="navigation_response", emotion="elated")
        database_handler.add_response( message="I like LOCATION", response_type="navigation_response", emotion="dignified")
        database_handler.add_response( message="I am happy about at LOCATION", response_type="navigation_response", emotion="neutral")
        database_handler.add_response( message="I like LOCATION", response_type="navigation_response", emotion="neutral")
        database_handler.add_response( message="What is this place? A LOCATION you say?", response_type="navigation_response", emotion="curious")
        database_handler.add_response( message="What is this place? A LOCATION you say?", response_type="navigation_response", emotion="puzzled")
        database_handler.add_response( message="I hate the LOCATION", response_type="navigation_response", emotion="angry")
        database_handler.add_response( message="I dont like the LOCATION", response_type="navigation_response", emotion="angry")
        database_handler.add_response( message="A the LOCATION, whatever. Been there, done that...", response_type="navigation_response", emotion="unconcerned")
        database_handler.add_response( message="A the LOCATION, whatever. Been there, done that...", response_type="navigation_response", emotion="angry")
        database_handler.add_response( message="A the LOCATION, whatever. Been there, done that...", response_type="navigation_response", emotion="inhibited")
        
    rospy.init_node("cyborg_navigation")
    navigation_server = NavigationServer(database_file=path)
    rospy.spin()
示例#27
0
class NavigationServer():
    """NavigationServer"""

    client_base_feedback = StateMachineFeedback()
    client_base_result = StateMachineResult()
    next_location = None
    command_location = None
    current_location = None
    reason = ""

    map_name = "ntnu2.map"
    base_canceled = False
    base_succeded = False

    current_x = 0.0
    current_y = 0.0
    current_emotion = "neutral"

    planing_timeout = 60  # (s)
    moving_timeout = 1000  # (s)
    taking_timeout = 60  # (s)

    def __init__(self, database_file=""):
        self.scheduler_rate = rospy.Rate(1)  # (hz)
        self.server_rate = rospy.Rate(0.5)  # (hz)

        self.server_planing = actionlib.SimpleActionServer(
            rospy.get_name() + "/planing",
            StateMachineAction,
            execute_cb=self.server_planing_callback,
            auto_start=False)
        self.server_moving = actionlib.SimpleActionServer(
            rospy.get_name() + "/moving",
            StateMachineAction,
            execute_cb=self.server_moving_callback,
            auto_start=False)
        self.server_talking = actionlib.SimpleActionServer(
            rospy.get_name() + "/talking",
            StateMachineAction,
            execute_cb=self.server_talking_callback,
            auto_start=False)
        self.server_go_to = actionlib.SimpleActionServer(
            rospy.get_name() + "/go_to",
            NavigationGoToAction,
            execute_cb=self.server_go_to_callback,
            auto_start=False)
        self.server_planing.start()
        self.server_moving.start()
        self.server_talking.start()
        self.server_go_to.start()
        self.client_base = actionlib.SimpleActionClient(
            "/rosarnl_node/move_base", MoveBaseAction)
        self.emotion_publisher = rospy.Publisher(
            "/cyborg_controller/emotional_feedback",
            EmotionalFeedback,
            queue_size=100)
        self.event_publisher = rospy.Publisher(
            "/cyborg_controller/register_event", String, queue_size=100)
        self.speech_publisher = rospy.Publisher(
            "/cyborg_text_to_speech/text_to_speech", String, queue_size=100)
        self.database_handler = DatabaseHandler(filename=database_file)
        self.location_subscriber = rospy.Subscriber("/rosarnl_node/amcl_pose",
                                                    PoseWithCovarianceStamped,
                                                    self.location_callback)
        self.emotion_subscriber = rospy.Subscriber(
            "/cyborg_controller/emotional_state",
            EmotionalState,
            self.emotion_callback,
            queue_size=100)
        self.text_subscriber = rospy.Subscriber("/text_from_speech",
                                                String,
                                                self.text_callback,
                                                queue_size=100)
        self.scheduler_thread = threading.Thread(target=self.scheduler)
        self.scheduler_thread.daemon = True  # Thread terminates when main thread terminates
        self.scheduler_thread.start()
        rospy.loginfo("NavigationServer: Activated.")

    # Updates the current position when the position subscriber receives data
    def location_callback(self, data):
        self.current_x = data.pose.pose.position.x
        self.current_y = data.pose.pose.position.y

    # Updates the current emotion when the emotion subscriber recives data from the controller (emotion system)
    def emotion_callback(self, data):
        self.current_emotion = data.to_emotional_state

    # Thread, updating current location name based on current possition, checks for ongoing events and current position compared to the event, if ongoing event is an other location it publish a navigation_schedulaer event for the state machine
    def scheduler(self):  # Threaded
        while (not rospy.is_shutdown()):
            self.current_location = self.database_handler.find_location(
                robot_map_name=self.map_name,
                location_x=self.current_x,
                location_y=self.current_y)
            current_location_name = self.current_location.location_name if self.current_location != None else ""
            event = self.database_handler.search_ongoing_events(
                robot_map_name=self.map_name,
                current_date=datetime.datetime.now())
            if event != None:
                if event.location_name != current_location_name:
                    self.event_publisher.publish("navigation_schedualer")
            self.scheduler_rate.sleep()

    # Called once when the robot base (ROSARNL) goal completes
    def client_base_done_callback(self, state, result):
        if self.is_controlling_base:
            if (state == 3):  # Succeded aka arived at location
                self.base_succeded = True
            elif (state == 2):  # Happens when we cancel goals aka preemted
                self.base_canceled = True
            elif (state == 1):  # Canceled?
                self.base_canceled = True
            self.client_base_state = state
            self.client_base_result = result
            rospy.logdebug(
                "NavigationServer: Base has completed its execution with " +
                str(state) + " and result " + str(result) + ".")

    # Called once when the robot base (ROSARNL) goal becomes active
    def client_base_active_callback(self):
        rospy.logdebug("NavigationServer: Base goal has gone active.")
        self.is_controlling_base = True

    # Called every time feedback is received for the goal for the robot base (ROSARNL)
    def client_base_feedback_callback(self, feedback):
        rospy.logdebug("NavigationServer: Received feedback from base - " +
                       str(feedback) + ".")
        self.client_base_feedback = feedback

    # Called when the controller (state machine) sets the navigation_planing state as active
    def server_planing_callback(self, goal):
        rospy.logdebug("NavigationServer: Executing planing state.")
        time.sleep(2)  # Let roscore update connections

        # Select what to do based on event
        self.next_location = None
        if goal.event == "navigation_schedualer":
            if self.current_emotion == "angry":
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.map_name, crowded=False)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving")
            else:
                self.next_location = self.database_handler.search_ongoing_events(
                    robot_map_name=self.map_name,
                    current_date=datetime.datetime.now())
                self.send_emotion(pleasure=0, arousal=0, dominance=-0.1)
                self.change_state(event="navigation_start_moving")

        elif goal.event == "navigation_emotional":
            if self.current_emotion in ["angry", "sad", "fear", "inhibited"]:
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.map_name, crowded=False)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving")
            elif self.current_emotion in [
                    "happy", "loved", "dignified", "neutral", "elated"
            ]:
                self.next_location = self.database_handler.search_for_crowded_locations(
                    robot_map_name=self.map_name, crowded=True)
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_moving")
            elif self.current_emotion in ["bored", "curious", "unconcerned"]:
                self.next_location = "wandering"
                self.send_emotion(pleasure=0, arousal=0, dominance=0.1)
                self.change_state(event="navigation_start_wandering")

        elif goal.event == "navigation_command":
            self.next_location = self.command_location
            self.send_emotion(pleasure=0, arousal=0, dominance=-0.2)
            self.change_state(event="navigation_start_moving")

    # Publishes an event and waits for a change of state.
    def change_state(self, event=None):
        if event != None and self.next_location != None:
            self.event_publisher.publish(event)
        else:
            self.server_planing.set_aborted()
            return

        # Wait until state is preemted, or abort if it takes to long time
        started_waiting = time.time()  # Prevent eternal looping
        while not rospy.is_shutdown():
            if self.server_planing.is_preempt_requested():
                self.server_planing.set_preempted()
                return
            elif (time.time() - started_waiting >
                  self.planing_timeout):  # Prevent eternal looping
                self.server_planing.set_aborted()
                return
            self.server_rate.sleep()

    # Called when the controller (state machine) sets the navigation_moving state as active
    def server_moving_callback(self, goal):
        rospy.logdebug("NavigationServer: Executing moving state." +
                       " Navigation movinging cmd " + str(self.next_location))
        self.goal = goal
        self.base_canceled = False
        self.base_succeded = False
        self.is_controlling_base = False

        # Select how to move based on event
        if goal.event == "navigation_start_wandering":
            self.start_wandering()
        elif goal.event == "navigation_start_moving" and self.next_location != None:
            self.start_moving()
        else:
            self.server_moving.set_aborted()
            rospy.logdebug(
                "NavigationServer: Received event that cant be handled - " +
                str(goal.event) + ".")

    # The robot base starts to wander and keeps wandering until it is preemted or no longer in the right mood
    def start_wandering(self):
        # Tell base to start wandering
        rospy.logdebug("NavigationServer: Waiting for base wandering service.")
        rospy.wait_for_service("/rosarnl_node/wander")
        rospy.logdebug("NavigationServer: wandering service available.")
        try:
            baseStartWandering = rospy.ServiceProxy("/rosarnl_node/wander",
                                                    Empty)
            baseStartWandering()
        except rospy.ServiceException, e:
            rospy.logdebug("NavigationServer: wandering service error - " +
                           str(e))

        started_waiting = time.time()  # Prevent eternal looping
        feedback_cycle = time.time()
        while not rospy.is_shutdown():
            if self.server_moving.is_preempt_requested():
                self.client_base.cancel_all_goals(
                )  # HERE - goal on wandering?
                try:
                    baseStop = rospy.ServiceProxy("/rosarnl_node/stop", Empty)
                    baseStop()
                except rospy.ServiceException, e:
                    rospy.logdebug("NavigationServer: stop service error - " +
                                   str(e))
                self.server_moving.set_preempted()
                return
            if self.current_emotion not in ["bored", "curious", "unconcerned"]:
                self.client_base.cancel_all_goals(
                )  # HERE - goal on wandering?
                try:
                    baseStop = rospy.ServiceProxy("/rosarnl_node/stop", Empty)
                    baseStop()
                except rospy.ServiceException, e:
                    rospy.logdebug("NavigationServer: stop service error - " +
                                   str(e))
                self.event_publisher.publish("navigation_wandering_completed")

                # Wait until state is preemted
                started_waiting = time.time()  # Prevent eternal looping
                while not rospy.is_shutdown():
                    if self.server_moving.is_preempt_requested():
                        self.server_moving.set_preempted()
                        return
                    self.server_rate.sleep()
                return
示例#28
0
 def __init__(self):
     self.datahandler = DatabaseHandler()
     print "instance created"
            formated_requests_clean = formated_requests

        with DatabaseHandler(table_name) as db:
            db.create_table(table_name)
            for req in formated_requests_clean:
                db.store(req)
        with DatabaseHandler(table_name) as db:
            l = db.cursor.execute(
                "SELECT * FROM {}".format(table_name)).fetchall()
            ips_in_table = []
            for val in l:
                ips_in_table.append(val[1])
        return list(set(ips_in_table))
    except Exception as e:
        raise e


def get_unique_ips(table_name):
    with DatabaseHandler(table_name) as db:
        l = db.cursor.execute("SELECT * FROM {}".format(table_name)).fetchall()
        ips_in_table = []
        for val in l:
            ips_in_table.append(val[1])
    return list(set(ips_in_table))


if __name__ == "__main__":
    ips = parse_requests('humans')
    db = DatabaseHandler("humans")
    db.print_table()