Esempio n. 1
0
class States(object):
    def __init__(self):
        self._dao = Sensors()
        self._sr = StateResolver()
    
    exposed = True
    
    def GET(self, *args, **kwargs):
        
        sensors = self._dao.findSensors()
        sensors = sorted(sensors, key = itemgetter('locationName', 'ChannelDescriptor'))
        
        elements = []
        for sensor in sensors:
            elements.append(
                            {
                             'color': self.getBackgroundColor(sensor),
                             'room': '%(loc)s: %(sen)s' % { 'loc': sensor['locationName'], 'sen': sensor['name'] },
                             'channel': sensor['ChannelDescriptor'],
                             'value': sensor['value'],
                             'status': self._sr.getDisplayState(sensor)
                             })
        
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return json.dumps(elements)

    def getBackgroundColor(self, sensor):
        stype = sensor['sensorTypeName']
        if stype == 'CONTACT_REED':
            if float(sensor['value']) == 1:
                return '#FF0000'
            else:
                return '#00FF00' # closed door == green colour
        elif stype == 'CONTACT_PRESSUREMAT':
            if float(sensor['value']) == 1:
                return '#00FF00' # vacant chair == green colour
            else:
                return '#FF0000'
        elif stype == 'TEMPERATURE_MCP9700_HOT' or stype == 'TEMPERATURE_MCP9700_COLD':
            #return str((float(sensor['value']) - 0.5) * 100.0) + 'C'
            temp = float(sensor['value'])
            if temp < 0.0:
                r = 0
            elif temp > 50.0:
                r = 255
            else:
                r = int(temp * 5.1) # -0C..+50C -> 0..255
            g = 0
            b = 255 - r
            return '#%02X%02X%02X' % (r, g, b)
        elif stype == 'POWER_CONSUMPTION_MONITOR':
            if self._sr.isSensorOn(sensor):
                return '#FFFF00'
            else:
                return '#00FF00' # closed door == green colour
        else:
            return 'None'
Esempio n. 2
0
    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)
Esempio n. 3
0
class GEOSystem(PollingProcessor):
	
	def __init__ (self, hostName, userName, password, database, query):
		super(GEOSystem, self).__init__()
		self._geoDao = SQLDao(hostName, userName, password, database)		
		self._geoQuery = query
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._sr = StateResolver()
		self._channels = {}
		self._warned = []

	@property
	def channels(self):		
		return self._channels

	def start(self):
		print "Started polling geo sensors"
		self._addPollingProcessor('geoSensors', self.pollGeoSystem, None, 0.1)

	def stop(self):
		print "Stopped polling geo sensors"
		self._removePollingProcessor('geoSensors')

	def pollGeoSystem(self):
		rows = self._geoDao.getData(self._geoQuery)
		# This appears to be needed or 'CALL exppower' doesn't update the power values,
		# oddly, it updates the timestamp field though...
		self._geoDao.close()
		for row in rows:
			try:
				sensor = next(s for s in self._sensors if s['ChannelDescriptor'] == str(row['ID']))
			except StopIteration:
				# Only warn once, or we'll flood the console
				if row['ID'] not in self._warned:
					print >> sys.stderr, "Warning: Unable to locate sensor record for geo sensor %s. ID: %s" % (row['Description'], row['ID'])
					self._warned.append(row['ID'])
				continue

			_device = sensor['locationName']
			_name = sensor['name']
			_id = sensor['sensorId']
			_type = sensor['sensorTypeName']

			# Only warn once, or we'll flood the console
			if _name != row['Description'] and row['ID'] not in self._warned:
				print >> sys.stderr, 'Warning: Channel name differs from Geo-System description: %s / %s' % (_name, row['Description'])
				self._warned.append(row['ID'])

			_status = self._sr.getDisplayState({'sensorTypeName': _type, 'value': row['Power'], 'sensorId': _id })

			self._channels[row['ID']] = { 
										'id': _id,
										'room': _device,
										'channel': _name,
										'value': '%.1f' % row['Power'],
										'status': _status
										}
Esempio n. 4
0
	def __init__ (self, hostName, userName, password, database, query):
		super(GEOSystem, self).__init__()
		self._geoDao = SQLDao(hostName, userName, password, database)		
		self._geoQuery = query
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._sr = StateResolver()
		self._channels = {}
		self._warned = []
Esempio n. 5
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)
Esempio n. 6
0
	def __init__ (self, ipAddress):
		super(ZWaveHomeController, self).__init__()
		
		self._baseUrl = "http://%(ip)s:80/api/devices" % {'ip': ipAddress}

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []
Esempio n. 7
0
	def __init__ (self, udpPort):
		super(ZigBee, self).__init__()
		self.sock = socket(AF_INET, SOCK_DGRAM)
		self.sock.settimeout(1)
		self.sock.bind(('', udpPort))

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []
Esempio n. 8
0
	def __init__ (self, ipAddress, port):
		super(ZWaveVeraLite, self).__init__()
		
		self._loadTime = None
		self._dataVersion = None
		self._baseUrl = "http://%(ip)s:%(port)s/data_request?id=lu_sdata&timeout=%(timeout)s" % {'ip': ipAddress, 'port': port, 'timeout': 60}

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []
Esempio n. 9
0
 def __init__(self):
     self._dao = Sensors()
     self._sr = StateResolver()
Esempio n. 10
0
 def __init__(self):
     self._robotName = CareOBot().name
     self._dao = DataAccess()
     self._sr = StateResolver()
Esempio n. 11
0
 def __init__(self):
     self._robotName = CareOBot().name
     self._dao = DataAccess()
     self._sr = StateResolver()
Esempio n. 12
0
class ZigBee(PollingProcessor):

    # Initialisation method
    # Opens the configured UDP socket for the receipt of broadcast messages.
    def __init__(self, udpPort):
        super(ZigBee, self).__init__()
        self.sock = socket(AF_INET, SOCK_DGRAM)
        self.sock.settimeout(1)
        self.sock.bind(('', udpPort))

        # Place for the callback methods to store "static" values.
        # Currently only needed for the Moving Average Filter for the MCP9700
        # temperature sensor temperature calculations.
        self._handler_memory = {}
        self._channels = {}
        self._sr = StateResolver()
        self._sensorDao = Sensors()
        self._sensors = self._sensorDao.findSensors()
        self._warned = []

    @property
    def channels(self):
        if self._channels == None:
            self._channels = {}

        return self._channels

    def start(self):
        print "Started polling zigBee sensors"
        self._addPollingProcessor('zigBee', self.pollZigbeeSensors, None,
                                  0.0001)

    def stop(self):
        print "Stopped polling zigBee sensors"
        self._removePollingProcessor('zigBee')

    # ZigBee thread main loop
    def pollZigbeeSensors(self):
        try:
            data, _ = self.sock.recvfrom(10240, 0)
        except Exception as e:
            if type(e) != timeout:
                print e
            return

        (_, mac, channel, val) = data.split(' ')

        mac = mac.lower()
        channel = channel.upper()

        try:
            sensor = next(s for s in self._sensors
                          if s['ChannelDescriptor'] == str(mac) + str(channel))
        except StopIteration:
            #Only warn once, or we'll flood the console
            if str(mac) + str(channel) not in self._warned:
                print >> sys.stderr, "Warning: Unable to locate sensor record for zigbee sensor ID: %s" % (
                    str(mac) + str(channel))
                self._warned.append(str(mac) + str(channel))
            return

        _device = sensor['locationName']
        _pin = sensor['name']
        _id = sensor['sensorId']

        if val != '-' and val != '':
            _type = sensor['sensorTypeName']
            _uuid = '%s_%s' % (mac, channel)
            if _type == 'TEMPERATURE_MCP9700_HOT' or _type == 'TEMPERATURE_MCP9700_COLD':
                _value = str((float(val) - 0.5) * 100.0)
            else:
                _value = val

            _status = self._sr.getDisplayState({
                'sensorTypeName': _type,
                'value': _value,
                'sensorId': _id
            })

            self._channels[_uuid] = {
                'id': _id,
                'room': _device,
                'channel': _pin,
                'value': _value,
                'status': _status
            }
Esempio n. 13
0
class GEOSystem(PollingProcessor):
    def __init__(self, hostName, userName, password, database, query):
        super(GEOSystem, self).__init__()
        self._geoDao = SQLDao(hostName, userName, password, database)
        self._geoQuery = query
        self._sensorDao = Sensors()
        self._sensors = self._sensorDao.findSensors()
        self._sr = StateResolver()
        self._channels = {}
        self._warned = []

    @property
    def channels(self):
        return self._channels

    def start(self):
        print "Started polling geo sensors"
        self._addPollingProcessor('geoSensors', self.pollGeoSystem, None, 0.1)

    def stop(self):
        print "Stopped polling geo sensors"
        self._removePollingProcessor('geoSensors')

    def pollGeoSystem(self):
        rows = self._geoDao.getData(self._geoQuery)
        #This appears to be needed or 'CALL exppower' doesn't update the power values,
        # oddly, it updates the timestamp field though...
        self._geoDao.close()
        for row in rows:
            try:
                sensor = next(s for s in self._sensors
                              if s['ChannelDescriptor'] == str(row['ID']))
            except StopIteration:
                #Only warn once, or we'll flood the console
                if row['ID'] not in self._warned:
                    print >> sys.stderr, "Warning: Unable to locate sensor record for geo sensor %s. ID: %s" % (
                        row['Description'], row['ID'])
                    self._warned.append(row['ID'])
                continue

            _device = sensor['locationName']
            _name = sensor['name']
            _id = sensor['sensorId']

            #Only warn once, or we'll flood the console
            if _name != row['Description'] and row['ID'] not in self._warned:
                print >> sys.stderr, 'Warning: Channel name differs from Geo-System description: %s / %s' % (
                    _name, row['Description'])
                self._warned.append(row['ID'])

            _state = self._sr.evaluateRule(sensor['sensorRule'], row['Power'])

            if _state:
                _state = 'On'
            else:
                _state = 'Off'

            self._channels[row['ID']] = {
                'id': _id,
                'room': _device,
                'channel': _name,
                'value': '%.1f' % row['Power'],
                'status': _state
            }
Esempio n. 14
0
class ZigBee(PollingProcessor):

	# Initialisation method
	# Opens the configured UDP socket for the receipt of broadcast messages.
	def __init__ (self, udpPort):
		super(ZigBee, self).__init__()
		self.sock = socket(AF_INET, SOCK_DGRAM)
		self.sock.settimeout(1)
		self.sock.bind(('', udpPort))

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []

	@property
	def channels(self):
		if self._channels == None:
			self._channels = {}
		
		return self._channels

	def start(self):
		print "Started polling zigBee sensors"
		self._addPollingProcessor('zigBee', self.pollZigbeeSensors, None, 0.0001)

	def stop(self):
		print "Stopped polling zigBee sensors"
		self._removePollingProcessor('zigBee')
		
	# ZigBee thread main loop
	def pollZigbeeSensors(self):
		try:
			data, _ = self.sock.recvfrom(10240, 0)
		except Exception as e:
			if type(e) != timeout:
				print e
			return

		(_, mac, channel, val) = data.split(' ')

		mac = mac.lower()
		channel = channel.upper()
		
		try:
			sensor = next(s for s in self._sensors if s['ChannelDescriptor'] == str(mac) + str(channel))
		except StopIteration:
			#Only warn once, or we'll flood the console
			if str(mac) + str(channel) not in self._warned:
				print >> sys.stderr, "Warning: Unable to locate sensor record for zigbee sensor ID: %s" % (str(mac) + str(channel))
				self._warned.append(str(mac) + str(channel))
			return

		_device = sensor['locationName']
		_pin = sensor['name']
		_id = sensor['sensorId']

		if val != '-' and val != '':
			_type = sensor['sensorTypeName']
			_uuid = '%s_%s' % (mac , channel)
			if _type == 'TEMPERATURE_MCP9700_HOT' or _type == 'TEMPERATURE_MCP9700_COLD':
				_value = str((float( val) - 0.5) * 100.0)
			else:
				_value = val
			
			_status = self._sr.getDisplayState({'sensorTypeName': _type, 'value': _value, 'sensorId': _id })

			self._channels[_uuid] = { 
									'id': _id, 
									'room': _device, 
									'channel': _pin, 
									'value': _value, 
									'status': _status
									}
Esempio n. 15
0
 def __init__(self):
     self._dao = Sensors()
     self._sr = StateResolver()
Esempio n. 16
0
class ZWaveVeraLite(PollingProcessor):

	# Initialisation method
	# Opens the configured UDP socket for the receipt of broadcast messages.
	def __init__ (self, ipAddress, port):
		super(ZWaveVeraLite, self).__init__()
		
		self._loadTime = None
		self._dataVersion = None
		self._baseUrl = "http://%(ip)s:%(port)s/data_request?id=lu_sdata&timeout=%(timeout)s" % {'ip': ipAddress, 'port': port, 'timeout': 60}

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []

	@property
	def channels(self):
		if self._channels == None:
			self._channels = {}
		
		return self._channels

	def start(self):
		print "Started polling zwave sensors"
		self._addPollingProcessor('zwave', self.pollZWaveSensors, None, 0.1)

	def stop(self):
		print "Stopped polling zwave sensors"
		self._removePollingProcessor('zwave')
		
	# ZigBee thread main loop
	def pollZWaveSensors(self):
		try:
			# http://192.168.1.158:3480/data_request?id=lu_sdata
			# http://192.168.1.158:3480/data_request?id=lu_sdata&loadtime=1282441735&dataversion=441736333&timeout=60
			url = self._baseUrl
			if self._loadTime != None and self._dataVersion != None:
				url += '&loadtime=%(load)s&dataversion=(dataversion)s' % {'load': self._loadTime, 'dataversion': self._dataVersion }
			data = json.load(urllib2.urlopen(url)) 
		except Exception as e:
			if type(e) != timeout:
				print e
			return
		
		self._loadTime = data['loadtime']
		self._dataVersion = data['dataversion']
		
		for device in data['devices']:
			channelDescriptor = 'zwave:' + str(device['id'])
			try:
				sensor = next(s for s in self._sensors if s['ChannelDescriptor'] == channelDescriptor)
			except StopIteration:
				# Only warn once, or we'll flood the console
				if channelDescriptor not in self._warned:
					print >> sys.stderr, "Warning: Unable to locate sensor record for zwave sensor ID: %s (%s)" % (str(channelDescriptor), str(device['name']))
					self._warned.append(channelDescriptor)
				continue
	
			_device = sensor['locationName']
			_pin = sensor['name']
			_id = sensor['sensorId']

			valueKeys = ['armed', 'status']

			val = ''
			for valueKey in valueKeys:
				if device.has_key(valueKey):
					val = device[valueKey]
					break
	
			if val != '-' and val != '':
				_type = sensor['sensorTypeName']
				_uuid = channelDescriptor
				if _type == 'TEMPERATURE_MCP9700_HOT' or _type == 'TEMPERATURE_MCP9700_COLD':
					_value = str((float(val) - 0.5) * 100.0)
				else:
					_value = val
				
				_status = self._sr.getDisplayState({'sensorTypeName': _type, 'value': _value, 'sensorId': _id })
	
				self._channels[_uuid] = { 
										'id': _id,
										'room': _device,
										'channel': _pin,
										'value': _value,
										'status': _status
										}
Esempio n. 17
0
class ZWaveHomeController(PollingProcessor):

	# Initialisation method
	# Opens the configured UDP socket for the receipt of broadcast messages.
	def __init__ (self, ipAddress):
		super(ZWaveHomeController, self).__init__()
		
		self._baseUrl = "http://%(ip)s:80/api/devices" % {'ip': ipAddress}

		# Place for the callback methods to store "static" values.
		# Currently only needed for the Moving Average Filter for the MCP9700
		# temperature sensor temperature calculations.
		self._handler_memory = {}
		self._channels = {}
		self._sr = StateResolver()
		self._sensorDao = Sensors()
		self._sensors = self._sensorDao.findSensors()
		self._warned = []

	@property
	def channels(self):
		if self._channels == None:
			self._channels = {}
		
		return self._channels

	def start(self):
		print "Started polling zwave sensors"
		self._addPollingProcessor('zwave', self.pollZWaveSensors, None, 0.1)

	def stop(self):
		print "Stopped polling zwave sensors"
		self._removePollingProcessor('zwave')
		
	def pollZWaveSensors(self):
		try:
			# http://192.168.1.109/devices
			url = self._baseUrl
			request = urllib2.Request(url)
			base64string = base64.encodestring('%s:%s' % ('admin', 'admin')).replace('\n', '')
			request.add_header("Authorization", "Basic %s" % base64string)
			result = urllib2.urlopen(request)
			data = json.load(result) 
		except Exception as e:
			if type(e) != timeout:
				print e
			return
		
		for device in data:
			channelDescriptor = 'zwave:' + str(device['id'])
			try:
				sensor = next(s for s in self._sensors if s['ChannelDescriptor'] == channelDescriptor)
			except StopIteration:
				# Only warn once, or we'll flood the console
				if channelDescriptor not in self._warned:
					print >> sys.stderr, "Warning: Unable to locate sensor record for zwave sensor ID: %s (%s)" % (str(channelDescriptor), str(device['name']))
					self._warned.append(channelDescriptor)
				continue
	
			_device = sensor['locationName']
			_pin = sensor['name']
			_id = sensor['sensorId']
	
			# order determines priority
			valueKeys = ['valueSensor', 'value']
			
			val = ''
			for valueKey in valueKeys:
				if device['properties'].has_key(valueKey):
					val = device['properties'][valueKey]
					break
	
			if val != '-' and val != '':
				_type = sensor['sensorTypeName']
				_uuid = channelDescriptor
				if _type == 'TEMPERATURE_MCP9700_HOT' or _type == 'TEMPERATURE_MCP9700_COLD':
					_value = str((float(val) - 0.5) * 100.0)
				else:
					_value = val
				
				_status = self._sr.getDisplayState({'sensorTypeName': _type, 'value': _value, 'sensorId': _id })
	
				self._channels[_uuid] = { 
										'id': _id,
										'room': _device,
										'channel': _pin,
										'value': _value,
										'status': _status
										}