Esempio n. 1
0
def test_remote_web(cfx_master, cfx_edge1, transport_config=None):

    mrealm = 'mrealm1'

    worker_id = 'worker1'
    worker_type = 'router'
    transport_id = 'transport1'

    management_session, _ = yield functest_management_session(realm=mrealm)
    yield sleep(.1)

    node_oids = yield management_session.call(
        'crossbarfabriccenter.mrealm.get_nodes')
    assert node_oids
    node_id = node_oids[0]

    result = yield management_session.call(
        'crossbarfabriccenter.remote.node.start_worker', node_id, worker_id,
        worker_type)
    print(hl(result, bold=True))
    yield sleep(.1)

    if not transport_config:
        transport_config = {
            "type": "web",
            "endpoint": {
                "type": "tcp",
                "port": 8080
            },
            "paths": {
                "/": {
                    "type": "nodeinfo"
                }
            }
        }

    result = yield management_session.call(
        'crossbarfabriccenter.remote.router.start_router_transport', node_id,
        worker_id, transport_id, transport_config)
    print(hl(result, bold=True))
    yield sleep(.1)

    response = yield treq.get('http://localhost:8080')
    result = yield response.text()
    assert '<title>Crossbar.io application router</title>' in result
    assert '<td>Node Started</td>' in result
    print(hl(result[:80], color='green', bold=True))

    result = yield management_session.call(
        'crossbarfabriccenter.remote.router.stop_router_transport', node_id,
        worker_id, transport_id)
    print(hl(result, bold=True))
    yield sleep(.1)

    result = yield management_session.call(
        'crossbarfabriccenter.remote.node.stop_worker', node_id, worker_id)
    print(hl(result, bold=True))
    yield sleep(.1)

    yield management_session.leave()
Esempio n. 2
0
def test_remote_container(cfx_master, cfx_edge1):
    mrealm = 'mrealm1'
    management_session, _ = yield functest_management_session(realm=mrealm)
    yield sleep(.1)

    # yield _prepare(management_session, mrealm)
    # yield sleep(.1)

    node_oids = yield management_session.call(
        'crossbarfabriccenter.mrealm.get_nodes')
    assert node_oids
    node_id = node_oids[0]

    worker_id = 'worker1'
    worker_type = 'container'
    result = yield management_session.call(
        'crossbarfabriccenter.remote.node.start_worker', node_id, worker_id,
        worker_type)
    print(hl(result, bold=True))
    yield sleep(.1)

    result = yield management_session.call(
        'crossbarfabriccenter.remote.node.stop_worker', node_id, worker_id)
    print(hl(result, bold=True))
    yield sleep(.1)

    yield management_session.leave()
Esempio n. 3
0
 def flash(self, delay=50, repeat=5):
     delay = float(delay) / 1000.
     for i in range(repeat):
         self.set_color(0xe1, 0xda, 0x05)
         yield sleep(2 * delay)
         self.set_color(0x52, 0x42, 0x00)
         yield sleep(delay)
Esempio n. 4
0
    def onJoin(self, details):
        print("session attached {}".format(details))
        counter = 0
        while True:
            counter += 1

            pub = yield self.publish('event.foo.{}'.format(counter),
                                     "some data")
            print("published {}".format(pub))
            yield sleep(1)

            sub = yield self.subscribe(lambda: None,
                                       'event.sub_{}'.format(counter))
            print("subscribed {sub.id}".format(sub=sub))
            yield sleep(1)

            reg = yield self.register(lambda: 42,
                                      'event.rpc.test_{}'.format(counter))
            print("registered {reg.id}".format(reg=reg))
            yield sleep(1)

            call = yield self.call('event.rpc.test_{}'.format(counter))
            print("called {}".format(call))
            yield sleep(1)

            yield reg.unregister()
            yield sub.unsubscribe()
    def onJoin(self, details):
        # barChart is the function name
        # _id is the topic id
        # title is the title
        # if function name == __all__ then unsubscribe to all
        yield self.publish('com.example.data',
                           'barChart',
                           oneTime=True,
                           _id=self._id,
                           title=self.title)
        yield sleep(3)
        # yield self.publish('com.example.data', 'barChart', data='hello', block=0, delay=0.01, oneTime=False, _id=self._id, add=True)

        docs = [['Element', 'Density'], ["Copper", 8.94], ["Silver", 10.49],
                ["Gold", 19.30], ["Platinum", 21.45]]

        # docs = yield getDataOfTowers(self.mongo)

        for doc in docs:
            yield self.publish('com.example.data',
                               'barChart',
                               data=doc,
                               block=0,
                               delay=0.01,
                               oneTime=False,
                               _id=self._id,
                               add=True)
            yield sleep(0.01)
    def on_face_detected(self, frame):
        self.logger.info("Face detected: {}".format(frame))
        try:
            if frame is None or len(frame) == 0:
                yield sleep(1)
            else:
                detected_face = frame["data"]["body"]
                # skip empty frames
                if detected_face and len(detected_face) > 0:
                    # check face size
                    face_size = frame["data"]["body"][0][2]
                    self.detected_faces_lst.append(face_size)
                    # > x seconds: notify observers
                    detection_interval = time.time() - self.last_time_detected
                    if detection_interval >= self.notification_interval:
                        self.logger.info("Detected a face: {} | after {}s".format(frame["data"],
                                                                                  detection_interval))
                        self.last_time_detected = time.time()
                        face_size = max(self.detected_faces_lst)
                        self.detected_faces_lst = []
                        self.face_detected_observers.notify_all(face_size)

                    yield sleep(1)
                else:
                    yield sleep(1)
        except Exception as e:
            self.logger.error("Error while receiving the detected face: {}".format(e))
            yield sleep(1)
Esempio n. 7
0
 def flash(self, delay=50, repeat=5):
     delay = float(delay) / 1000.
     for i in range(repeat):
         self.set_color(0xe1, 0xda, 0x05)
         yield sleep(2 * delay)
         self.set_color(0x52, 0x42, 0x00)
         yield sleep(delay)
Esempio n. 8
0
 def flash(self, r=255, g=255, b=255, delay=25, repeat=10):
     delay = float(delay) / 1000.
     for i in range(repeat):
         self.set_color(r, g, b)
         yield sleep(2 * delay)
         self.set_color(0, 0, 0)
         yield sleep(delay)
Esempio n. 9
0
    def connectToStream(self, auth):
        printNicely("-- Connecting to Stream --")
        stream = TwitterStream(auth = auth, secure = True, timeout = 20, heartbeat_timeout = 90)
        tweet_iter = stream.statuses.filter(track = "love")

       # while True:
        #    print(".")
         #   self.publish('com.myapp.heartbeat')
          #  yield sleep(1)

        for tweet in tweet_iter:
            # check whether this is a valid tweet
            if tweet is None:
                printNicely("-- None --")
                return
            elif tweet is Timeout:
                printNicely("-- Timeout --")
                sleep(5);
                return
            elif tweet is HeartbeatTimeout:
                printNicely("-- Heartbeat Timeout --")
                return
            elif tweet is Hangup:
                printNicely("-- Hangup --")
                return
            elif tweet.get('text'):
            #   obj = {'text': tweet["text"], 'user': tweet["user"]["screen_name"]}
                obj = {'text': tweet["text"]}
                yield obj
Esempio n. 10
0
    def interrupt(self, last=None):
        if self.client.current_client:
            yield self.client.current_client.shutdown()
            yield sleep(0.05)

            if self.client.current_task and self.client.current_task.wait:
                self.client.current_task.wait.cancel()
                yield sleep(0.05)
Esempio n. 11
0
 def flash(self, delay=50, repeat=5):
     self.log.info('flash animation starting ..')
     delay = float(delay) / 1000.
     for i in range(repeat):
         self.set_color(0xff, 0xff, 0xff)
         yield sleep(2 * delay)
         self.set_color(0x00, 0x00, 0x00)
         yield sleep(delay)
Esempio n. 12
0
 def longop(n, details = None):
    if details.progress:
       for i in range(n):
          details.progress(i)
          yield sleep(1)
    else:
       yield sleep(1 * n)
    returnValue(n)
Esempio n. 13
0
 def longop(n, details=None):
     if details.progress:
         for i in range(n):
             details.progress(i)
             yield sleep(1)
     else:
         yield sleep(1 * n)
     returnValue(n)
Esempio n. 14
0
    def interrupt(self, last=None):
        if self.client.current_client:
            yield self.client.current_client.shutdown()
            yield sleep(0.05)

            if self.client.current_task and self.client.current_task.wait:
                self.client.current_task.wait.cancel()
                yield sleep(0.05)
Esempio n. 15
0
def test_sigint_router(reactor, request, virtualenv, temp_dir):
    '''
    Test-case for #278.

    Variation 1: just Router (subprocess) gets SIGINT
    '''

    config = {
        "version": 2,
        "controller": {},
        "workers": [{
            "id": "testee",
            "type": "router",
            "transports": []
        }]
    }

    cbdir = temp_dir
    cb = yield start_crossbar(reactor,
                              virtualenv,
                              cbdir,
                              config,
                              log_level='debug')
    myproc = psutil.Process(cb.transport.pid)

    def cleanup():
        try:
            myproc.send_signal(signal.SIGKILL)
        except psutil.NoSuchProcess:
            pass
        pytest.blockon(sleep(1))

    request.addfinalizer(cleanup)

    yield sleep(15)
    print("Crossbar started, sending SIGINT")

    # find the NodeController worker; should be the only subprocess of
    # our crossbar.
    children = myproc.children()
    assert len(children) == 1

    # kill JUST the Router child.
    children[0].send_signal(signal.SIGINT)
    yield sleep(1)

    sigints = 0
    errors = []
    for line in cb.logs.getvalue().split('\n'):
        if 'SIGINT' in line:
            sigints += 1
        if 'Failure: ' in line:
            errors.append(line)

    assert sigints == 1, "Wanted precisely one SIGINT"
    # XXX the controller/crossbar are still running here; should they
    # in turn die if their Router process has gone away?
    assert len(errors) == 0, '\n'.join(errors)
Esempio n. 16
0
def test_sigint_controller_and_router(reactor, request, virtualenv, temp_dir):
    '''
    Test-case for #278.

    Variation 3: crossbar AND the Router subprocess both get SIGINT at "same time"
    '''

    config = {
        "version": 2,
        "controller": {},
        "workers": [{
            "id": "testee",
            "type": "router",
            "transports": []
        }]
    }

    cb = yield start_crossbar(reactor,
                              virtualenv,
                              temp_dir,
                              config,
                              log_level='debug')
    myproc = psutil.Process(cb.transport.pid)

    def cleanup():
        try:
            myproc.send_signal(signal.SIGKILL)
        except psutil.NoSuchProcess:
            pass
        pytest.blockon(sleep(1))

    request.addfinalizer(cleanup)

    yield sleep(15)
    # print("Crossbar started, sending SIGINT")

    children = myproc.children()
    assert len(children) == 1

    assert myproc.is_running()
    assert children[0].is_running()

    children[0].send_signal(signal.SIGINT)
    myproc.send_signal(signal.SIGINT)
    yield sleep(1)

    sigints = 0
    errors = []
    for line in cb.logs.getvalue().split('\n'):
        if 'SIGINT' in line:
            sigints += 1
        if 'Failure: ' in line:
            errors.append(line)

    assert sigints >= 1, "Wanted at least one SIGINT"
    assert not myproc.is_running()
    assert len(errors) == 0, '\n'.join(errors)
Esempio n. 17
0
	def onJoin(self, details):

		namespace = self.app_config['namespace']
		do_raw = self.app_config['raw'].lower()=='true'

		firebase_server = firebase.FirebaseApplication('https://amber-fire-3917.firebaseio.com')

		def send(key,d):
			return self.publish(namespace+u'.queue.'+key,d) and 1 or 0

		def blink(d):
			return send('blink',d['blinkStrength'])

		def data(d):
			return send('data',
				[d['eSense']['attention']
				,d['eSense']['meditation']
				,d['eegPower']['lowAlpha']
				,d['eegPower']['highAlpha']
				,d['eegPower']['lowBeta']
				,d['eegPower']['highBeta']
				,d['eegPower']['lowGamma']
				,d['eegPower']['highGamma']
				,d['eegPower']['delta']
				,d['eegPower']['theta']
				])

		def raw(d):
			return send('raw',d['rawEeg'])

		def sendany(d):
			print(d)
			if 'blinkStrength' in d:
				return blink(d)
			if 'eegPower' in d:
				return data(d)
			if 'rawEeg' in d:
				return raw(d)
			return None

		if self.app_config['debug'].lower()=='true':
			print('debug mode.')
			counter = 0
			while True:
				send('debug', counter)
				#print("Published event.")
				counter += 1
				yield sleep(1)
		else:
			tn = Telnet('localhost',13854)
			tn.write('{"enableRawOutput": %s, "format": "Json"}' % (['false','true'][do_raw],))
			i = tn.read_until('\r')
			while True:
				# ret = sendany(json.loads(tn.read_until('\r')))
				firebase_server.post('/mindwave', json.loads(tn.read_until('\r')))
				yield sleep(0.001)
Esempio n. 18
0
 def longop(n, details=None):
     if details.progress:
         # caller can (and requested to) consume progressive results
         for i in range(n):
             details.progress(i)
             yield sleep(1)
     else:
         # process like a normal call (not producing progressive results)
         yield sleep(1 * n)
     returnValue(n)
 def longop(n, details=None):
     if details.progress:
         # caller can (and requested to) consume progressive results
         for i in range(n):
             details.progress(i)
             yield sleep(1)
     else:
         # process like a normal call (not producing progressive results)
         yield sleep(1 * n)
     returnValue(n)
Esempio n. 20
0
  def onJoin(self, details):
    yield self.InitSensors()
    yield sleep(1)

    t = 0
    while True:
      yield self.ReadSensors()
      #yield self.ReadDHT()
      #yield self.ReadWater()
      yield sleep(3)
Esempio n. 21
0
    def onJoin(self, details):

        namespace = self.app_config['namespace']
        do_raw = self.app_config['raw'].lower() == 'true'

        firebase_server = firebase.FirebaseApplication(
            'https://amber-fire-3917.firebaseio.com')

        def send(key, d):
            return self.publish(namespace + u'.queue.' + key, d) and 1 or 0

        def blink(d):
            return send('blink', d['blinkStrength'])

        def data(d):
            return send('data', [
                d['eSense']['attention'], d['eSense']['meditation'],
                d['eegPower']['lowAlpha'], d['eegPower']['highAlpha'],
                d['eegPower']['lowBeta'], d['eegPower']['highBeta'],
                d['eegPower']['lowGamma'], d['eegPower']['highGamma'],
                d['eegPower']['delta'], d['eegPower']['theta']
            ])

        def raw(d):
            return send('raw', d['rawEeg'])

        def sendany(d):
            print(d)
            if 'blinkStrength' in d:
                return blink(d)
            if 'eegPower' in d:
                return data(d)
            if 'rawEeg' in d:
                return raw(d)
            return None

        if self.app_config['debug'].lower() == 'true':
            print('debug mode.')
            counter = 0
            while True:
                send('debug', counter)
                #print("Published event.")
                counter += 1
                yield sleep(1)
        else:
            tn = Telnet('localhost', 13854)
            tn.write('{"enableRawOutput": %s, "format": "Json"}' %
                     (['false', 'true'][do_raw], ))
            i = tn.read_until('\r')
            while True:
                # ret = sendany(json.loads(tn.read_until('\r')))
                firebase_server.post('/mindwave',
                                     json.loads(tn.read_until('\r')))
                yield sleep(0.001)
Esempio n. 22
0
def test_sigint_controller(reactor, request, virtualenv, temp_dir):
    '''
    Test-case for #278.

    Variation 2: crossbar instance itself gets SIGINT
    '''

    config = {
        "version": 2,
        "controller": {},
        "workers": [{
            "id": "testee",
            "type": "router",
            "transports": []
        }]
    }

    cb = yield start_crossbar(reactor,
                              virtualenv,
                              temp_dir,
                              config,
                              log_level='debug')
    myproc = psutil.Process(cb.transport.pid)

    def cleanup():
        try:
            myproc.send_signal(signal.SIGKILL)
        except psutil.NoSuchProcess:
            pass
        pytest.blockon(sleep(1))

    request.addfinalizer(cleanup)

    print("Crossbar started, waiting")
    yield sleep(15)
    print("sending SIGINT")
    myproc.send_signal(signal.SIGINT)
    yield sleep(1)

    sigints = 0
    errors = []
    for line in cb.logs.getvalue().split('\n'):
        # note the logs don't actually emit anything about SIGINT any
        # longer...
        if 'SIGINT' in line:
            sigints += 1
        if 'Failure: ' in line:
            errors.append(line)


#    assert sigints >= 1, "Wanted at least one SIGINT"
    assert not myproc.is_running()
    assert len(errors) == 0, '\n'.join(errors)
Esempio n. 23
0
 def reconnector():
     while True:
         try:
             log.msg("Attempting to connect...")
             wampconnection = yield _bridge_runner.run(build_bridge_class(client), start_reactor=False)
             log.msg(wampconnection)
             yield sleep(10.0) # Give the connection time to set _session
             while wampconnection.isOpen():
                 yield sleep(5.0)
         except ConnectionRefusedError as ce:
             log.msg("ConnectionRefusedError: Trying to reconnect... ")
             yield sleep(1.0)
Esempio n. 24
0
 def reconnector():
     while True:
         try:
             log.msg("Attempting to connect...")
             wampconnection = yield _bridge_runner.run(
                 build_bridge_class(client), start_reactor=False)
             log.msg(wampconnection)
             yield sleep(10.0)  # Give the connection time to set _session
             while wampconnection.isOpen():
                 yield sleep(5.0)
         except ConnectionRefusedError as ce:
             log.msg("ConnectionRefusedError: Trying to reconnect... ")
             yield sleep(1.0)
Esempio n. 25
0
    def beep(self, count=None, on=None, off=None):
        """
        Trigger beeping sequence.

        :param count: Number of beeps.
        :type count: int

        :param on: ON duration in ms.
        :type on: int

        :param off: OFF duration in ms.
        :type off: int
        """
        # use default values
        count = count or 1
        on = on or 30
        off = off or 80

        # check types
        if type(count) not in six.integer_types:
            raise TypeError('"count" must be an integer')
        if type(on) not in six.integer_types:
            raise TypeError('"on" must be an integer')
        if type(off) not in six.integer_types:
            raise TypeError('"off" must be an integer')

        if self._is_beeping:
            raise ApplicationError(u'{}.already-beeping'.format(self._prefix),
                                   'currently already in a beeping sequence')

        # run the beeping sequence ..
        self.log.info(
            'start beeping sequence: count={count}, on={on}, off={off}',
            count=count,
            on=on,
            off=off)

        self._is_beeping = True
        self.publish(u'{}.on_beep_started'.format(self._prefix),
                     count=count,
                     on=on,
                     off=off)

        for i in range(count):
            GPIO.output(self._buzzer_pin, 1)
            yield sleep(float(on) / 1000.)
            GPIO.output(self._buzzer_pin, 0)
            yield sleep(float(off) / 1000.)

        self._is_beeping = False
        self.publish(u'{}.on_beep_ended'.format(self._prefix))
Esempio n. 26
0
    def swing(self):
        self.strokes += 1
        yield self.session.publish('com.forrestli.selfiegolf.pubsub.strokes',
                                   self.strokes, self.my_id)

        v = self.prevDtheta * r
        path = collision.collision.path(
            self.x, self.z, v * np.cos(self.orientation + self.cameraHeading),
            v * np.sin(self.orientation + self.cameraHeading))
        for x, z in path:
            if z > self.hole_z-hole_halfwidth  and z < self.hole_z+hole_halfwidth and \
                    x > self.hole_x-hole_halfwidth and x < self.hole_x+hole_halfwidth:
                subprocess.Popen(['play', '-q', '../golf_hole.wav'])
                yield self.session.publish(
                    'com.forrestli.selfiegolf.hide_ball', self.my_id)
                # don't continue to perform swing
                self.disable_hits = True

                # sleep 1 sec for user experience
                yield sleep(1)

                # set game state
                self.cur_level = (self.cur_level + 1) % len(holes)
                self.hole_x, self.hole_z = holes[self.cur_level]
                self.x, self.z = start[self.cur_level]
                self.stationary = True
                yield self.session.publish(
                    'com.forrestli.selfiegolf.pubsub.ball', self.x, .1, self.z,
                    self.stationary, self.my_id)

                self.strokes = 0
                yield self.session.publish(
                    'com.forrestli.selfiegolf.pubsub.strokes', self.strokes,
                    self.my_id)

                # stupid "mutex"
                self.disable_hits = False

                yield self.session.publish(
                    'com.forrestli.selfiegolf.show_ball', self.my_id)

                return
            yield self.session.publish('com.forrestli.selfiegolf.pubsub.ball',
                                       x, .1, z, self.stationary, self.my_id)
            yield sleep(.01)
        self.stationary = True
        self.x = x
        self.z = z
        yield self.session.publish('com.forrestli.selfiegolf.pubsub.ball', x,
                                   .1, z, self.stationary, self.my_id)
Esempio n. 27
0
  def onJoin(self, details):
    cam = picamera.PiCamera()
    cam.contrast = 15
    cam.saturation = 15
    cam.awb_mode = "fluorescent"
    cam.exposure_mode = "sports"
    cam.exposure_compensation = 6
    cam.resolution = (950, 535) #(1296, 730)
    cam.rotation = 270
    yield sleep(2)

    while (True):
      cam.capture("../cam/cam.png")
      yield sleep(60)
Esempio n. 28
0
def waitForCompletePackets(day):
    global packets
    prev_l = -1
    # checks when to start clearing the packets

    # wait for packets to get filled
    while not len(packets):
        yield sleep(5)

    # actual check code
    while packets[-1]['day'] == day and len(packets) > prev_l:
        prev_l = len(packets)
        yield sleep(6)
        print('\033[93m Waiting for packets.... \033[0m')
    defer.returnValue(True)
Esempio n. 29
0
        def longop(a, details=None):
            if details.progress:
                print("Alpha")
                details.progress("Alpha")
                yield sleep(1)

                print("Bravo")
                details.progress("Bravo")
                yield sleep(1)

                print("Charlie")
                details.progress("Charlie")
                yield sleep(1)

            returnValue("ok")
Esempio n. 30
0
 def reconnector():
     while True:
         try:
             log.msg("Capture component attempting to connect...")
             captdconnection = yield _capture_runner.run(
                 build_capture_component(_session_key), start_reactor=False)
             log.msg(captdconnection)
             yield sleep(10.0)  # Give the connection time to set _session
             while captdconnection.isOpen():
                 yield sleep(5.0)
         except ConnectionRefusedError as ce:
             log.msg(
                 "Capture component: ConnectionRefusedError; Trying to reconnect... "
             )
             yield sleep(1.0)
Esempio n. 31
0
    def onJoin(self, details):

        counter = 0
        while True:
            self.publish('com.myapp.topic1', counter)
            counter += 1
            yield sleep(1)
Esempio n. 32
0
    def _frontend_session_started(self, *_):
        client = Client(self.state.frontend_session, MockService.methods)
        publisher = Publisher(self.state.backend_session)

        multiply_result = yield client.multiply(2, 3)
        assert multiply_result == 6

        divide_result = yield client.divide(4)
        assert divide_result == 2

        divide_result = yield client.divide(8, 4)
        assert divide_result == 2

        assert self.state.frontend.n_hello_received == 0
        yield publisher.publish('mock.event.hello')
        yield util.sleep(0.5)
        assert self.state.frontend.n_hello_received > 0

        with self.assertRaises(ApplicationError):
            yield client.exception()

        ping_result = yield client.ping()
        assert ping_result == u'pong'

        yield self.state.router.stop()
        self.state.done = True
Esempio n. 33
0
    def status(self, ref, follow=False, **kwargs):

        name, service = self.parse_app_ref(ref, kwargs, app_only=True)

        self.last_lines = 0

        def _print(data):

            ret = 'App not found.'

            for app in data:
                if app['name'] == name:
                    ret = self.print_app_details(app)
                    break

            if self.last_lines > 0:
                print '\033[1A' * self.last_lines

            self.last_lines = ret.count('\n') + 2

            print ret

        if follow:
            while follow:
                ret = yield self._remote_exec('list')
                _print(ret)
                yield sleep(1)
        else:
            ret = yield self._remote_exec('list')
            _print(ret)
Esempio n. 34
0
def foo(*args, **kw):
    print("foo({}, {})".format(args, kw))
    for x in range(5, 0, -1):
        print("  returning in {}".format(x))
        yield sleep(1)
    print("returning '42'")
    returnValue(42)
Esempio n. 35
0
 def rainbow_cycle(self, wait_ms=20, iterations=5):
     """Draw rainbow that uniformly distributes itself across all pixels."""
     for j in range(256 * iterations):
         for i in range(self._leds.numPixels()):
             r, g, b = self.wheel(((i * 256 / self._leds.numPixels()) + j) & 255)
             self.set_color(r, g, b, i)
         yield sleep(wait_ms / 1000.0)
Esempio n. 36
0
    def toggleSwitch(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("toggleSwitch {}".format(id))

            id = int(id)

            if (id >= 16 and id <= 21):
                id = 32768 + (id - 16)
            elif (id == 0):
                id = 32768 + 6
            else:
                return "unknown switch"

            self.client.write_coil(id, 1)
            yield sleep(0.1)
            self.client.write_coil(id, 0)

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"
Esempio n. 37
0
    def onJoin(self, details):
        self.log.info('session joined: {details}', details=details)

        def on_event(pid, seq, ran, details=None):
            self.log.info(
                'event received on topic {topic}: pid={pid}, seq={seq}, ran={ran}, details={details}\n',
                topic=TOPIC,
                pid=pid,
                seq=seq,
                ran=binascii.b2a_hex(ran),
                details=details)

        reg = yield self.subscribe(on_event,
                                   TOPIC,
                                   options=SubscribeOptions(details=True))

        self.log.info('subscribed to topic {topic}: registration={reg}',
                      topic=TOPIC,
                      reg=reg)

        pid = os.getpid()
        seq = 1

        while True:
            pub = yield self.publish(
                TOPIC,
                pid,
                seq,
                os.urandom(8),
                options=PublishOptions(acknowledge=True, exclude_me=False),
            )
            self.log.info('event published: publication={pub}\n', pub=pub)
            seq += 1
            yield sleep(1)
Esempio n. 38
0
 def hold(self, duration):
     yield self.set(True)
     self.sleeping = sleep(duration)
     try:
         yield self.sleeping
     finally:
         yield self.set(False)
Esempio n. 39
0
    def onJoin(self, details):
        hydroponic_plant = HydroponicPlan()
        status = hydroponic_plant.status
        yield self.publish('com.ebbandflow.onread', status)

        def onwrite(msg):
            # self.log.info("event for 'onwrite' received: {msg}", msg=msg)

            substrate_humidity_set_point = msg.get('substrate_humidity_set_point', None)
            if substrate_humidity_set_point:
                hydroponic_plant.substrate_humidity_set_point = int(substrate_humidity_set_point)

            substrate_humidity_pump = msg.get('substrate_humidity_pump', None)
            if substrate_humidity_pump is not None:
                hydroponic_plant.substrate_humidity_pump = int(substrate_humidity_pump)

            operation_mode = msg.get('operation_mode', None)
            if operation_mode and operation_mode in ['auto', 'manual']:
                hydroponic_plant.operation_mode = operation_mode

        yield self.subscribe(onwrite, 'com.ebbandflow.onwrite')
        self.log.info("subscribed to topic 'onwrite'")

        while True:
            status = hydroponic_plant.status
            self.log.info("hydroponic plant status: {0}".format(status))
            yield self.publish('com.ebbandflow.onread', status)
            yield sleep(60)
Esempio n. 40
0
   def onJoin(self, details):
      print("session attached")

      def add2(a, b):
         return a + b

      yield self.register(add2, 'com.myapp.add2')

      def on_event(i):
         print("Got event: {}".format(i))

      yield self.subscribe(on_event, 'com.myapp.topic1')

      counter = 0
      while True:
         print(".")

         try:
            res = yield self.call('com.myapp.add2', counter, 7)
            print("Got call result: {}".format(res))
         except Exception as e:
            print("Call failed: {}".format(e))

         try:
            publication = yield self.publish('com.myapp.topic1', counter,
                  options = PublishOptions(acknowledge = True, discloseMe = True, excludeMe = False))
            print("Event published with publication ID {}".format(publication.id))
         except Exception as e:
            print("Publication failed: {}".format(e))

         counter += 1
         yield sleep(1)
Esempio n. 41
0
    def onJoin(self, details):
        print("session attached")
        # SUBSCRIBE to a topic and receive events
        #

        def process_order(msg):
            # print "got this order", msg
            command = json.loads(msg)
            command = self._decode_dict(command)
            # print command
            myfunc = self.funcdict[command["command"]]
            # print myfunc
            myfunc(self, command, self.values)
            orders.put(self.values)
            # print self.values
            # reset values to all zeros after processing
            self.values = [0] * 26

        sub = yield self.subscribe(process_order, 'com.arduino.order')
        print("subscribed to topic 'com.arduino.order': {}".format(sub))

        #
        # PUBLISH an event
        #
        while True:
            if(exitFlag.value):
                reactor.stop()
                return
            if not queue.empty():
                I = queue.get()
                yield self.publish('com.arduino.state', I)
            # else:
            #    print ("No items in queue")
            yield sleep(0.1)
Esempio n. 42
0
    def onJoin(self, details):
        print("session joined")

        # ---- Publisher ----

        for i in range(5):
            msg = u'Testing %d' % i
            print("Publishing:", msg)
            self.publish(topic, msg)
            yield sleep(1)

        # ---- Caller ----

        print('Calling procedure:', procedure)
        try:
            res = yield self.call(procedure, 2, 3)
            print("call result: {}".format(res))
        except Exception as e:
            print("call error: {0}".format(e))


        def on_prog(msg):
            print("here")
            print("partial result: {}".format(msg))

        print('Calling procedure:', procedure2)
        try:
            res = yield self.call(procedure2, 'A',
                                  options=CallOptions(on_progress=on_prog))
            print("call result: {}".format(res))
        except Exception as e:
            print("call error: {0}".format(e))
Esempio n. 43
0
    def onJoin(self, details):

        ## SUBSCRIBE to a topic and receive events
        def probot_topic_2(msg):
                
        	msg2=[msg.encode('utf-8') for msg in msg]
            
        	publisher=Pub_Sub.publisher(msg2)
             

        sub = yield self.subscribe(probot_topic_2, 'probot-topic-2')
        self.log.info("subscribed to topic 'probot-topic-2'")

	self.publish('general-topic', "B-2")


        ## PUBLISH and CALL every second .. forever
        while True:
		
		## PUBLISH an event
        	subscriber = Pub_Sub.subscriber()
		if subscriber is None:
			subscriber=0
			Bat_perc=0	
        	else:
			if 'Bat-' in subscriber:
            			bat=subscriber.split('-')[1]			
				Bat_perc=((int(bat)*15.385)-287.673)
		
		self.publish('probot-bat-2', int(Bat_perc))
		self.log.info("published on probot-bat-2: {msg}", msg=int(Bat_perc))
                yield sleep(1)
Esempio n. 44
0
    def welcome(self):
        msgs = []

        # Pi serial number
        msg = 'serial {:0>6d}'.format(self._serial)
        self.log.info(msg)
        msgs.append(msg)

        # interface IP addresses
        for ifc in netifaces.interfaces():
            if ifc.startswith('wlan') or ifc.startswith('eth'):
                ip4 = '0.0.0.0'
                if netifaces.AF_INET in netifaces.ifaddresses(ifc):
                    ip4_ifcs = netifaces.ifaddresses(ifc)[netifaces.AF_INET]
                    if ip4_ifcs:
                        ip4 = ip4_ifcs[0]['addr']
                msg = 'interface {} {}'.format(ifc, ip4)
                msgs.append(msg)
                self.log.info(msg)

        # scroll informational message
        msg = '     '.join(msgs)
        yield self._display.scroll_message(msg)

        # write the ZOLLHOF logo
        self._display.set_raw_digit(0, 0b0001001)
        self._display.set_raw_digit(1, 0b0111111)
        self._display.set_raw_digit(2, 0b0110110)
        self._display.set_raw_digit(3, 0b1110000)
        self._display.set_raw_digit(4, 0b0111111)
        self._display.set_raw_digit(5, 0b1110001)
        self._display.write_display()

        yield sleep(5)
Esempio n. 45
0
   def onJoin(self, details):

      counter = 0
      while True:
         self.publish('com.myapp.topic1', counter)
         counter += 1
         yield sleep(1)
Esempio n. 46
0
    def onJoin(self, details):

        self._prefix = self.config.extra['prefix']
        self._logname = self.config.extra['logname']

        self._pinfo = ProcessInfo()

        def echo(arg):
            return arg

        yield self.register(echo, '{}.echo'.format(self._prefix), options=RegisterOptions(invoke='roundrobin'))

        self.log.info('{} ready!'.format(self._logname))

        last = None
        while True:
            stats = self._pinfo.get_stats()
            if last:
                secs = (stats['time'] - last['time']) / 10**9
                ctx = round((stats['voluntary'] - last['voluntary']) / secs, 0)
                self.log.info('{logname}: {cpu} cpu, {mem} mem, {ctx} ctx',
                              logname=self._logname,
                              cpu=round(stats['cpu_percent'], 1),
                              mem=round(stats['mem_percent'], 1),
                              ctx=ctx)
            last = stats
            yield sleep(5)
Esempio n. 47
0
 def onJoin(self, details):
    print("session attached")
    while True:
       t = time.time()
       print("Sent time: {}".format(t))
       self.publish('df_everywhere.test.test.time', t)
       yield sleep(1)
Esempio n. 48
0
 def rainbow(self, wait_ms=20, iterations=1):
     """Draw rainbow that fades across all pixels at once."""
     for j in range(256 * iterations):
         for i in range(self._leds.numPixels()):
             r, g, b = self.wheel((i + j) & 255)
             self.set_color(r, g, b, i)
         yield sleep(wait_ms / 1000.0)
Esempio n. 49
0
    def onJoin(self, details):
        GPIO.setmode(self.gpio_mode)
        for channel in self.board_gpio_channels:
            GPIO.setup(channel, GPIO.OUT)
            GPIO.output(channel, self.GPIO_OFF)

        self.deviceRegUID = yield self.call('com.jeremydyer.residence.rpi.join.request')
        print "Device Registry Unique Identifier -> " + str(self.deviceRegUID)

        #Registers the RPC components for this device with their unique values received from the device registry
        self.rpi = RPi(self.deviceRegUID)
        self.rpi.turnOnOutletRPC = "com.jeremydyer.gpio.power.{}.turnon".format(str(self.deviceRegUID))
        self.rpi.turnOffOutletRPC = "com.jeremydyer.gpio.power.{}.turnoff".format(str(self.deviceRegUID))
        self.rpi.updateDeviceRPC = "com.jeremydyer.gpio.residence.{}.update".format(str(self.deviceRegUID))
        yield self.register(self.turn_on_outlet, self.rpi.turnOnOutletRPC)
        yield self.register(self.turn_off_outlet, self.rpi.turnOffOutletRPC)
        yield self.register(self.update_device, self.rpi.updateDeviceRPC)

        #Now that all of the registration has occured call back and give the list of subscriptions you have
        self.deviceRegUID = yield self.call('com.jeremydyer.residence.rpi.join', self.rpi.to_json())

        #Publish a message letting all connected devices know that a newly connected device is now available
        yield self.publish('com.jeremydyer.residence.rpi.join.notify', self.rpi.to_json())

        #Creates the heartbeat object that
        heartbeat = RPiHeartBeat(self.rpi.uid)

        #Creates an infinite loop to post the heartbeat back to the device registry.
        while True:
            heartbeat.timestamp = time.time()
            yield self.publish(u'com.jeremydyer.residence.rpi.heartbeat', jsonpickle.encode(heartbeat))
            yield sleep(self.heartbeatinterval)
Esempio n. 50
0
    def _exec_remote_with_pty(self, task_name, *args):
        stream_proto = AttachStdinProtocol()
        stdio.StandardIO(stream_proto)

        from mcloud.remote import Client, Task

        client = Client(host=self.host, port=self.port, settings=self.settings)
        try:
            yield txtimeout(client.connect(), 20, 'Can\'t connect to the server on host %s' % self.host)

            task = Task(task_name)
            task.on_progress = self.print_progress
            task.on_stdout = stream_proto.write

            stream_proto.listener = task.on_stdin

            try:
                yield client.call(task, *args, size=stream_proto.term.get_size())

                res = yield task.wait_result()
                yield client.shutdown()
                yield sleep(0.1)

                defer.returnValue(res)

            except Exception as e:
                print repr(e)
                print('Failed to execute the task: %s' % e.message)

        except ConnectionRefusedError:
            print 'Can\'t connect to mcloud server'

        finally:
            stream_proto.stop()
Esempio n. 51
0
    def onJoin(self, details):
        self.log.info("connected:  {details}", details=details)
        self._running = True

        topic_name = u"com.example.mytopic1"

        def _foo(*args, **kwargs):
            print("{}: {} {}".format(topic_name, args, kwargs))
            assert 'foo' in kwargs and type(kwargs['foo']) == str and len(
                kwargs['foo']) == 22
            assert 'baz' in kwargs and type(kwargs['baz']) == bytes and len(
                kwargs['baz']) == 10
            assert binascii.a2b_hex(kwargs['foo'][2:]) == kwargs['baz']

        self.subscribe(_foo, topic_name)
        print("subscribed")

        pid = os.getpid()
        counter = 0
        while self.is_connected():
            print("pid {} publish {} to '{}'".format(pid, counter, topic_name))
            data = os.urandom(10)
            yield self.publish(
                topic_name,
                pid,
                counter,
                foo='0x' + binascii.b2a_hex(data).decode(),
                baz=data,
                options=PublishOptions(acknowledge=True, exclude_me=False),
            )
            counter += 1
            yield sleep(1)
Esempio n. 52
0
    def onJoin(self, details):

        def leitura():
            self.log.info("Leitura solicitada")
            ultimas_leituras = models.StatusPlanta.select().order_by(models.StatusPlanta.created_date.desc()).limit(10)
            return [leitura.to_dict() for leitura in ultimas_leituras]

        yield self.register(leitura, 'com.ebbandflow.leitura')

        def comando_serial(comando):
            arduino.write(bytes(comando))
            return 'OK'
        yield self.register(comando_serial, 'com.ebbandflow.comando_serial')

        intervalo_leitura = 5
        while True:
            arduino.write("r")  # Solicita leitura
            data = arduino.readlines()
            if(data):
                status = {}
                for line in data:
                    key, value = line.split('=')
                    status[key] = value.rstrip()
                models.StatusPlanta(**status).save()
                intervalo_leitura = int(status.get("intervalo_leitura", intervalo_leitura)) / 1000
                self.log.info("Leitura Arduino: {status}", data=json.dumps(status))
            yield sleep(intervalo_leitura)
Esempio n. 53
0
    def onJoin(self, details):
        def leitura():
            self.log.info("Leitura solicitada")
            ultimas_leituras = models.StatusPlanta.select().order_by(
                models.StatusPlanta.created_date.desc()).limit(10)
            return [leitura.to_dict() for leitura in ultimas_leituras]

        yield self.register(leitura, 'com.ebbandflow.leitura')

        def comando_serial(comando):
            arduino.write(bytes(comando))
            return 'OK'

        yield self.register(comando_serial, 'com.ebbandflow.comando_serial')

        intervalo_leitura = 5
        while True:
            arduino.write("r")  # Solicita leitura
            data = arduino.readlines()
            if (data):
                status = {}
                for line in data:
                    key, value = line.split('=')
                    status[key] = value.rstrip()
                models.StatusPlanta(**status).save()
                intervalo_leitura = int(
                    status.get("intervalo_leitura", intervalo_leitura)) / 1000
                self.log.info("Leitura Arduino: {status}",
                              data=json.dumps(status))
            yield sleep(intervalo_leitura)
Esempio n. 54
0
 def onJoin(self, details):
     counter = 0
     while True:
         print("publish: com.myapp.topic1", counter)
         yield self.publish(u'com.myapp.topic1', counter)
         counter += 1
         yield sleep(1)
Esempio n. 55
0
    def onNotify(self, title, body, duration=2):

        print("Notification received: title = '{}', body = '{}', duration = {}".format(title, body, duration))

        try:
            nid = yield self._notifier.callRemote('Notify',
                                                  'WAMP/Dbus Notifier',
                                                  0,
                                                  '',
                                                  str(title),
                                                  str(body),
                                                  [],
                                                  {},
                                                  1)

            print("Desktop notification shown (NID = {}).. closing in {} seconds".format(nid, duration))

            yield sleep(duration)
            print("Closing notification")

            yield self._notifier.callRemote('CloseNotification', nid)
            print("Notification closed")

        except Exception as e:
            print("ERROR: {}".format(e))
 def onJoin(self, details):
     counter = 0
     while True:
         print("publish: com.myapp.topic1", counter)
         yield self.publish(u'com.myapp.topic1', counter)
         counter += 1
         yield sleep(1)
Esempio n. 57
0
 def set(self, value):
     if self.sleeping and not self.sleeping.called:
         self.sleeping.cancel()
         yield sleep(0.1)
     self.vfile.write(str(int(value)))
     self.vfile.flush()
     self.changeState(value)
Esempio n. 58
0
    def onJoin(self, details):
        print("session attached")
        print("  authid: {}".format(details.authid))
        print("authrole: {}".format(details.authrole))

        def got_heartbeat(name, counter):
            print("hearbeat: {}: {}".format(name, counter))

        for name in ['erin', 'bob', 'carol', 'dave', 'erin']:
            yield self.subscribe(
                partial(got_heartbeat, name),
                u'public.heartbeat.{}'.format(name),
            )

        counter = 0
        topic = u'public.heartbeat.erin'
        while True:
            print("publish '{}'".format(topic))
            self.publish(
                topic,
                '{}: to alice, bob, dave'.format(counter),
                options=PublishOptions(
                    eligible_authid=[u'alice', u'bob', u'dave'], ),
            )
            if counter % 2:
                self.publish(
                    topic,
                    '{}: "beta" role'.format(counter),
                    options=PublishOptions(
                        eligible_authrole=u"beta",
                        exclude_me=False,
                    ),
                )
            counter += 1
            yield sleep(3)
Esempio n. 59
0
def called_on_joinded():
    """ Boucle envoyant l'état de cette machine avec WAMP toutes les x secondes.

        Cette fonction est exécutée quand le client "joins" le router, c'est
        à dire qu'il est connecté et authentifié, prêt à envoyer des messages
        WAMP.
    """
    # Ensuite on fait une requête post au serveur pour dire qu'on est
    # actif et récupérer les valeurs de configuration de notre client.
    app._params.update(requests.post('http://' + SERVER + ':8000/clients/',
                                    data={'ip': app._params['ip']}).json())


    # Puis on boucle indéfiniment
    while True:
        # Chaque tour de boucle, on récupère les infos de notre machine
        infos = {'ip': app._params['ip'], 'name': app._params['name']}
        infos.update(get_infos(app._params))

        # Si les stats sont a envoyer, on fait une publication WAMP.
        if not app._params['disabled']:
            app.session.publish('clientstats', infos)

        # Et on attend. Grâce à @inlineCallbacks, utiliser yield indique
        # qu'on ne bloque pas ici, donc pendant ce temps notre client
        # peut écouter les événements WAMP et y réagir.
        yield sleep(app._params['frequency'])
Esempio n. 60
0
 def onJoin(self, details):
     print("session attached")
     counter = 0
     while True:
         print('backend publishing com.myapp.topic1', counter)
         self.publish(u'com.myapp.topic1', counter)
         counter += 1
         yield sleep(1)