Example #1
0
    def __init__(self):
        self.version = 0
        self.hwVersion = None
        self.devices = []
        self.sensors = []
        self.rawEnabled = False
        self.rawEnabledAt = 0
        self.dev = Adapter(self, Board.rf433Port())
        deviceNode = DeviceNode(self.dev)
        self.deviceManager = DeviceManager(self.context)
        for d in self.deviceManager.retrieveDevices('433'):
            p = d.params()
            if 'type' not in p:
                continue
            if p['type'] == 'sensor':
                device = SensorNode()
                self.sensors.append(device)
            elif p['type'] == 'device':
                device = DeviceNode(self.dev)
                self.devices.append(device)
            else:
                continue
            device.setNodeId(d.id())
            device.setParams(p)
            self.deviceManager.addDevice(device)

        self.deviceManager.finishedLoading('433')
        self.dev.queue(
            RF433Msg('V', success=self.__version, failure=self.__noVersion))
        self.dev.queue(
            RF433Msg('H', success=self.__hwVersion,
                     failure=self.__noHWVersion))
        self.live = TelldusLive(self.context)
Example #2
0
 def __init__(self, webKitDir=webKitDir):
     Adapter.__init__(self, webKitDir)
     if sys.platform == 'win32':
         import msvcrt
         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
     # Get Host and Port information for WebKit AppServer
     (self.host, self.port) = open(os.path.join(self._webKitDir, 'adapter.address')).read().split(':')
     self.port = int(self.port)
Example #3
0
	def __init__(self, webkitdir):
		Adapter.__init__(self, webkitdir)
		if sys.platform == 'win32':
			import msvcrt
			msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
			msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)		

		# Get Host and Port information for WebKit AppServer
		(self.host, self.port) = string.split(open(os.path.join(self._webKitDir, 'address.text')).read(), ':')
		self.port = int(self.port)
Example #4
0
 def list_adapters(self):
     if self.__class__.get_interface_version()[0] < 5:
         adapters = self.get_interface().ListAdapters()
         return [Adapter(adapter) for adapter in adapters]
     else:
         objects = self.get_interface().GetManagedObjects()
         adapters = []
         for path, interfaces in objects.items():
             if 'org.bluez.Adapter1' in interfaces:
                 adapters.append(path)
         return [Adapter(adapter) for adapter in adapters]
Example #5
0
 def __init__(self, searchString, category, maxEntries):
     """
     Initialize the RarBg adapter
     """
     Adapter.__init__(self, searchString, category, maxEntries)
     self._logger = logging.getLogger(__name__)
     self._defHeaders = {
         'accept': '''text/html,application/xhtml+xml,application/xml;q=0.9,
         image/webp,*/*;q=0.8''',
         'accept-encoding': 'deflate',
         'accept-language': 'en-US,en;q=0.8',
         'user-agent': '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36
         (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'''}
Example #6
0
 def __init__(self, searchString, category, maxEntries):
     """
     Initialize the RarBg adapter
     """
     Adapter.__init__(self, searchString, category, maxEntries)
     self._logger = logging.getLogger(__name__)
     self._defHeaders = {
         'accept':
         '''text/html,application/xhtml+xml,application/xml;q=0.9,
         image/webp,*/*;q=0.8''',
         'accept-encoding':
         'deflate',
         'accept-language':
         'en-US,en;q=0.8',
         'user-agent':
         '''Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36
         (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'''
     }
Example #7
0
	def __init__(self):
		self.version = 0
		self.hwVersion = None
		self.devices = []
		self.sensors = []
		self.rawEnabled = False
		self.rawEnabledAt = 0
		self.dev = Adapter(self, Board.rf433Port())
		deviceNode = DeviceNode(self.dev)
		self.deviceManager = DeviceManager(self.context)
		self.registerSensorCleanup()
		for d in self.deviceManager.retrieveDevices('433'):
			p = d.params()
			if 'type' not in p:
				continue
			if p['type'] == 'sensor':
				device = SensorNode()
				self.sensors.append(device)
			elif p['type'] == 'device':
				device = DeviceNode(self.dev)
				self.devices.append(device)
			else:
				continue
			device.setNodeId(d.id())
			device.setParams(p)
			if p['type'] == 'sensor':
				device._packageCount = 7  # already loaded, keep it that way!
				device._sensorValues = d._sensorValues
				device.batteryLevel = d.batteryLevel
				if hasattr(d, 'declaredDead'):
					device.declaredDead = d.declaredDead

			self.deviceManager.addDevice(device)

		self.deviceManager.finishedLoading('433')
		self.dev.queue(RF433Msg('V', success=self.__version, failure=self.__noVersion))
		self.dev.queue(RF433Msg('H', success=self.__hwVersion, failure=self.__noHWVersion))
		self.live = TelldusLive(self.context)
Example #8
0
from flask import Flask
from flask import request
from Adapter import Adapter
from InOutput import InOutput

app = Flask(__name__)

io = InOutput()
df_json_adapter = Adapter(io)


@app.route('/personal_data', methods=['POST'])
def personal_data():
    patientid = request.values.get('patientid')
    return str(
        df_json_adapter.handle_instructions("get_personal_info", patientid))


@app.route('/icd_card', methods=['POST'])
def icd_card():
    patientid = request.values.get('patientid')
    return str(
        df_json_adapter.handle_instructions("get_icd_category_growth_trend",
                                            patientid))


@app.route('/inpatient', methods=['POST'])
def inpatient():
    patientid = request.values.get('patientid')
    return str(
        df_json_adapter.handle_instructions("get_personal_inpatient_cycle",
Example #9
0
 def __init__(self, host, port, webKitDir):
     Adapter.__init__(self, webKitDir)
     self.host = host
     self.port = port
Example #10
0
class RF433(Plugin):
    implements(ITelldusLiveObserver)

    fwVersions = {'18F25K50': 1}

    def __init__(self):
        self.version = 0
        self.hwVersion = None
        self.devices = []
        self.sensors = []
        self.rawEnabled = False
        self.rawEnabledAt = 0
        self.dev = Adapter(self, Board.rf433Port())
        deviceNode = DeviceNode(self.dev)
        self.deviceManager = DeviceManager(self.context)
        self.registerSensorCleanup()
        for d in self.deviceManager.retrieveDevices('433'):
            p = d.params()
            if 'type' not in p:
                continue
            if p['type'] == 'sensor':
                device = SensorNode()
                self.sensors.append(device)
            elif p['type'] == 'device':
                device = DeviceNode(self.dev)
                self.devices.append(device)
            else:
                continue
            device.setNodeId(d.id())
            device.setParams(p)
            if p['type'] == 'sensor':
                device._packageCount = 7  # already loaded, keep it that way!
                device._sensorValues = d._sensorValues
                device.batteryLevel = d.batteryLevel

            self.deviceManager.addDevice(device)

        self.deviceManager.finishedLoading('433')
        self.dev.queue(
            RF433Msg('V', success=self.__version, failure=self.__noVersion))
        self.dev.queue(
            RF433Msg('H', success=self.__hwVersion,
                     failure=self.__noHWVersion))
        self.live = TelldusLive(self.context)

    def addDevice(self, protocol, model, name, params):
        device = DeviceNode(self.dev)
        device.setName(name)
        device.setParams({
            'protocol': protocol,
            'model': model,
            'protocolParams': params
        })
        self.devices.append(device)
        self.deviceManager.addDevice(device)

    def cleanupSensors(self):
        numberOfSensorsBefore = len(self.sensors)
        for i, sensor in enumerate(self.sensors):
            if not sensor.isValid():
                self.deviceManager.removeDevice(sensor.id())
                del self.sensors[i]

        self.deviceManager.sensorsUpdated()

    @TelldusLive.handler('rf433')
    def __handleCommand(self, msg):
        data = msg.argument(0).toNative()
        action = data['action']
        if action == 'addDevice':
            self.addDevice(data['protocol'], data['model'], data['name'],
                           data['parameters'])

        elif action == 'deviceInfo':
            deviceId = data['device']
            for device in self.devices:
                if device.id() == deviceId:
                    params = device.params()
                    params['deviceId'] = deviceId
                    self.live.pushToWeb('rf433', 'deviceInfo', params)
                    return

        elif action == 'editDevice':
            deviceId = data['device']
            for device in self.devices:
                if device.id() == deviceId:
                    device.setParams({
                        'protocol': data['protocol'],
                        'model': data['model'],
                        'protocolParams': data['parameters']
                    })
                    device.paramUpdated('')
                    break

        elif action == 'remove':
            deviceId = data['device']
            for device in self.devices:
                if device.id() == deviceId:
                    self.deviceManager.removeDevice(deviceId)
                    self.devices.remove(device)
                    return

        elif action == 'rawEnabled':
            if data['value']:
                self.rawEnabled = True
                self.rawEnabledAt = time.time()
            else:
                self.rawEnabled = False

        else:
            logging.warning("Unknown rf433 command %s", action)

    @signal('rf433RawData')
    def decode(self, msg):
        """
		Signal send on any raw data received from 433 receiver. Please note that
		the TellStick must contain a receiver for this signal to be sent. Not all
		models contains a receiver.
		"""
        if 'class' in msg and msg['class'] == 'sensor':
            self.decodeSensor(msg)
            return
        msg = Protocol.decodeData(msg)
        for m in msg:
            self.decodeCommandData(m)
            if self.rawEnabled:
                if self.rawEnabledAt < (time.time() - 600):
                    # timeout, only allow scan for 10 minutes at a time
                    self.rawEnabled = False
                    continue
                self.live.pushToWeb('client', 'rawData', m)

    def decodeCommandData(self, msg):
        protocol = msg['protocol']
        model = msg['model']
        method = msg['method']
        methods = Protocol.methodsForProtocol(protocol, model)
        if not method & methods:
            return
        for device in self.devices:
            params = device.params()
            if params['protocol'] != protocol:
                continue
            if not method & device.methods():
                continue
            deviceParams = params['protocolParams']
            thisDevice = True
            for parameter in Protocol.parametersForProtocol(protocol, model):
                if parameter not in msg:
                    thisDevice = False
                    break
                if parameter not in deviceParams:
                    thisDevice = False
                    break
                if msg[parameter] != deviceParams[parameter]:
                    thisDevice = False
                    break
            if thisDevice:
                device.setState(method, None)

    def decodeData(self, cmd, params):
        if cmd == 'W':
            self.decode(params)
        elif cmd == 'V':
            # New version received, probably after firmware upload
            self.__version(params)
        else:
            logging.debug("Unknown data: %s", str(cmd))

    def decodeSensor(self, msg):
        protocol = Protocol.protocolInstance(msg['protocol'])
        if not protocol:
            logging.error("No known protocol for %s", msg['protocol'])
            return
        data = protocol.decodeData(msg)
        if not data:
            return
        p = data['protocol']
        m = data['model']
        sensorId = data['id']
        sensorData = data['values']
        sensor = None
        for s in self.sensors:
            if s.compare(p, m, sensorId):
                sensor = s
                break
        if sensor is None:
            sensor = SensorNode()
            sensor.setParams({'protocol': p, 'model': m, 'sensorId': sensorId})
            sensor.setManager(self.deviceManager)
            self.sensors.append(sensor)
        if 'battery' in data:
            sensor.batteryLevel = data['battery']
        sensor.updateValues(sensorData)

    """ Register scheduled job to clean up sensors that have not been updated for a while"""

    def registerSensorCleanup(self):
        Application().registerScheduledTask(self.cleanupSensors,
                                            hours=12)  # every 12th hour
        t = Timer(10, self.cleanupSensors)  # run a first time after 10 minutes
        t.daemon = True
        t.name = 'Sensor cleanup'
        t.start()

    def __noVersion(self):
        logging.warning(
            "Could not get firmware version for RF433, force upgrade")

    def __noHWVersion(self):
        logging.warning("Could not get hw version for RF433")

    def __hwVersion(self, version):
        logging.debug("Got HW version %s", version)
        self.hwVersion = version
        if version not in RF433.fwVersions:
            return
        fwVersion = RF433.fwVersions[self.hwVersion]
        if fwVersion != self.version:
            logging.info("Version %i is to old, update firmware", self.version)
            # TODO: implement

    def __version(self, version):
        self.version = version
        logging.info("RF433 version: %i", self.version)
Example #11
0
 def __init__(self):
     Adapter.__init__(self)
        def receive_wrapper(transport_impl, target_method, data, client_address):

            lock.acquire()
            workflow = None
            logger = logging.getLogger('Transport: Handle Message')
            exc_info = None
            if Transport.serialization == Transport.JSON:
                packed = JSON.deserialize(data)
            else:
                packed = Pickle.deserialize(data)

            args = packed[0]
            kwargs = packed[1]

            if hasattr(transport_impl, 'workflow'):
                workflow = transport_impl.workflow

                # Complicated ... if this method has default arguments, add these to the method but add them first
                # so that the new values can override the old ones.

            node = None
            if workflow is not None:
                node = transport_impl.workflow.get_my_node(transport_impl)
                node_name = node.unique_name

                #print "Transport receive at node " + node_name + " coming from " + client_address

                input_port = workflow.get_my_input_port(transport_impl)

                if input_port.args is not None:
                    args = [i for sub in input_port.args for i in sub]
                    #args = input_port.args + args

                if input_port.kwargs is not None:
                    kwargs= dict(Transport.combine_dictionaries(input_port.kwargs, kwargs))


            # This should have worked but I get the error:
            # TypeError: def_sensor() got multiple values for keyword argument 'mean' even though the dictionaries are
            # identical

            logger.debug("In Decorated Receiver, receiving " + str(args) + " AND " + str(kwargs) + " using " +
                         transport_impl.__class__.__name__)
            logger.debug("Sending to Method " + str(target_method))

            try:
                logger.debug("Executing method " + str(target_method) + " using:")
                logger.debug ("Args = " + str(args))
                logger.debug ("Kwargs = " + str(kwargs))

                # There is always a node for a workflow
                if node is not None:
                    return_values = target_method(node, *args, **kwargs)
                else:
                    return_values = target_method(transport_impl, *args, **kwargs)

                # Once we execute the method, we now send the data from this node's ports to the other
                # nodes it is connected to
                # Kwargs = {'mean': 2.0, 'dev': 0.5, 's_secs': 10, 'dataset': 'seismic'} worked when called
                # Kwargs = {'dataset': 'seismic', 's_secs': 10, 'dev': 0.4171342709488157, 'mean': 2.117} did not

                if workflow is not None:
                    logger.debug("Looking at which output ports need activating")

                    output_ports = node.get_output_ports()

                    for port in output_ports:
                        logger.debug("Looking at port with bind add: " + port.bind_address + ", port: " + str(port.bind_port))
                        if port.enabled is True: # is the port enabled for sending or was it disabled by the method?
                            logger.debug("Port " + str(port.port_id) + " is enabled !! ")
                            edge = workflow.get_edge_for_port(port.port_id)

                            from Adapter import Adapter
                            sender_adapter = Adapter(edge.transport, edge.serialization, workflow)
                            sender = sender_adapter.get_sender_instance(port.bind_address, port.bind_port,
                                                                        edge.get_receiver_address(),
                                                                        edge.get_receiver_port())
                            port.bind_address = sender.bind_address
                            port.bind_port = sender.bind_port

                            node = workflow.get_node_for_port(port)

                            args = port.args
                            kwargs = port.kwargs
                            Transport.parse_arguments_and_send(sender, node, return_values, *args, **kwargs)

            except Exception as inst:
                import sys
                exc_info = sys.exc_info()
                print "ERROR OF TYPE: " + str(type(inst))     # the exception instance
                print "Details: " + str(inst)
            finally:
                # Display the *original* exception
                if exc_info is not None:
                    import traceback
                    traceback.print_exception(*exc_info)
                    del exc_info

            lock.release()
Example #13
0
 def __init__(self, host, port, webKitDir):
     Adapter.__init__(self, webKitDir)
     self.host = host
     self.port = port
Example #14
0
@app.route('/', methods=['GET', 'POST'])
def all_categories():
    return jsonify({"about": 'Hello World!'})


@app.route('/transaction_fraud_detection', methods=['GET', 'POST'])
def predict_transaction():
    if (request.method == 'POST'):
        transaction = adapter.read_data_andparse_to_df(request)
        transaction = fraud_detection.prepare_data(transaction)
        return fraud_detection.prediction(transaction)


@app.route('/transactions_fraud_detection', methods=['GET', 'POST'])
def predict_transactions():
    if (request.method == 'POST'):
        result = {}
        predictions = []
        transactions = adapter.read_data_andparse_to_dfs(request)
        for elem in transactions:
            transaction = fraud_detection.prepare_data(elem)
            predictions.append(fraud_detection.prediction(transaction))
        result['predictions'] = predictions
        return json.dumps(result)


if __name__ == '__main__':

    adapter = Adapter()
    fraud_detection = Fraud_detection()
    app.run(host='0.0.0.0', debug=False)
Example #15
0
from Adapter import Adapter

if __name__ == "__main__":
    '''
    for some reason we cannot use the original Adaptee interface, instead, we
    must have getters and setters for each attribute. To solve this, we use the
    Adapter Design Pattern to create a new interface (Adapter) that fulfills our
    requirements
    '''

    print("Starting Testing")

    person1 = Adapter("Rogelio", 25, "blue")
    person2 = Adapter("Adelaide", 43, "green")
    person3 = Adapter("Jonathan", 5, "brown")

    assert (person1.get_name() == "Rogelio")
    assert (person2.get_age() == 43)
    assert (person3.get_eye_color() == "brown")

    assert (person2.adaptee != None)

    print("Changing Attributes")

    person1.set_age(26)
    person2.set_name("Andrew")
    person3.set_eye_color("violet")

    assert (person1.get_age() == 26)
    assert (person1.get_eye_color() == "blue")
    assert (person2.get_name() == "Andrew")