本文整理汇总了Python中Data.dataAccess.DataAccess类的典型用法代码示例。如果您正苦于以下问题:Python DataAccess类的具体用法?Python DataAccess怎么用?Python DataAccess使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DataAccess类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RobotCommands
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)
示例2: SensorLog
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
示例3: MapImage
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)
示例4: __init__
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 = ''
示例5: SensorLog
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
示例6: addHistory
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
示例7: SensorLog
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']
示例8: __init__
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']
示例9: MapImage
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)
示例10: Data
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)
示例11: LocationProcessor
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)
示例12: UserData
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)
示例13: MapHistory
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)
示例14: Images
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)
示例15: addHistory
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