def game_state_callback(self, data):
        _game = data.game
        # if _game == self._which_game:
        _state = data.state
        rospy.loginfo('current game state = ' +
                      self.game_state2str_dict[_state])
        if _state == GameState.READY:
            self._game_is_ready_to_begin = True
            rospy.loginfo("received signal: game is ready to begin")
        elif _state == GameState.END:
            _performance = data.performance
            # TODO: where do we log user perfomance??
            rospy.loginfo('user performance ' + _performance)
            # force to kill the running application
            self.force_to_end_current_game()

            if self._send_signals_to_server:
                _msg = self.game_id2str_dict[_game] + " is ended"
                pack = Packet(_msg, self._default_notification_level,
                              self._robot_id)
                pack.add([{"dataset": "message", "numerical": "1"}]).send()

            # save to temp log
            self.save_temp_log(check_point=self._n_game_played)
            # reset game related parameters
            self.reset_gaming_parameter()
            self.state = session_manager.STATE_GAME_SELECTION
        elif _state == GameState.USER_TIMEOUT:
            self.send_game_command(_game, GameCommand.WAIT_FOR_RESPONSE)
    def __init__(self):
        rospy.init_node('robot_proxy', anonymous=True)
        self._send_signals_to_server = rospy.get_param(
            '/sar/global/_send_signals_to_server')
        self._robot_id = rospy.get_param('/sar/global/_robot_id')
        self._default_notification_level = rospy.get_param(
            '/sar/global/_default_notification_level')

        self.lock_robot_attention_target = threading.Lock()
        self.estimated_robot_attention_target = None
        self.previous_robot_attention_target = None
        self._f_system_down = False

        rospy.Subscriber("/sar/jibo/health", JiboHealth,
                         self.jibo_health_callback)
        rospy.Subscriber('/sar/jibo/verbose_state', String,
                         self.jibo_verbose_state_callback)

        rospy.Subscriber("/sar/system/state", SystemState,
                         self.system_state_callback)

        # estimate robot attention
        self.robot_attention_target_pub = rospy.Publisher(
            '/sar/jibo/robot_attention_target', String, queue_size=10)

        if self._send_signals_to_server:
            pack = Packet("Good Morning", self._default_notification_level,
                          self._robot_id)
            pack.add([{"dataset": "message", "numerical": "1"}]).send()
    def run(self):
        rate = rospy.Rate(10)  # 30hz, is this too often?
        while not rospy.is_shutdown():
            if self._f_system_down:
                break

            with self.lock_robot_attention_target:
                if self.estimated_robot_attention_target != None:
                    self.robot_attention_target_pub.publish(
                        self.estimated_robot_attention_target)
            rate.sleep()
        if self._send_signals_to_server:
            pack = Packet("Good Night", self._default_notification_level,
                          self._robot_id)
            pack.add([{"dataset": "message", "numerical": "1"}]).send()
    def jibo_health_callback(self, data):
        _cpu_temp = data.cpu_temperature
        _battery_temp = data.battery_temperature
        _main_board_temp = data.main_board_temperature

        # rospy.loginfo(_cpu_temp)

        _alert_cpu_temp = 75.0  # alert the admin when the cpu temp is higher than 75

        if _cpu_temp >= _alert_cpu_temp:  # TODO: auto shutdown when it is over 95
            if self._send_signals_to_server:
                pack = Packet(
                    "Alert! Robot Over Temperature: " + str(_cpu_temp), 2,
                    self._robot_id)
                pack.add([{
                    "dataset": "message",
                    "numerical": str(_cpu_temp)
                }]).send()
            rospy.logwarn("Alert! Robot Over Temperature: " + str(_cpu_temp))

        if self._send_signals_to_server:
            pack = Packet("Robot Health Information",
                          self._default_notification_level, self._robot_id)
            pack.add([{
                "dataset": "cpu_temperature",
                "numerical": _cpu_temp
            }, {
                "dataset": "battery_temperature",
                "numerical": _battery_temp
            }, {
                "dataset": "main_board_temperature",
                "numerical": _main_board_temp
            }]).send()

        rospy.loginfo("robot cpu_temperature: " + str(_cpu_temp))
        rospy.loginfo("robot battery_temperature: " + str(_battery_temp))
        rospy.loginfo("robot main_board_temperature: " + str(_main_board_temp))
    def jibo_health_callback(self, data):
        _cpu_temp = data.cpu_temperature
        _battery_temp = data.battery_temperature
        _main_board_temp = data.main_board_temperature

        rospy.loginfo(_cpu_temp)

        _alert_cpu_temp = 75.0 #Change this

        if _cpu_temp >= _alert_cpu_temp: # auto shutdown when it is over 95
            if self._send_signals_to_server:
                pack = Packet("Robot Over Alert Temperature: " + str(_cpu_temp), 2)
                pack.add([{"dataset" : "message", "numerical" : 0}]).send()
            rospy.logwarn("Robot Over Alert Temperature: " + str(_cpu_temp))

        if self._send_signals_to_server:
            pack = Packet("Health Information", 0)
            pack.add([{"dataset":"cpu_temperature","numerical": _cpu_temp },
                {"dataset":"battery_temperature", "numerical":_battery_temp},
                {"dataset":"main_board_temperature", "numerical":_main_board_temp
                }]).send()
        rospy.loginfo("robot cpu_temperature: " + str(_cpu_temp))
        rospy.loginfo("robot battery_temperature: " + str(_battery_temp))
        rospy.loginfo("robot main_board_temperature: " + str(_main_board_temp))
#!/usr/bin/env python

from server_communication import Packet
from server_communication import Communication
import sys
import time
#/etc/network/if-up.d/startupSAR
import xml.etree.ElementTree

if __name__ == "__main__":
    e = xml.etree.ElementTree.parse(
        '/home/sar/catkin_ws/src/sar_core/launch/sar_core.launch').getroot()
    for aparam in e.findall('param'):
        if (aparam.get('name') == '/sar/global/_robot_id'):
            _robot_id = aparam.get('value')
        if (aparam.get('name') == '/sar/global/_default_notification_level'):
            _level = aparam.get('value')
    if (sys.argv[1] == "up"):
        pack = Packet("System Online", _level, _robot_id)
        pack.add([{
            "dataset": "message",
            "numerical": int(time.time())
        }]).send()
    elif (sys.argv[1] == "down"):
        pack = Packet("System Offline", _level, _robot_id)
        pack.add([{
            "dataset": "message",
            "numerical": int(time.time())
        }]).send()
    def run(self):
        #INIT
        pack = Packet("Good Morning")
        pack.add([{"dataset": "message", "numerical": "Good Morning"}]).send()

        time.sleep(3)
        self.robot_state_publ.publish(self.state)
        self.state.is_playing_sound = False
        self.state.doing_action = False

        data = {}
        data['to'] = VSCommand.VS
        data['from'] = VSCommand.ROBOT
        data['action'] = VSCommand.ACTION_START
        data['day'] = "0"
        self.vs_action_publ.publish(json.dumps(data))

        _address = 'file:///home/waco001/catkin_ws/src/sar_core/resources/visual_schedule/index.html'
        #self.run_javascript_application(_address)

        while not rospy.is_shutdown():
            #MAIN LOOP
            current = time.time()
            if (current % .25 == 0):
                self.robot_state_publ.publish(self.state)

            if (current % 300 == 0):
                pack = Packet("Data Dump")
                pack.add([{
                    "dataset": "cpu_temp",
                    "numerical": str(48 + (random.random() * 7.5))
                }]).send()
        #SHUTDOWN
        pack = Packet("Good Night")
        pack.add([{"dataset": "message", "numerical": "Good Night!"}]).send()
        return
    def run(self):
        self.lets_wait(0.5)
        while not rospy.is_shutdown():

            if (self.state != session_manager.STATE_EXIT) and (
                    self.state != session_manager.STATE_GAME_SELECTION
            ) and (self.state != session_manager.STATE_WAIT):  #for testing
                rospy.loginfo(bcolors.HEADER + 'we are at the state of [' +
                              self.state + ']' + bcolors.ENDC)

            if self.state == session_manager.STATE_INIT:
                self.send_system_state_msg(SystemState.SYSTEM_UP)
                self._system_up_time = time.strftime("%c")

                session_data = self.load_session_data()

                self.state = session_manager.STATE_DAILY_OPENING
                continue

            elif self.state == session_manager.STATE_DAILY_OPENING:
                rospy.loginfo("trying to run visual schedule")
                _p_js_app = self.run_javascript_application(
                    self.visual_schedule_filepath, js_game=False)

                if self._f_clean_start:
                    # select games to play and pass the game ids to vs
                    self._todays_games = self.pick_todays_games()
                else:
                    self._todays_games = self._previous_games

                rospy.loginfo('today we are going to play [%s], [%s], [%s]',
                              self.game_id2str_dict[self._todays_games[0]],
                              self.game_id2str_dict[self._todays_games[1]],
                              self.game_id2str_dict[self._todays_games[2]])
                # rospy.loginfo('today we are going to play [%d], [%d], [%d]',
                #     self._todays_games[0], self._todays_games[1], self._todays_games[2])

                # ensuring visual schedule js is ready
                self.lets_wait(3)

                JSdata = {}
                JSdata['to'] = VSMessage.VS
                #session manager is considered as robot when communicating with vs
                JSdata['from'] = VSMessage.ROBOT
                if self._f_clean_start:
                    JSdata['content'] = VSMessage.ACTION_START
                else:
                    JSdata['content'] = VSMessage.ACTION_RELOAD_SESSION_START
                    JSdata['game1_status'] = self._previous_games_status[0]
                    JSdata['game2_status'] = self._previous_games_status[1]
                    JSdata['game3_status'] = self._previous_games_status[2]
                JSdata['day'] = self._day
                JSdata['game1'] = self._todays_games[0]
                JSdata['game2'] = self._todays_games[1]
                JSdata['game3'] = self._todays_games[2]
                self.vs_pub.publish(json.dumps(JSdata))

                # set today's games to param server
                rospy.set_param('/sar/global/_today_game1',
                                self._todays_games[0])
                rospy.set_param('/sar/global/_today_game2',
                                self._todays_games[1])
                rospy.set_param('/sar/global/_today_game3',
                                self._todays_games[2])

                self.save_temp_log(check_point=0)

                self.state = session_manager.STATE_WAIT
                continue

            elif self.state == session_manager.STATE_GAME_SELECTION:
                # finished all the game activity for today's session
                if self._n_game_played >= session_manager.NUM_GAME_TO_PLAY:
                    # closing today's session: load the collected piece of the day
                    self.lets_wait(3)
                    self.send_vs_msg(VSMessage.VS, VSMessage.ROBOT,
                                     VSMessage.ACTION_END)

                    # wait for the closing to finish
                    self.state = session_manager.STATE_WAIT
                    continue

                if self._which_game == None:
                    # cmhuang: TODO TODO
                    if (not self._f_has_asked_for_choice) and (
                            self._n_game_played >= 1):
                        _robot_command = self.get_a_scripted_robot_command(
                            'transition_between_games')
                        self.send_multiple_robot_commands(
                            _robot_command)  #blocking
                        self._f_has_asked_for_choice = True
                        # enable menu
                        self.send_vs_msg(VSMessage.JS, VSMessage.ROBOT,
                                         VSMessage.ACTION_SHOW_MENU)
                    continue

                self._game_is_ready_to_begin = False
                # the user chose _which_game to play
                self.play_game(self._which_game)
                self._n_game_played += 1
                self._f_has_asked_for_choice = False

                if self._send_signals_to_server:
                    _msg = self.game_id2str_dict[
                        self._which_game] + " is launched"
                    pack = Packet(_msg, self._default_notification_level,
                                  self._robot_id)
                    pack.add([{"dataset": "message", "numerical": "1"}]).send()

                self.state = session_manager.STATE_WAIT

            elif self.state == session_manager.STATE_PARENT_JOURNAL:
                p_parent_journal = self.run_javascript_application(
                    self.parent_journal_filepath, js_game=False)
                self._f_waiting_for_pj_to_finish = True

                if self._send_signals_to_server:
                    _msg = "pj is launched"
                    pack = Packet(_msg, self._default_notification_level,
                                  self._robot_id)
                    pack.add([{"dataset": "message", "numerical": "1"}]).send()

                self.state = session_manager.STATE_WAIT
                continue

            elif self.state == session_manager.STATE_WAIT:
                self.lets_wait(seconds=0.1)

                # wait for the user to click the start button
                if self._f_user_requested_start == False:
                    continue
                else:
                    if self._f_user_requested_start_once:
                        self.send_vs_msg(VSMessage.JS, VSMessage.ROBOT,
                                         VSMessage.ACTION_LOAD_DEFAULT_BG)
                        self.state = session_manager.STATE_GAME_SELECTION
                        self._f_user_requested_start_once = False

                # after requesting to end the game, wait for the game to complete its ending process
                if self._f_waiting_for_game_to_end:
                    _now = rospy.get_time()
                    _duration_game_play = _now - self._t_game_begin
                    # force the game to exit after a minute
                    if _duration_game_play >= (
                            self._game_duration_limit +
                            session_manager.DURATION_FOR_GAME_EXIT):
                        rospy.loginfo('FORCE to kill game application [' +
                                      session_manager.game_id2str_dict[
                                          self._which_game] + ']')

                        if self._send_signals_to_server:
                            _msg = self.game_id2str_dict[
                                self.
                                _which_game] + " is killed forcefully due to OVERTIME"
                            pack = Packet(_msg,
                                          self._default_notification_level,
                                          self._robot_id)
                            pack.add([{
                                "dataset": "message",
                                "numerical": "1"
                            }]).send()

                        # force to kill the game
                        self.force_to_end_current_game()
                        # save to temp log
                        self.save_temp_log(check_point=self._n_game_played)
                        # reset game related parameters
                        self.reset_gaming_parameter()
                        self.state = session_manager.STATE_GAME_SELECTION
                    else:
                        continue

                if self._f_waiting_for_pj_to_finish:
                    continue

                if self._vs_closed_session:
                    _robot_command = self.get_a_scripted_robot_command(
                        'end_of_daily_session')
                    self.send_multiple_robot_commands(_robot_command)

                    # end of daily intervention session
                    self.send_system_state_msg(SystemState.SESSION_END)
                    self._session_end_time = time.strftime("%c")

                    self.lets_wait(3)
                    JSdata = {}
                    JSdata['to'] = VSMessage.JS
                    JSdata[
                        'from'] = VSMessage.ROBOT  #session is considered as robot when communicating with vs
                    JSdata['content'] = VSMessage.ACTION_LOAD_IMAGE
                    JSdata['screen'] = "survey_time.png"
                    self.vs_pub.publish(json.dumps(JSdata))
                    _robot_command = self.get_a_scripted_robot_command(
                        'before_parent_journal')
                    self.send_multiple_robot_commands(_robot_command)
                    # robot goes to sleep mode
                    self.send_robot_command(RobotCommand.DO,
                                            "<jibo-sleep-mode>")
                    self.lets_wait(1.5)
                    # put robot to sleep
                    self.send_system_state_msg(SystemState.ROBOT_SLEEP)

                    self.state = session_manager.STATE_PARENT_JOURNAL

                if self._is_playing_game == True:
                    if self._p_game == None:  # game finishes from within
                        _robot_command = self.get_a_scripted_robot_command(
                            'user_finished_game')
                        rospy.loginfo('%s is finished before its given time',
                                      self.game_id2str_dict[self._which_game])
                        self.send_multiple_robot_commands(_robot_command)
                        # save to temp log
                        self.save_temp_log(check_point=self._n_game_played)
                        self.reset_gaming_parameter()
                        self.state = session_manager.STATE_GAME_SELECTION
                    else:
                        if self._p_game.returncode == None:  # the process is still alive
                            _now = rospy.get_time()
                            _duration_game_play = _now - self._t_game_begin
                            if _duration_game_play >= self._game_duration_limit:
                                # TODO: end robot behavior if any; how to do this gracefully?
                                _robot_command = self.get_a_scripted_robot_command(
                                    'game_times_up')
                                self.send_multiple_robot_commands(
                                    _robot_command)
                                # TODO: this is not the best way to end a game.
                                self.lets_wait(3)
                                self.send_game_command(self._which_game,
                                                       GameCommand.END)
                                self._f_waiting_for_game_to_end = True
                                rospy.loginfo('requesting game to end')
                                if self._send_signals_to_server:
                                    _msg = self.game_id2str_dict[
                                        self.
                                        _which_game] + " is notified to end"
                                    pack = Packet(
                                        _msg, self._default_notification_level,
                                        self._robot_id)
                                    pack.add([{
                                        "dataset": "message",
                                        "numerical": "1"
                                    }]).send()
                        else:
                            # save to temp log
                            self.save_temp_log(check_point=self._n_game_played)
                            self.reset_gaming_parameter()
                            self.state = session_manager.STATE_GAME_SELECTION

                continue

            elif self.state == session_manager.STATE_EXIT:
                _session_start_time = rospy.get_param(
                    '/sar/global/session_start_time')
                today_session_data = {
                    "day": self._day,
                    "session_start_time": _session_start_time,
                    "session_end_time": self._session_end_time,
                    "system_up_time": self._system_up_time,
                    "system_down_time": time.strftime("%c"),
                    "cumulative_game_play": self.cumulative_game_play_dict
                }
                self.save_session_data(today_session_data)
                self.reset_temp_log()

                # very last: close the background vs-js application
                self.send_vs_msg(VSMessage.JS, VSMessage.ROBOT,
                                 VSMessage.ACTION_CLOSE)

                self.lets_wait(seconds=5)

                # signal all running nodes to shut off
                self.send_system_state_msg(SystemState.SYSTEM_DOWN)
                self.lets_wait(seconds=2)
                break

            self.lets_wait(seconds=0.01)

        # killall -- TODO: change later
        subprocess.Popen("killall roslaunch",
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)