Exemple #1
0
class RobotCommands(object):
    
    def __init__(self):
        self._dao = DataAccess()
    
    exposed = True

    def POST(self, *args, **kwargs):
        
        request = json.loads(cherrypy.request.body.read())
        
        # Send the robot to certain location
        if request.has_key('location'):
            object = self._dao.getLocationByName(request['location']);
            robot = Factory.getCurrentRobot();

            robot.setComponentState('tray', request['tray'])
            robot.setComponentState('base', [object['xCoord'], object['yCoord'], object['orientation']])

        # Send voice command to the robot (espeak software required)        
        elif request.has_key('speech'):

            if self._dao.getUserPreferences()[0]['voice'] == 1:
                import subprocess
                #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
                subprocess.call(['espeak', request['speech']]); #Linux
        else:      
            raise cherrypy.HTTPError(400)      
Exemple #2
0
 def __init__(self):
     super(LocationProcessor, self).__init__()
     self._dao = DataAccess()
     self._storedLoc = lambda: {'locationName': '', 'xCoord': 0, 'yCoord': 0, 'orientation': 0, 'driftThreshold': 0 }
     self._curLoc = lambda: ('', (0, 0, 0))
     self._updateLoc = lambda locid, x, y, orientation: True
     self._targetName = ''
Exemple #3
0
 def __init__(self):
     self._dao = DataAccess()
     self._preferences = self._dao.users.getUserPreferences()
     self._robot = Factory.getCurrentRobot()
     self._threadLights = myThreadLights(1, "Thread-Lights", self._robot)
     self._threadHead = myThreadHead(2, "Thread-Head", self._robot)
     self._threadBase = myThreadBase(3, "Thread-BaseDirect", self._robot)
     self._threadTray = myThreadTray(4, "Thread-Tray", self._robot)
Exemple #4
0
class SensorLog(PollingProcessor):
    """ Handles updating sensors of all types to the database """
    def __init__(self, channels, name=''):
        super(SensorLog, self).__init__()
        self._dao = DataAccess().sensors
        self._channels = channels
        self._logCache = {}
        self._name = name

    def start(self):
        """ Begin asynchronously updating changes in sensors """
        if self._name != '':
            print "Started updating database for %s sensor changes" % (
                self._name)
        else:
            print "Started updating database for [unknown] sensor changes"
        self._addPollingProcessor('sensorHistory', self.checkUpdateSensors,
                                  (self._channels, ), 0.01)

    def stop(self):
        """ Stop updating the sensor table """
        if self._name != '':
            print "Stopped updating database for %s sensor changes" % (
                self._name)
        else:
            print "Stopped updating database for [unknown] sensor changes"

        self._removePollingProcessor('sensorHistory')

    def checkUpdateSensors(self, channels):
        """ Check the specified channels and update the database whenever changes are detected to the 'value' or 'status'"""
        for uuid, sensor in channels.items():
            if not self._logCache.has_key(uuid):
                current = self._dao.getSensor(sensor['id'])
                self._logCache[uuid] = {
                    'value': current['value'],
                    'status': current['status']
                }

            status = str(sensor['status']).capitalize()
            if self._logCache[uuid]['status'] != status or self._logCache[
                    uuid]['value'] != sensor['value']:
                val = sensor['value'] if len(
                    sensor['value']) > 1 else sensor['value'][0]
                timestamp = datetime.datetime.now().strftime(
                    '%Y-%m-%d %H:%M:%S')
                success = self._dao.saveSensorLog(sensor['id'], val, status,
                                                  timestamp, sensor['room'],
                                                  sensor['channel'])
                if success:
                    print "Updated sensor log for %(id)s to %(status)s (%(value)s)" % {
                        'id': sensor['channel'],
                        'status': status,
                        'value': val,
                    }
                    self._logCache[uuid]['value'] = sensor['value']
                    self._logCache[uuid]['status'] = status
Exemple #5
0
class Scenario(object):
    def __init__(self):
        self._dao = DataAccess()
        self._robot = Factory.getRobot('UH Sunflower')
        self._thread1 = myThreadLights(1, "Thread-1", self._robot)
        self._thread2 = myThreadHead(2, "Thread-2", self._robot)

    def Scenario1(self):
        #self._thread1.start()
        time.sleep(25)
        self._dao.setResponse('fromDiningArea', None)
Exemple #6
0
class SensorLog(PollingProcessor):
    """ Handles updating sensors of all types to the database """
    def __init__ (self, channels, name=''):
        super(SensorLog, self).__init__()
        self._dao = DataAccess().sensors
        self._channels = channels
        self._logCache = {}
        self._name = name
                
    def start(self):
        """ Begin asynchronously updating changes in sensors """
        if self._name != '':
            print "Started updating database for %s sensor changes" % (self._name)
        else:
            print "Started updating database for [unknown] sensor changes"
        self._addPollingProcessor('sensorHistory', self.checkUpdateSensors, (self._channels,), 0.01)

    def stop(self):
        """ Stop updating the sensor table """
        if self._name != '':
            print "Stopped updating database for %s sensor changes" % (self._name)
        else:
            print "Stopped updating database for [unknown] sensor changes"

        self._removePollingProcessor('sensorHistory')

    def checkUpdateSensors(self, channels):
        """ Check the specified channels and update the database whenever changes are detected to the 'value' or 'status'"""
        for uuid, sensor in channels.items():
            if not self._logCache.has_key(uuid):
                current = self._dao.getSensor(sensor['id'])
                self._logCache[uuid] = { 'value': current['value'], 'status': current['status']}

            status = str(sensor['status']).capitalize()
            if self._logCache[uuid]['status'] != status or self._logCache[uuid]['value'] != sensor['value']:
                val = sensor['value'] if len(sensor['value']) > 1 else sensor['value'][0]
                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                success = self._dao.saveSensorLog(
                                                  sensor['id'],
                                                  val,
                                                  status,
                                                  timestamp,
                                                  sensor['room'],
                                                  sensor['channel'])
                if success:
                    print "%(time)s: Updated sensor log for %(id)s to %(status)s (%(value)s)" % { 
                                                                           'time':timestamp,
                                                                           'id':sensor['channel'],
                                                                           'status': status,
                                                                           'value': val,
                                                                           }
                    self._logCache[uuid]['value'] = sensor['value']
                    self._logCache[uuid]['status'] = status
Exemple #7
0
    def addHistory(self, ruleName, imageBytes=None, imageType=None):
        """ updates the action history table, blocking until all data is retrieved and stored """
        """ returns true on successful update """

        from Robots.robotFactory import Factory
        cob = Factory.getCurrentRobot()
        dao = DataAccess()
        dateNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        location = dao.getRobotByName(cob.name)['locationId']

        historyId = dao.saveHistory(dateNow, ruleName, location)

        if (historyId > 0):
            dao.saveSensorHistory(historyId)

            if imageType == None:
                imageType = ActionHistory._defaultImageType

            if imageBytes == None:
                imageBytes = cob.getImage(retFormat=imageType)

            if imageBytes != None:
                dao.saveHistoryImage(historyId, imageBytes, imageType)

        return historyId > 0
Exemple #8
0
class MapImage(object):
    exposed = True
    
    def __init__(self):
        #TODO: Handle multiple robots
        self._dao = DataAccess()
        self._sr = StateResolver()
        activeLocation = Locations().getActiveExperimentLocation()
        if activeLocation == None:
            return cherrypy.HTTPError(500, "Unable to determine active location")

        robot = Robots().getRobot(activeLocation['activeRobot'])
        self._robotName = robot['robotName']
        
        self._emptyMap = locations_config[activeLocation['location']]['map']
        
    def GET(self, *args, **kwargs):
        #if len(args) < 1:
            #raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor(self._emptyMap)
        sensors = self._sr.resolveStates(self._dao.findSensors())
        #sensors = self._sr.appendSensorMetadata(sensors, self._emptyMap) #adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
               'icon':self._dao.sensors.getSensorIconByName('robot')['id'], 
               'name':cob['robotName'], 
               'xCoord': cob['xCoord'],
               'yCoord': cob['yCoord'],
               'orientation': '%sd' % cob['orientation'],
               'id':'r%s' % (cob['robotId'])
               }

        elements = []
        elements.extend(sensors)
        #important to put robot last as z-order is determined by render order in svg and we want the robot icon
        #to always be on top
        elements.append(robot)
        
        img = mp.buildMap(elements)
        
        data = io.BytesIO(img)
        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
        cherrypy.response.headers['Cache-Control'] = "max-age=0, no-cache, must-revalidate"
        cherrypy.response.headers['Pragma'] = "no-cache"
        # In the past to prevent browser caching
        cherrypy.response.headers['Expires'] = (datetime.datetime.utcnow() - datetime.timedelta(hours=1)).strftime('%a, %d %b %Y %H:%M:%S GMT')
        return file_generator(data)
Exemple #9
0
 def __init__(self):
     super(LocationProcessor, self).__init__()
     self._dao = DataAccess()
     self._storedLoc = lambda: {'locationName': '', 'xCoord': 0, 'yCoord': 0, 'orientation': 0, 'driftThreshold': 0 }
     self._curLoc = lambda: ('', (0, 0, 0))
     self._updateLoc = lambda locid, x, y, orientation: True
     self._targetName = ''
Exemple #10
0
class Images(object):
    exposed = True

    def __init__(self):
        self._dao = DataAccess()
        self._basePath = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), 'images')

    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        img = self._dao.getBinary(args[0])

        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
            img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
Exemple #11
0
class SensorLog(PollingProcessor):    
    def __init__ (self, channels, name=''):
        super(SensorLog, self).__init__()
        self._dao = DataAccess().sensors
        self._channels = channels
        self._logCache = {}
        self._name = name
                
    def start(self):
        if self._name != '':
            print "Started updating database for %s sensor changes" % (self._name)
        else:
            print "Started updating database for [unknown] sensor changes"
        self._addPollingProcessor('sensorHistory', self.checkUpdateSensors, (self._channels,), 0.01)

    def stop(self):
        if self._name != '':
            print "Stopped updating database for %s sensor changes" % (self._name)
        else:
            print "Stopped updating database for [unknown] sensor changes"

        self._removePollingProcessor('sensorHistory')

    def checkUpdateSensors(self, channels):
        for uuid, sensor in channels.items():
            if not self._logCache.has_key(uuid):
                current = self._dao.getSensor(sensor['id'])
                self._logCache[uuid] = { 'value': current['value'], 'status': current['status']}

            status = str(sensor['status']).capitalize()
            if self._logCache[uuid]['status'] != status:
                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                success = self._dao.saveSensorLog(
                                                  sensor['id'],
                                                  sensor['value'],
                                                  status,
                                                  timestamp,
                                                  sensor['room'],
                                                  sensor['channel'])
                if success:
                    print "Updated sensor log for %(id)s to %(status)s" % { 
                                                                           'id':sensor['channel'],
                                                                           'status': status
                                                                           }
                    self._logCache[uuid]['value'] = sensor['value']
                    self._logCache[uuid]['status'] = status
Exemple #12
0
    def addHistory(self, ruleName, imageBytes=None, imageType=None):
        """ updates the action history table, blocking until all data is retrieved and stored """
        """ returns true on successful update """

        from Robots.robotFactory import Factory

        cob = Factory.getCurrentRobot()
        dao = DataAccess()
        dateNow = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        location = dao.getRobotByName(cob.name)["locationId"]

        historyId = dao.saveHistory(dateNow, ruleName, location)

        if historyId > 0:
            dao.saveSensorHistory(historyId)

            if imageType == None:
                imageType = ActionHistory._defaultImageType

            if imageBytes == None:
                imageBytes = cob.getImage(retFormat=imageType)

            if imageBytes != None:
                dao.saveHistoryImage(historyId, imageBytes, imageType)

        return historyId > 0
Exemple #13
0
class SensorLog(PollingProcessor):    
    def __init__ (self, channels, name=''):
        super(SensorLog, self).__init__()
        self._dao = DataAccess().sensors
        self._channels = channels
        self._logCache = {}
        self._name = name
                
    def start(self):
        if self._name != '':
            print "Started polling sensor changes for %s" % (self._name)
        else:
            print "Started polling sensor changes"
        self._addPollingProcessor('sensorHistory', self.checkUpdateSensors, (self._channels, ), 0.01)

    def stop(self):
        if self._name != '':
            print "Stopped polling sensor changes for %s" % (self._name)
        else:
            print "Stopped polling sensor changes"

        self._removePollingProcessor('sensorHistory')

    def checkUpdateSensors(self, channels):
        for k in channels.keys():
            if not self._logCache.has_key(k):
                current = self._dao.getSensor(channels[k]['id'])
                self._logCache.setdefault(k, { 'value': current['value'], 'status': current['status']})
            if self._logCache[k]['status'] != channels[k]['status']:
                timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                success = self._dao.saveSensorLog(
                                                  channels[k]['id'], 
                                                  channels[k]['value'], 
                                                  channels[k]['status'],
                                                  timestamp,
                                                  channels[k]['room'],
                                                  channels[k]['channel'])
                if success:
                    print "Updated sensor log for %(id)s to %(status)s" % { 
                                                                           'id':channels[k]['channel'], 
                                                                           'status': channels[k]['status']
                                                                           }
                    self._logCache[k]['value'] = channels[k]['value']
                    self._logCache[k]['status'] = channels[k]['status']
Exemple #14
0
class MapImage(object):
    exposed = True

    def __init__(self):
        self._robotName = CareOBot().name
        self._dao = DataAccess()
        self._sr = StateResolver()

    def GET(self, *args, **kwargs):
        #if len(args) < 1:
        #raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor()
        sensors = self._sr.resolveStates(self._dao.findSensors())
        sensors = self._sr.appendSensorMetadata(
            sensors)  #adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
            'type':
            'robot',
            'name':
            cob['robotName'],
            'location':
            (cob['xCoord'], cob['yCoord'], '%sd' % (cob['orientation'] * -1)
             ),  #svg rotates opposite of our cooridnate system
            'id':
            'r%s' % (cob['robotId'])
        }

        elements = []
        elements.extend(sensors)
        #important to put robot last as z-order is determined by render order in svg and we want the robot icon
        #to always be on top
        elements.append(robot)

        img = mp.buildMap(elements)

        data = io.BytesIO(img)
        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
            'img.svg')[0]
        return file_generator(data)
Exemple #15
0
    def __init__(self):
        #TODO: Handle multiple robots
        self._dao = DataAccess()
        self._sr = StateResolver()
        activeLocation = Locations().getActiveExperimentLocation()
        if activeLocation == None:
            return cherrypy.HTTPError(500, "Unable to determine active location")

        robot = Robots().getRobot(activeLocation['activeRobot'])
        self._robotName = robot['robotName']
        
        self._emptyMap = locations_config[activeLocation['location']]['map']
Exemple #16
0
class MapImage(object):
    exposed = True

    def __init__(self):
        self._robotName = CareOBot().name
        self._dao = DataAccess()
        self._sr = StateResolver()

    def GET(self, *args, **kwargs):
        # if len(args) < 1:
        # raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        mp = MapProcessor()
        sensors = self._sr.resolveStates(self._dao.findSensors())
        sensors = self._sr.appendSensorMetadata(sensors)  # adds location and type
        cob = self._dao.getRobotByName(self._robotName)
        robot = {
            "type": "robot",
            "name": cob["robotName"],
            "location": (
                cob["xCoord"],
                cob["yCoord"],
                "%sd" % (cob["orientation"] * -1),
            ),  # svg rotates opposite of our cooridnate system
            "id": "r%s" % (cob["robotId"]),
        }

        elements = []
        elements.extend(sensors)
        # important to put robot last as z-order is determined by render order in svg and we want the robot icon
        # to always be on top
        elements.append(robot)

        img = mp.buildMap(elements)

        data = io.BytesIO(img)
        cherrypy.response.headers["Content-Type"] = mimetypes.guess_type("img.svg")[0]
        return file_generator(data)
Exemple #17
0
class Data(object):
    exposed = True

    def __init__(self):
        self._dao = DataAccess()

    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(400)

        questionNo = args[0]
        if questionNo == 'current':
            ques = self._dao.getActiveQuestion()
            if ques != None:
                questionNo = ques['sequenceName']
            else:
                questionNo = None

        if questionNo != None:
            resp = self._dao.getResponses(questionNo)
            obj = {'query': questionNo, 'responses': resp}
        else:
            obj = {'query': 'none'}

        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(obj)

    def POST(self, *args, **kwargs):
        request = json.loads(cherrypy.request.body.read())
        if not request.has_key('response'):
            raise cherrypy.HTTPError(400)
        else:
            userresponse = int(request['response'])
            if self._dao.setResponse(args[0], userresponse):
                return 'OK'
            else:
                raise cherrypy.HTTPError(500)
Exemple #18
0
class Data(object):
    exposed = True
    
    def __init__(self):
        self._dao = DataAccess()
        
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(400)
        
        questionNo = args[0]
        if questionNo == 'current':
            ques = self._dao.getActiveQuestion()
            if ques != None:
                questionNo = ques['sequenceName']
            else:
                questionNo = None
        
        if questionNo != None:
            resp = self._dao.getResponses(questionNo)
            obj = {'query': questionNo, 'responses':resp}
        else:
            obj = {'query': 'none'}
        
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(obj)

    def POST(self, *args, **kwargs):
        request = json.loads(cherrypy.request.body.read())
        if not request.has_key('response'):
            raise cherrypy.HTTPError(400)
        else:
            userresponse = int(request['response'])
            if self._dao.setResponse(args[0], userresponse):
                return 'OK'
            else:
                raise cherrypy.HTTPError(500)
Exemple #19
0
class LocationProcessor(PollingProcessor):
    """Abstract location processor, current concrete implementations are Human and Robot processors"""
    
    def __init__(self):
        super(LocationProcessor, self).__init__()
        self._dao = DataAccess()
        self._storedLoc = lambda: {'locationName': '', 'xCoord': 0, 'yCoord': 0, 'orientation': 0, 'driftThreshold': 0 }
        self._curLoc = lambda: ('', (0, 0, 0))
        self._updateLoc = lambda locid, x, y, orientation: True
        self._targetName = ''
    
    def start(self):
        print "Started polling location for %s" % (self._targetName)
        self._addPollingProcessor('location', self.checkUpdateLocation, (self._curLoc, self._storedLoc, self._updateLoc), 2)

    def stop(self):
        print "Stopped polling location for %s" % (self._targetName)
        self._removePollingProcessor('location')
    
    def checkUpdateLocation(self, getCurrentLocation, getSavedLocation, updateLocation):
        savedLoc = getSavedLocation()
        (name, (x, y, orientation)) = getCurrentLocation()

        if x == None or y == None:
            return
        
        update = False
        if name != savedLoc['locationName']:
            update = True
        else:
            dist = 0
            dist += math.pow(x - savedLoc['xCoord'], 2)
            dist += math.pow(y - savedLoc['yCoord'], 2)
            dist = math.sqrt(dist)
            if not savedLoc.has_key('driftThreshold') or dist > savedLoc['driftThreshold']:
                update = True
            else:
                if abs(savedLoc['orientation'] - orientation) > 5:                     
                    update = True

        if update:
            loc = self._dao.getLocationByName(name)
            if loc == None:
                locid = None
            else:
                locid = loc['locationId']
            print "Updating %(target)s location to Name:%(name)s, X:%(x)s, Y:%(y)s, O:%(orientation)s" % dict({'target':self._targetName}.items() + locals().items())
            updateLocation(locid, x, y, orientation)
Exemple #20
0
class LocationProcessor(PollingProcessor):
    """Abstract location processor, current concrete implementations are Human and Robot processors"""
    
    def __init__(self):
        super(LocationProcessor, self).__init__()
        self._dao = DataAccess()
        self._storedLoc = lambda: {'locationName': '', 'xCoord': 0, 'yCoord': 0, 'orientation': 0, 'driftThreshold': 0 }
        self._curLoc = lambda: ('', (0, 0, 0))
        self._updateLoc = lambda locid, x, y, orientation: True
        self._targetName = ''
    
    def start(self):
        print "Started polling location for %s" % (self._targetName)
        self._addPollingProcessor('location', self.checkUpdateLocation, (self._curLoc, self._storedLoc, self._updateLoc), 2)

    def stop(self):
        print "Stopped polling location for %s" % (self._targetName)
        self._removePollingProcessor('location')
    
    def checkUpdateLocation(self, getCurrentLocation, getSavedLocation, updateLocation):
        savedLoc = getSavedLocation()
        (name, (x, y, orientation)) = getCurrentLocation()

        if x == None or y == None:
            return
        
        update = False
        if name != savedLoc['locationName']:
            update = True
        else:
            dist = 0
            dist += math.pow(x - savedLoc['xCoord'], 2)
            dist += math.pow(y - savedLoc['yCoord'], 2)
            dist = math.sqrt(dist)
            if not savedLoc.has_key('driftThreshold') or dist > savedLoc['driftThreshold']:
                update = True
            else:
                if abs(savedLoc['orientation'] - orientation) > 5:                     
                    update = True

        if update:
            loc = self._dao.getLocationByName(name)
            if loc == None:
                locid = None
            else:
                locid = loc['locationId']
            print "Updating %(target)s location to Name:%(name)s, X:%(x)s, Y:%(y)s, O:%(orientation)s" % dict({'target':self._targetName}.items() + locals().items())
            updateLocation(locid, x, y, orientation)
Exemple #21
0
class UserData(object):
    
    def __init__(self):
        self._dao = DataAccess()
        
    exposed = True

    def GET(self, *args, **kwargs):
        
        if len(args) < 1:
            raise cherrypy.HTTPError(400)
        
        questionNo = args[0]
        if questionNo == 'preferences':
            value = self._dao.getUserPreferences()
        elif questionNo == 'persona':
            value = self._dao.getPersonaValues()
        elif questionNo == 'username': 
            value = self._dao.getActiveUserName()
        elif questionNo == 'experimentLocation':
            value = self._dao.getActiveExperimentLocation()
        
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(value)
    
    def POST(self, *args, **kwargs):
        
        request = json.loads(cherrypy.request.body.read())

        if request.has_key('time'):
            time = datetime.datetime.now().strftime('%H:%M:%S') #strftime('%Y-%m-%d %H:%M:%S') 
            self._dao.setSessionControlTime(time)
        elif request.has_key('preferences'):
            for column, value in request.iteritems():
                if column != 'preferences':
                    print column + " " + value
                    self._dao.setUserPreferences(column, value)
        else:
            raise cherrypy.HTTPError(400)
Exemple #22
0
    def addHistory(self, ruleName, imageBytes=None, imageType=None):
        
        cob = CareOBot()
        dao = DataAccess()
        dateNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        location = dao.getRobotByName(cob.name)['locationId']
        
        historyId = dao.saveHistory(dateNow, ruleName, location)
        
        if(historyId > 0):
            dao.saveSensorHistory(historyId)

            if imageType == None:
                imageType = ActionHistory._defaultImageType

            if imageBytes == None:
                imageBytes = cob.getImage(retFormat=imageType)

            if imageBytes != None:
                dao.saveHistoryImage(historyId, imageBytes, imageType)
        
        return historyId > 0
Exemple #23
0
class MapHistory(object):
    exposed = True
    
    def __init__(self):
        self._dao = DataAccess()
        
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        key = args[0]
        
        sensorHist = self._dao.getSensorHistory(key)        
        if len(sensorHist) > 0:
            mp = MapProcessor()
            s = StateResolver()
            sensors = s.resolveStates(sensorHist)     
            img = mp.buildMap(sensors)
            data = io.BytesIO(img)
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type('img.svg')[0]
            return file_generator(data)
Exemple #24
0
class Images(object):
    exposed = True
    
    def __init__(self):
        self._dao = DataAccess()
        self._basePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images')
        
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        from PIL import Image
        fileName, fileExtension = os.path.splitext(args[0])
        if fileExtension=='.jpg':
            #path = os.path.join(self._basePath, args[0])
            data = Image.open(os.path.join(self._basePath, args[0]))
            img = {
                   'data': None,
                   'meta': {
                            'type': '',
                            'name': ''
                            }
                   }
        else:
            img = self._dao.getBinary(args[0])

        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
Exemple #25
0
class ImagesOverhead(object):
    exposed = True
    
    def __init__(self):
        self._dao = DataAccess()
        self._basePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'imagesOverhead')
        
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        img = self._dao.getBinaryOverhead(args[0])
        
        if img['data'] == None:
            path = os.path.join(self._basePath, args[0])
            if os.path.exists(path):
                data = io.FileIO(path)
            else:
                raise cherrypy.HTTPError(404)
        else:
            data = io.BytesIO(img['data'])

        cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(img['meta']['name'] + '.' + img['meta']['type'])[0]
        return file_generator(data)
Exemple #26
0
class MapHistory(object):
    exposed = True

    def __init__(self):
        self._dao = DataAccess()

    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(403, 'Directory Listing Denied')

        key = args[0]

        sensorHist = self._dao.getSensorHistory(key)
        if len(sensorHist) > 0:
            mp = MapProcessor()
            s = StateResolver()
            sensors = s.resolveStates(sensorHist)
            #[{'id': sensor['sensorId'], 'value': sensor['value'], 'state':'on'},]
            sensors = s.appendSensorMetadata(sensors)  #adds location and type
            img = mp.buildMap(sensors)
            data = io.BytesIO(img)
            cherrypy.response.headers['Content-Type'] = mimetypes.guess_type(
                'img.svg')[0]
            return file_generator(data)
Exemple #27
0
    def addHistoryComplete(self, ruleName, imageBytes=None, imageType=None, imageOverheadBytes=None, imageOverheadType=None):
        """ updates the action history table, blocking until all data is retrieved and stored """
        """ returns true on successful update """
        
        from Robots.robotFactory import Factory
        cob = Factory.getCurrentRobot()
        dao = DataAccess()
        dateNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        location = dao.getRobotByName(cob.name)['locationId']
        user = self._dao.users.getActiveUser['userId']

        historyId = dao.saveHistoryComplete(dateNow, ruleName, location, user)
        
        if(historyId > 0):
            #dao.saveSensorHistory(historyId)

            if imageType == None:
                imageType = ActionHistory._defaultImageType

            if imageBytes == None:
                imageBytes = cob.getImage(retFormat=imageType)

            if imageBytes != None:
                dao.saveHistoryImage(historyId, imageBytes, imageType)

            #the same but for the overhead camera image

            if imageOverheadType == None:
                imageOverheadType = ActionHistory._defaultImageType

            if imageOverheadBytes == None:
                imageOverheadBytes = cob.getImageOverhead(retFormat=imageOverheadType)

            if imageOverheadBytes != None:
                dao.saveHistoryImageOverhead(historyId, imageOverheadBytes, imageOverheadType)
        
        return historyId > 0
Exemple #28
0
 def __init__(self):
     self._dao = DataAccess()
     self._robot = Factory.getRobot('UH Sunflower')
     self._thread1 = myThreadLights(1, "Thread-1", self._robot)
     self._thread2 = myThreadHead(2, "Thread-2", self._robot)
Exemple #29
0
 def __init__(self, channels, name=""):
     super(SensorLog, self).__init__()
     self._dao = DataAccess().sensors
     self._channels = channels
     self._logCache = {}
     self._name = name
Exemple #30
0
class Data(object):
    exposed = True
    
    def __init__(self):
        self._dao = DataAccess()
        
    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(400)
        dataType = args[0]
        if len(args) > 1:
            dataKey = args[1]
        elif kwargs.has_key('key'):
            dataKey = kwargs['key']
        else:
            dataKey = None

        obj = None    
        if dataType == 'user':
            obj = {}
        elif dataType == 'robot':
            obj = {}
        elif dataType == 'events':
            if kwargs.has_key('tags'):
                tags = kwargs['tags'].split(',')
            else:
                tags = ()
            obj = self.getEvents(dataKey, tags)
        else :
            raise cherrypy.HTTPError(400)
        
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(obj)
    
    def POST(self, *args, **kwargs):
        request = json.loads(cherrypy.request.body.read())
        if not request.has_key('historyId'):
            raise cherrypy.HTTPError(400)
        else:
            historyId = request['historyId']
            tags = request['tags']
            if type(tags) != tuple and type(tags) != list:
                tags = (tags, )
            if type(tags) == list:
                tags = tuple(tags)
            if self._dao.actionHistory.updateTags(historyId, tags) >= 0:
                return 'OK'
            else:
                raise cherrypy.HTTPError(500)


    def getEvents(self, key, tags):
        events = self._dao.getHistory(key, tags)
        #if len(events) == 0:
        #    raise cherrypy.HTTPError(404)
        
        for event in events:
            if event['imageId'] != None:
                event['imageUrl'] = 'images/%s' % event['imageId']
            event.pop('imageId')
            if event['sensors'] != None and len(event['sensors']) > 0:
                event['sensorMapUrl'] = 'mapHistory/%s' % event['id']
            
        return {'Episodes': [{'Events': events}]}
Exemple #31
0
 def __init__(self):
     self._robotName = CareOBot().name
     self._dao = DataAccess()
     self._sr = StateResolver()
Exemple #32
0
 def __init__(self, threadID, name, robot):
     threading.Thread.__init__(self)
     self._threadID = threadID
     self._robot = robot
     self._name = name
     self._dao = DataAccess()
Exemple #33
0
 def __init__(self):
     self._dao = DataAccess()
     self._basePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images')
Exemple #34
0
class RobotCommands(object):

    exposed = True

    def __init__(self):
        self._dao = DataAccess()
        self._scenarios = Scenario()
        self._host = "nathan@sf1-1-pc1"
        self._robot = Factory.getCurrentRobot()

    def POST(self, *args, **kwargs):

        request = json.loads(cherrypy.request.body.read())

        # Send the robot to certain location (The behaviour depends on the scenario)
        if request.has_key('location'):

            if request['scenario'] == 1:
                if request['scenarioType'] == 'HallDoorbell':
                    self._scenarios.ScenarioDoorbell1(request, self._host)
                else:
                    self._scenarios.Scenario1(request, self._host)

            elif request['scenario'] == 2:
                if request['scenarioType'] == 'HallDoorbell':
                    self._scenarios.ScenarioDoorbell2(request, self._host)
                elif request['scenarioType'] == 'LivingDrink':
                    self._scenarios.Scenario2(request, self._host)
                else:
                    self._scenarios.Scenario1(request, self._host)

            elif request['scenario'] == 3:
                if request['scenarioType'] == 'HallDoorbell':
                    self._scenarios.ScenarioDoorbell1(request, self._host)
                else:
                    self._scenarios.Scenario3(request, self._host)

        # Send voice command to the robot (espeak software required)
        elif request.has_key(
                'speech') and self._dao.getActiveQuestion()['repeated'] == 0:

            #Block other interfaces to repeat the message
            self._dao.setResponse(request['messageId'], None, 1)
            self._preferences = self._dao.users.getUserPreferences()

            if request['scenario'] == 3 or request[
                    'messageId'] == 'doorbellAssistLowPro':
                time.sleep(0.5)  #Including delay to help transition
            elif request['scenario'] == 1 or request['scenario'] == 2:
                time.sleep(7)  #Time to wait for the body movement to finish

            if self._preferences[0]['voice'] == 1:
                self._robot.setComponentState('head', 'front')

                #Compose speech
                if request['scenario'] == 1 or request['scenario'] == 2:
                    message = request['speech'].replace(
                        "User,", request['username'] + ",")
                else:
                    message = request['speech'].replace("User, ", "")
                message = message.replace("<br/>",
                                          "")  #Remove end of line if exists

                #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
                #subprocess.call(['espeak', message]) #Linux
                subprocess.Popen(
                    ["ssh",
                     "%s" % self._host,
                     "espeak -s 135 '%s'" % message],
                    shell=False,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)  #Remote Linux

                if request['scenario'] == 1 or request['scenario'] == 2:
                    self._robot.setComponentState('head', 'front_bend_left')
                    time.sleep(0.150)
                    self._robot.setComponentState('head', 'front_bend_right')
                    time.sleep(0.150)
                    self._robot.setComponentState('head', 'front')
                else:
                    time.sleep(1)

                ## Determine the speech time
                wait = 0.3 * (len(message.split()) - 1)
                time.sleep(wait)

            #It means the robot has already spoken and the dialog can be shown
            self._dao.setResponse(request['messageId'], None, 2)

            # Open Tray
            if self._robot.getComponentState('tray')[0] == 'lowered':
                self._robot.setComponentState('tray', 'raised')

            #Finish Action
            self._robot.setComponentState('head', 'back')
            self._robot.setLight(eval(self._preferences[0]['light']))

            # Open Tray (Sometimes the first attempt is failing)
            if self._robot.getComponentState('tray')[0] != 'raised':
                self._robot.setComponentState('tray', 'raised')

        else:
            raise cherrypy.HTTPError(400)
Exemple #35
0
 def __init__(self):
     self._robotName = CareOBot().name
     self._dao = DataAccess()
     self._sr = StateResolver()
Exemple #36
0
 def __init__(self, channels, name=''):
     super(SensorLog, self).__init__()
     self._dao = DataAccess().sensors
     self._channels = channels
     self._logCache = {}
     self._name = name
Exemple #37
0
 def __init__(self):
     self._dao = DataAccess()
     self._basePath = os.path.join(
         os.path.dirname(os.path.realpath(__file__)), 'images')
Exemple #38
0
class Scenario(object):
    def __init__(self):
        self._dao = DataAccess()
        self._preferences = self._dao.users.getUserPreferences()
        self._robot = Factory.getCurrentRobot()
        self._threadLights = myThreadLights(1, "Thread-Lights", self._robot)
        self._threadHead = myThreadHead(2, "Thread-Head", self._robot)
        self._threadBase = myThreadBase(3, "Thread-BaseDirect", self._robot)
        self._threadTray = myThreadTray(4, "Thread-Tray", self._robot)

    def Scenario1(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])
        #Preferred LED colour

        self._robot.setComponentState('head',
                                      'front')  #Set default head position

        #Compose speech
        if request['scenario'] == 1 or request['scenario'] == 2:
            message = request['speech'].replace("User,",
                                                request['username'] + ",")
        else:
            message = request['speech'].replace("User, ", "")
        message = message.replace("<br/>", "")  #Remove end of line if exists

        #If robot voice is activated
        if self._preferences[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', message]) #Linux
            subprocess.Popen(
                ["ssh", "%s" % host,
                 "espeak -s 135 '%s'" % message],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        time.sleep(1.5)

        self._threadLights.start()
        #Send the robot to the location
        #time.sleep(4)
        self._robot.setComponentState(
            'base',
            [location['xCoord'], location['yCoord'], location['orientation']])

        if 'KitchenDrink' == request['scenarioType']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
            self._dao.setResponse('goKitchen', None)
        elif 'TransportDrink' == request['scenarioType']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadHead.start()
            self._dao.setResponse('transportDrink', None)
        elif 'LivingDrink' == request['scenarioType']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
            self._dao.setResponse('goLivingRoom', None)
        elif 'TransportObject' == request['scenarioType']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
            self._dao.setResponse('transportObject', None)
        elif 'DoorbellGoToHall' == request['scenarioType']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
            self._dao.setResponse('doorbellAssistance', None)
        else:
            self._threadLights.stopLights(eval(self._preferences[0]['light']))
            self._robot.setComponentState('tray', 'raised')
            self._robot.setComponentState('head', 'back')  #Set head position

    def Scenario2(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])
        #Preferred LED colour

        self._threadLights.start()
        self._robot.setComponentState('head',
                                      'front')  #Set default head position

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        time.sleep(1)

        self._threadLights.arrivedPlace(eval(self._preferences[0]['light']))
        self._threadBase.start()
        self._dao.setResponse('fromDiningArea', None)

    def Scenario3(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])

        self._robot.setComponentState('head',
                                      'front')  #Set default head position

        #Compose speech
        if request['scenario'] == 1 or request['scenario'] == 2:
            message = request['speech'].replace("User,",
                                                request['username'] + ",")
        else:
            message = request['speech'].replace("User, ", "")
        message = message.replace("<br/>", "")  #Remove end of line if exists

        #If robot voice is activated
        if self._preferences[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', message]) #Linux
            subprocess.Popen(
                ["ssh", "%s" % host,
                 "espeak -s 135 '%s'" % message],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        time.sleep(1.5)

        #Send the robot to the location
        self._threadLights.start()
        #time.sleep(4)
        self._robot.setComponentState(
            'base',
            [location['xCoord'], location['yCoord'], location['orientation']])

        self._threadLights.stopLights(eval(self._preferences[0]['light']))

        if 'KitchenDrink' == request['scenarioType']:
            self._dao.setResponse('goKitchen', None)
        elif 'TransportDrink' == request['scenarioType']:
            self._dao.setResponse('transportDrink', None)
        elif 'LivingDrink' == request['scenarioType']:
            self._dao.setResponse('goLivingRoom', None)
        elif 'TransportObject' == request[
                'scenarioType'] or 'DoorbellGoToHall' == request[
                    'scenarioType']:
            self._dao.setResponse('transportObject', None)
        elif 'DoorbellGoToHall' == request['scenarioType']:
            self._dao.setResponse('transportObject', None)
        else:
            self._robot.setComponentState('tray', 'raised')
            self._robot.setComponentState('head', 'back')  #Set head position

    def ScenarioDoorbell1(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])

        self._robot.setComponentState('head', 'front')
        self._threadLights.start()

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        #Send the robot to the location (if it is not there already)
        #time.sleep(4)
        if request['scenario'] == 1:
            livingRoomLoc = self._dao.locations.getLocationByName(
                'Living Room Sofa Area')
            self._robot.setComponentState('base', [
                livingRoomLoc['xCoord'], livingRoomLoc['yCoord'],
                livingRoomLoc['orientation']
            ])
        else:
            livingRoomSocialLoc = self._dao.locations.getLocationByName(
                'Living Room Sofa Area Social')
            self._robot.setComponentState('base', [
                livingRoomSocialLoc['xCoord'], livingRoomSocialLoc['yCoord'],
                livingRoomSocialLoc['orientation']
            ])

        if request['scenario'] == 1:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))

            #Set base movement (expressive behaviour)
            self._robot.setComponentState('head', 'up')

            self._robot.setComponentState('base_direct', [0.2, 0.0])
            self._robot.setComponentState('head', 'up_look_left')

            self._robot.setComponentState('base_direct', [-0.4, 0.0])
            self._robot.setComponentState('head', 'up_look_right')

            self._robot.setComponentState('base_direct', [0.3, 0.0])
            self._robot.setComponentState('head', 'up_look_left')

            self._robot.setComponentState('base_direct', [-0.2, 0.0])
            self._robot.setComponentState('head', 'up_look_right')

            self._robot.setComponentState('base_direct', [0.075, 0.0])
            self._robot.setComponentState('head', 'up')
            time.sleep(0.5)
            self._robot.setComponentState('head', 'front')

        else:
            self._threadLights.stopLights(eval(self._preferences[0]['light']))

        #Compose speech
        if request['scenario'] == 1 or request['scenario'] == 2:
            message = request['speech'].replace("User,",
                                                request['username'] + ",")
        else:
            message = request['speech'].replace("User, ", "")
        message = message.replace("<br/>", "")  #Remove end of line if exists

        #If robot voice is activated
        if self._preferences[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', message]) #Linux
            subprocess.Popen(
                ["ssh", "%s" % host,
                 "espeak -s 135 '%s'" % message],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

            if request['scenario'] == 1:
                self._robot.setComponentState('head', 'front_bend_left')
                time.sleep(0.150)
                self._robot.setComponentState('head', 'front_bend_right')
                time.sleep(0.150)
                self._robot.setComponentState('head', 'front')
            else:
                time.sleep(1)

            ## Determine the speech time
            wait = 0.4 * (len(message.split()) - 1)
            time.sleep(wait)

        #Send the robot to the location
        time.sleep(1)
        self._threadLights.start()
        #time.sleep(4)
        self._robot.setComponentState(
            'base',
            [location['xCoord'], location['yCoord'], location['orientation']])

        #Stop blinking lights and tell user about help to transport
        if request['scenario'] == 1 or request['scenario'] == 2:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
        else:
            self._threadLights.stopLights(eval(self._preferences[0]['light']))

        self._dao.setResponse('doorbellAssistance', None)

    def ScenarioDoorbell2(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])

        self._robot.setComponentState('head', 'front')
        self._threadLights.start()

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        livingRoomSocialLoc = self._dao.locations.getLocationByName(
            'Living Room Sofa Area Social')
        self._robot.setComponentState('base', [
            livingRoomSocialLoc['xCoord'], livingRoomSocialLoc['yCoord'],
            livingRoomSocialLoc['orientation']
        ])
        self._threadLights.arrivedPlace(eval(self._preferences[0]['light']))

        #Set base movement (expressive behaviour)
        self._robot.setComponentState('head', 'up')

        self._robot.setComponentState('base_direct', [0.2, 0.0])
        self._robot.setComponentState('head', 'up_look_left')

        self._robot.setComponentState('base_direct', [-0.4, 0.0])
        self._robot.setComponentState('head', 'up_look_right')

        self._robot.setComponentState('base_direct', [0.3, 0.0])
        self._robot.setComponentState('head', 'up_look_left')

        self._robot.setComponentState('base_direct', [-0.2, 0.0])
        self._robot.setComponentState('head', 'up_look_right')

        self._robot.setComponentState('base_direct', [0.075, 0.0])
        self._robot.setComponentState('head', 'up')
        time.sleep(0.5)
        self._robot.setComponentState('head', 'front')

        #Wait until the tray finishes
        time.sleep(1.5)

        self._dao.setResponse('doorbellAssistLowPro', None)
Exemple #39
0
class Data(object):
    exposed = True

    def __init__(self):
        self._dao = DataAccess()

    def GET(self, *args, **kwargs):
        if len(args) < 1:
            raise cherrypy.HTTPError(400)
        dataType = args[0]
        if len(args) > 1:
            dataKey = args[1]
        elif kwargs.has_key('key'):
            dataKey = kwargs['key']
        else:
            dataKey = None

        obj = None
        if dataType == 'user':
            obj = {}
        elif dataType == 'robot':
            obj = {}
        elif dataType == 'events':
            if kwargs.has_key('tags'):
                tags = kwargs['tags'].split(',')
            else:
                tags = ()
            obj = self.getEvents(dataKey, tags)
        else:
            raise cherrypy.HTTPError(400)

        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(obj)

    def POST(self, *args, **kwargs):
        request = json.loads(cherrypy.request.body.read())
        if not request.has_key('historyId'):
            raise cherrypy.HTTPError(400)
        else:
            historyId = request['historyId']
            tags = request['tags']
            if type(tags) != tuple and type(tags) != list:
                tags = (tags, )
            if type(tags) == list:
                tags = tuple(tags)
            if self._dao.actionHistory.updateTags(historyId, tags) >= 0:
                return 'OK'
            else:
                raise cherrypy.HTTPError(500)

    def getEvents(self, key, tags):
        events = self._dao.getHistory(key, tags)
        #if len(events) == 0:
        #    raise cherrypy.HTTPError(404)

        for event in events:
            if event['imageId'] != None:
                event['imageUrl'] = 'images/%s' % event['imageId']
            event.pop('imageId')
            if event['sensors'] != None and len(event['sensors']) > 0:
                event['sensorMapUrl'] = 'mapHistory/%s' % event['id']

        return {'Episodes': [{'Events': events}]}
Exemple #40
0
 def __init__(self):
     self._dao = DataAccess()
     self._scenarios = Scenario()
     self._host = "nathan@sf1-1-pc1"
     self._robot = Factory.getCurrentRobot()
Exemple #41
0
 def __init__(self):
     self._dao = DataAccess()
Exemple #42
0
 def __init__(self):
     self._dao = DataAccess()
Exemple #43
0
class Scenario(object):
    def __init__(self):
        self._dao = DataAccess()
        self._preferences = self._dao.users.getUserPreferences()
        self._robot = Factory.getCurrentRobot()
        self._threadLights = myThreadLights(1, "Thread-Lights", self._robot)
        self._threadHead = myThreadHead(2, "Thread-Head", self._robot)
        self._threadBase = myThreadBase(3, "Thread-BaseDirect", self._robot)
        self._threadTray = myThreadTray(4, "Thread-Tray", self._robot)

    def Scenario1(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])
        #Preferred LED colour

        self._robot.setComponentState('head',
                                      'front')  #Set default head position

        #If robot voice is activated
        if self._dao.users.getUserPreferences()[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', request['speech']]) #Linux
            subprocess.Popen(
                ["ssh",
                 "%s" % host,
                 "espeak -s 135 '%s'" % request['speech']],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

#time.sleep(1.5)

#Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        time.sleep(1.5)

        self._threadLights.start()
        #Send the robot to the location
        #time.sleep(4)
        self._robot.setComponentState(
            'base',
            [location['xCoord'], location['yCoord'], location['orientation']])

        if "Kitchen Entrance" in request['location']:
            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            self._threadBase.start()
            self._dao.setResponse('goKitchen', None)

        elif "Living" in request['location']:

            self._threadLights.arrivedPlace(eval(
                self._preferences[0]['light']))
            if "Transporting" not in request['speech']:
                self._threadBase.start()
                self._dao.setResponse('goLivingRoom', None)
            else:
                self._threadHead.start()
                self._dao.setResponse('transportLivingRoom', None)
        else:
            self._threadLights.stopLights(eval(self._preferences[0]['light']))
            self._robot.setComponentState('tray', 'raised')
            self._robot.setComponentState('head', 'back')  #Set head position

    def Scenario3(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])

        self._robot.setComponentState('head',
                                      'front')  #Set default head position

        #If robot voice is activated
        if self._dao.users.getUserPreferences()[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', request['speech']]) #Linux
            subprocess.Popen(
                ["ssh",
                 "%s" % host,
                 "espeak -s 135 '%s'" % request['speech']],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

#Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

        time.sleep(1.5)

        #Send the robot to the location
        self._threadLights.start()
        #time.sleep(4)
        self._robot.setComponentState(
            'base',
            [location['xCoord'], location['yCoord'], location['orientation']])

        self._threadLights.stopLights(eval(self._preferences[0]['light']))

        if "Kitchen Entrance" in request['location']:
            self._dao.setResponse('goKitchen', None)

        elif "Living" in request['location']:

            if "Transporting" not in request['speech']:
                self._dao.setResponse('goLivingRoom', None)
            else:
                self._dao.setResponse('transportLivingRoom', None)

        else:
            self._robot.setComponentState('tray', 'raised')
            self._robot.setComponentState('head', 'back')  #Set head position

    def ScenarioDoorbell3(self, request, host):
        #Get the location selected by the user
        location = self._dao.locations.getLocationByName(request['location'])

        self._threadLights.start()
        time.sleep(2)
        self._robot.setComponentState('head', 'front')
        self._threadLights.arrivedPlace(eval(self._preferences[0]['light']))

        #Set base movement (expressive behaviour)
        self._robot.setComponentState('head', 'up')

        self._robot.setComponentState('base_direct', [0.2, 0.0])
        self._robot.setComponentState('head', 'up_look_left')

        self._robot.setComponentState('base_direct', [-0.4, 0.0])
        self._robot.setComponentState('head', 'up_look_right')

        self._robot.setComponentState('base_direct', [0.3, 0.0])
        self._robot.setComponentState('head', 'up_look_left')

        self._robot.setComponentState('base_direct', [-0.2, 0.0])
        self._robot.setComponentState('head', 'up_look_right')

        self._robot.setComponentState('base_direct', [0.1, 0.0])
        self._robot.setComponentState('head', 'up')
        time.sleep(0.5)
        self._robot.setComponentState('head', 'front')

        #Compose speech
        message = request['speech'].replace(
            "User",
            self._dao.users.getActiveUser()['firstName'])
        message = message.replace("<br/>", "")  #Remove end of line if exists

        #If robot voice is activated
        if self._dao.users.getUserPreferences()[0]['voice'] == 1:
            #subprocess.call(['C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe', request['speech']]) #Windows
            #subprocess.call(['espeak', request['speech']]) #Linux
            subprocess.Popen(
                ["ssh",
                 "%s" % host,
                 "espeak -s 135 '%s'" % request['speech']],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)  #Remote Linux

        self._robot.setComponentState('head', 'front_bend_left')
        time.sleep(0.150)
        self._robot.setComponentState('head', 'front_bend_right')
        time.sleep(0.150)
        self._robot.setComponentState('head', 'front')

        #Open or close tray
        if 'lowered' == request['tray']:
            self._robot.setComponentState('tray', 'lowered')
        else:
            self._robot.setComponentState('tray', 'raised')

#Wait until the tray finishes
        time.sleep(1.5)

        #Send the robot to the location #time.sleep(4)
        self._threadLights.start()
        time.sleep(4)
        #self._robot.setComponentState('base', [location['xCoord'], location['yCoord'], location['orientation']])
        #Stop blinking lights and tell user about help to transport
        self._threadLights.stopLights(eval(self._preferences[0]['light']))

        self._dao.setResponse('doorbellAssistance', None)