Beispiel #1
0
    def test_change_useragent(self):
        "Test changing the HTTP useragent string."

        from relayr import config
        from relayr.api import Api
        port = get_free_port()
        t = MyThread(port)
        t.start()

        previous = config.relayrAPI[:]

        url = 'http://localhost:%d' % port
        config.relayrAPI = url

        if PY3:
            user_agent_key = 'User-Agent'
        else:
            user_agent_key = 'user-agent'

        # default config user-agent
        headers = Api().get_server_status()
        assert headers[user_agent_key] == config.userAgent

        # modified config user-agent
        config.userAgent = 'Python Relayr API Super Special Testing Agent'
        headers = Api().get_server_status()
        assert headers[user_agent_key] == config.userAgent

        t.stop()

        config.relayrAPI = previous
Beispiel #2
0
    def __init__(self, token=None):
        """
        :arg token: A token generated on the relayr site for the combination of
            a user and an application.
        :type token: A string.
        """

        self.api = Api(token=token)
Beispiel #3
0
class Client(object):
    """
    A client providing a higher level interface to the relayr cloud platform.

    Example:

    .. code-block:: python

        c = Client(token='...')
        info = c.get_oauth_user_info()
        usr = User(info['id'], client=c)
        devs = usr.get_devices()
        d = next(devs)
        apps = usr.get_apps()
    """
    def __init__(self, token=None):
        """
        :arg token: A token generated on the relayr site for the combination of
            a user and an application.
        :type token: A string.
        """

        self.api = Api(token=token)

    def get_public_apps(self):
        """
        Returns a generator for all apps on the relayr platform.

        A generator is returned since the called API method always
        returns the entire results list and not a paginated one.


        :rtype: A generator for :py:class:`relayr.resources.App` objects.

        .. code-block:: python

            c = Client(token='...')
            apps = c.get_public_apps()
            for app in apps:
                print('%s %s' % (app.id, app.name))
        """

        for app in self.api.get_public_apps():
            a = App(app['id'], client=self)
            a.get_info()
            yield a

    def get_public_publishers(self):
        """
        Returns a generator for all publishers on the relayr platform.

        A generator is returned since the called API method always
        returns the entire results list and not a paginated one.


        :rtype: A generator for :py:class:`relayr.resources.Publisher` objects.
        """

        for pub in self.api.get_public_publishers():
            p = Publisher(pub['id'], client=self)
            for k in pub:
                setattr(p, k, pub[k])
            # p.get_info()
            yield p

    def get_public_devices(self, meaning=''):
        """
        Returns a generator for all devices on the relayr platform.

        A generator is returned since the called API method always
        returns the entire results list and not a paginated one.


        :arg meaning: The *meaning* (type) of the desired devices.
        :type meaning: string
        :rtype: A generator for :py:class:`relayr.resources.Device` objects.
        """

        for dev in self.api.get_public_devices(meaning=meaning):
            d = Device(dev['id'], client=self)
            d.get_info()
            yield d

    def get_public_device_models(self):
        """
        Returns a generator for all device models on the relayr platform.

        A generator is returned since the called API method always
        returns the entire results list and not a paginated one.


        :rtype: A generator for :py:class:`relayr.resources.DeviceModel` objects.
        """

        for dm in self.api.get_public_device_models():
            d = DeviceModel(dm['id'], client=self)
            d.get_info()
            yield d

    def get_public_device_model_meanings(self):
        """
        Returns a generator for all device models' meanings on the relayr platform.

        A device model meaning is a simple dictionary with a ``key`` and ``value``
        field.

        A generator is returned since the called API method always
        returns the entire results list and not a paginated one.


        :rtype: A device model meaning (as a dictionary) generator.

        .. code-block:: python

            {'key': 'humidity', 'value': 'humidity'}
        """

        for dmm in self.api.get_public_device_model_meanings():
            yield dmm

    def get_user(self):
        """
        Returns the relayr user owning the API client.

        :rtype: A :py:class:`relayr.resources.User` object.
        """
        info = self.api.get_oauth2_user_info()
        usr = User(info['id'], client=self)
        for k in info:
            setattr(usr, k, info[k])
        return usr

    def get_app(self):
        """
        Returns the relayr application of the API client.

        :rtype: A :py:class:`relayr.resources.App` object.
        """
        info = self.api.get_oauth2_app_info()
        app = App(info['id'], client=self)
        app.get_info()
        return app

    def get_device(self, id):
        """
        Returns the device with the specified ID.

        :arg id: the unique ID for the desired device.
        :type id: string
        :rtype: A :py:class:`relayr.resources.Device` object.
        """
        return Device(id=id, client=self)
def send_data_to_plotly(): 
    tls.set_credentials_file(stream_ids=[
        "l2jcjzwcag",
        "vd0uk9bn68",
        "gb7zo82zbm",
        "h9zzpurc0q"
    ])
    a = Api(token='ENtcsvfM9tOT0.ktctGbJDdAyxZtKVEF')
    stream_ids = tls.get_credentials_file()['stream_ids']
    print (stream_ids)
    stream_id = stream_ids[0]
    stream_id2 = stream_ids[1]

    # Make instance of stream id object 

    stream = Stream(
     token=stream_id,  # (!) link stream id to 'token' key
     maxpoints=80      # (!) keep a max of 80 pts on screen
     )

    stream2 = Stream(
     token=stream_id2,  # (!) link stream id to 'token' key
     maxpoints=80      # (!) keep a max of 80 pts on screen
     )
     # Initialize trace of streaming plot by embedding the unique stream_id

    trace1 = Scatter(
     x=[],
     y=[],
     mode='lines+markers',
     stream=stream         # (!) embed stream id, 1 per trace

     )

    trace2 = Scatter(
     x=[],
     y=[],
     mode='lines+markers',
     stream=stream2         # (!) embed stream id, 1 per trace

     )
    data = Data([trace1])
    data2 = Data([trace2])

    # Add title to layout object
    layout = Layout(title='BPM Series')
    layout2 = Layout(title='Heartbeat monitoring')

    # Make a figure object
    fig = Figure(data=data, layout=layout)
    fig2 = Figure(data=data2, layout=layout2)

    # (@) Send fig to Plotly, initialize streaming plot, open new tab
    #unique_url = py.plot(fig, filename='s7_first-stream')
    # (@) Make instance of the Stream link object, 
    #     with same stream id as Stream id object

    s = py.Stream(stream_id)
    s2 = py.Stream(stream_id2)

    # (@) Open the stream
    s.open()
    s2.open()


    # Delay start of stream by 5 sec (time to switch tabs)
    time.sleep(5)
    ser = serial.Serial('/dev/ttyACM0', 115200)
    while True:
        ch = ser.readline()
        x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
        if 'B' in  ch:
            print ch
            chfin = ch.split('B')
            print chfin[1]  

            # Current time on x-axis, random numbers on y-axis
            y = int(chfin[1])    

            # POST data to relayr
            #finstr = "\'" + chfin[1] + "\'"
            #print finstr
            finstr = chfin[1].rstrip()
            data = {'meaning' : 'bpm', 'value' : finstr }
            print data 
            a.post_device_data('7ccfb852-2203-4616-8cbf-cdf55471abc9', data)
            # (@) write to Plotly stream!
            s.write(dict(x=x, y=y))

            # (!) Write numbers to stream to append current data on plot,
            #     write lists to overwrite existing data on plot (more in 7.2).
        elif 'S' in ch:
            print ch
            chfinS = ch.split('S')
            print chfinS[1] 
            y1 = int(chfinS[1])
            s2.write(dict(x=x, y=y1)) 

        time.sleep(0.08)  # (!) plot a point every 80 ms, for smoother plotting

    # (@) Close the stream when done plotting

    s.close()
    s2.close()