Ejemplo n.º 1
0
def draw(name, open, close, max, min, dates):
    py.get_credentials()
    open = sql.search(name, "open")
    close = sql.search(name, "close")
    max = sql.search(name, "max")
    min = sql.search(name, "min")
    dates = sql.search(name, "date")
    fig = FF.create_candlestick(open, max, min, close, dates)
    py.iplot(
        fig,
        filename=name,
        validate=False,
    )
Ejemplo n.º 2
0
def init():
    # use auto setup as described here: https://plot.ly/python/getting-started/ to avoid passwords in code
    # or less secure sign_in code below
    # py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),model_helper.get_param(constant.P_PLOTLY_APIKEY))
    username = ""
    if py.get_credentials()['username'] == '' or py.get_credentials(
    )['api_key'] == '':
        env_var = 'PLOTLY_CREDENTIALS_PATH'
        alt_path = os.environ.get(env_var)
        if not alt_path:
            L.l.info(
                'Plotly config not in environment var: {}'.format(env_var))
            env_var = 'OPENSHIFT_REPO_DIR'
            alt_path = os.environ.get(env_var)
            if alt_path is None:
                L.l.info(
                    'Plotly config not in environment var: {}'.format(env_var))
                credential_file = model_helper.get_param(
                    Constant.P_PLOTLY_ALTERNATE_CONFIG)
                alt_path = os.getcwd() + '/' + credential_file
            else:
                L.l.info('Plotly config found in environment var: {}, path={}'.
                         format(env_var, alt_path))
                alt_path = str(alt_path) + '/../data/.plotly.credentials'
        L.l.info("Plotly standard config empty, trying alt_path={}".format(
            alt_path))
        try:
            with open(alt_path, 'r') as cred_file:
                data = cred_file.read().replace('\n', '')
            if len(data) > 0:
                cred_obj = utils.json2obj(data)
                username = cred_obj['username']
                api_key = cred_obj['api_key']
                if username and api_key:
                    py.sign_in(username, api_key)
                    global initialised
                    initialised = True
                    # else:
                    #    Log.logger.info("Plotly init from db folder config {}{} not ok, trying with db data".format(os.getcwd(),
                    #        credential_file))
                    #    #alternate way if reading data from DB
                    #    py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),
                    #               model_helper.get_param(constant.P_PLOTLY_APIKEY))

        except Exception, ex:
            L.l.warning("error reading plotly credentials {}".format(ex))
Ejemplo n.º 3
0
 def test_sign_in(self):
     un = 'anyone'
     ak = 'something'
     # TODO, add this!
     # si = ['this', 'and-this']
     py.sign_in(un, ak)
     creds = py.get_credentials()
     self.assertEqual(creds['username'], un)
     self.assertEqual(creds['api_key'], ak)
Ejemplo n.º 4
0
 def test_get_credentials(self):
     session_credentials = session.get_session_credentials()
     if 'username' in session_credentials:
         del session._session['credentials']['username']
     if 'api_key' in session_credentials:
         del session._session['credentials']['api_key']
     creds = py.get_credentials()
     file_creds = tls.get_credentials_file()
     self.assertEqual(creds, file_creds)
Ejemplo n.º 5
0
    def __generate_plotly_url(fig, **kwargs):
        """ Returns a ready-to-embed URL to a provided fig.
        """

        # Sign in, if necessary.
        if py.get_credentials()["username"] == "":
            py.sign_in("jmoles", os.environ.get('PLOTLY_API_KEY'))

        return py.plot(fig, auto_open=False, **kwargs)
Ejemplo n.º 6
0
    def __init__(self, plotly_args=[], plotly_kwargs={}, parent=None):

        super(QtPlotlyExporter, self).__init__(parent=parent)

        self.plotly_args = plotly_args
        self.plotly_kwargs = plotly_kwargs

        self.ui = load_ui('exporter.ui',
                          self,
                          directory=os.path.dirname(__file__))

        self.button_cancel.clicked.connect(self.reject)
        self.button_export.clicked.connect(self.accept)

        # Set up radio button groups

        self._radio_account = QtWidgets.QButtonGroup()
        self._radio_account.addButton(self.ui.radio_account_glue)
        self._radio_account.addButton(self.ui.radio_account_config)
        self._radio_account.addButton(self.ui.radio_account_manual)

        self._radio_sharing = QtWidgets.QButtonGroup()
        self._radio_sharing.addButton(self.ui.radio_sharing_public)
        self._radio_sharing.addButton(self.ui.radio_sharing_secret)
        self._radio_sharing.addButton(self.ui.radio_sharing_private)

        # Find out stored credentials (note that this will create the
        # credentials file if it doesn't already exist)

        from plotly import plotly

        credentials = plotly.get_credentials()
        config_available = credentials['username'] != "" and credentials[
            'api_key'] != ""

        if config_available:
            self.ui.radio_account_config.setChecked(True)
            label = self.ui.radio_account_config.text()
            self.ui.radio_account_config.setText(
                label + " (username: {0})".format(credentials['username']))
        else:
            self.ui.radio_account_glue.setChecked(True)
            self.ui.radio_account_config.setEnabled(False)

        self.ui.radio_sharing_secret.setChecked(True)

        self.ui.text_username.textChanged.connect(
            nonpartial(self._set_manual_mode))
        self.ui.text_api_key.textChanged.connect(
            nonpartial(self._set_manual_mode))
        self.ui.radio_account_glue.toggled.connect(
            nonpartial(self._set_allowed_sharing_modes))

        self.set_status('', color='black')

        self._set_allowed_sharing_modes()
Ejemplo n.º 7
0
def main():
    try:
        addr = sys.argv[1]
        rid = sys.argv[2]
    except IndexError:
        print 'Usage: %s /dev/serial_device R_ID DHT_VER or ip:port R_ID DHT_VER' % sys.argv[0]
        sys.exit(1)

    if ':' in addr:
        ip, port = addr.split(':')
        ser = connect_telnet(ip, port)
    else:
        ser = connect_serial(addr, 9600)

    data_payload = ''

    layout = Layout(
        title=sensor_title, 
        yaxis=YAxis(
            title='Temperature (Celsius) / Humidity (%)',
            range=y_range
        ),
    )

    # Get credentials from plotly configfile.
    cr = py.get_credentials()
    trace1 = Scatter(x=[], y=[], name='temperature',
                     stream=dict(token=stream_ids[0], maxpoints=max_points))
    trace2 = Scatter(x=[], y=[], name='humidity',
                     stream=dict(token=stream_ids[1], maxpoints=max_points))
    fig = Figure(data=[trace1, trace2], layout=layout)
    py.plot(fig, filename=sensor_filename_plotly, fileopt='extend')
    s1 = py.Stream(stream_ids[0])
    s2 = py.Stream(stream_ids[1])
    s1.open()
    s2.open()

    draw_stored_data(s1, s2, db_filename)
    
    while True:
        # Read the newest output from the Arduino
        data_payload = ser.readline().strip()
        #data = parse_serial_data(data_payload, ':I%sH([0-9]+).([0-9]+)T([0-9]+).([0-9]+);' % rid)
        data = parse_serial_data(data_payload, ':I%sH([0-9]{1,3})\.?([0-9]{1,2})?T([0-9]{1,3})\.?([0-9]{1,2})?;' % rid)
        if data:
            try:
                ploty_streams(s1, s2, data)
            except socket.error, e:
                print 'Error contacting plotly server: %s' % e
            store_data_db(db_filename, data)
            print '%s end' % data_payload
        else:
            print '%s error' % data_payload
Ejemplo n.º 8
0
    def __init__(self, plotly_args=[], plotly_kwargs={}, parent=None):

        super(QtPlotlyExporter, self).__init__(parent=parent)

        self.plotly_args = plotly_args
        self.plotly_kwargs = plotly_kwargs

        self.ui = load_ui('exporter.ui', self,
                          directory=os.path.dirname(__file__))

        self.button_cancel.clicked.connect(self.reject)
        self.button_export.clicked.connect(self.accept)

        # Set up radio button groups

        self._radio_account = QtWidgets.QButtonGroup()
        self._radio_account.addButton(self.ui.radio_account_glue)
        self._radio_account.addButton(self.ui.radio_account_config)
        self._radio_account.addButton(self.ui.radio_account_manual)

        self._radio_sharing = QtWidgets.QButtonGroup()
        self._radio_sharing.addButton(self.ui.radio_sharing_public)
        self._radio_sharing.addButton(self.ui.radio_sharing_secret)
        self._radio_sharing.addButton(self.ui.radio_sharing_private)

        # Find out stored credentials (note that this will create the
        # credentials file if it doesn't already exist)

        from plotly import plotly

        credentials = plotly.get_credentials()
        config_available = credentials['username'] != "" and credentials['api_key'] != ""

        if config_available:
            self.ui.radio_account_config.setChecked(True)
            label = self.ui.radio_account_config.text()
            self.ui.radio_account_config.setText(label + " (username: {0})".format(credentials['username']))
        else:
            self.ui.radio_account_glue.setChecked(True)
            self.ui.radio_account_config.setEnabled(False)

        self.ui.radio_sharing_secret.setChecked(True)

        self.ui.text_username.textChanged.connect(nonpartial(self._set_manual_mode))
        self.ui.text_api_key.textChanged.connect(nonpartial(self._set_manual_mode))
        self.ui.radio_account_glue.toggled.connect(nonpartial(self._set_allowed_sharing_modes))

        self.set_status('', color='black')

        self._set_allowed_sharing_modes()
Ejemplo n.º 9
0
def plot_data():
    c = py.get_credentials()
    trace1 = pygraph.Scatter(
        x=[], y=[],
        mode='lines',
        line=pygraph.Line(color='rgba(31,119,180,0.15)'),
        stream=dict(token=c.get('stream_ids')[0], maxpoints=100))
    trace2 = pygraph.Scatter(
        x=[], y=[],
        mode='lines',
        line=pygraph.Line(color='rgba(180,119,31,0.15)'),
        stream=dict(token=c.get('stream_ids')[1], maxpoints=100))
    trace3 = pygraph.Scatter(
        x=[], y=[],
        mode='lines',
        line=pygraph.Line(color='rgba(119,180,31,0.15)'),
        stream=dict(token=c.get('stream_ids')[2], maxpoints=100))

    data = pygraph.Data([trace1, trace2, trace3])
    layout = pygraph.Layout(
        title='Streaming PyBerryIMU Data'
    )
    fig = pygraph.Figure(data=data, layout=layout)
    print(py.plot(fig, filename='PyBerryIMU'))
    s_x = py.Stream(c.get('stream_ids')[0])
    s_y = py.Stream(c.get('stream_ids')[1])
    s_z = py.Stream(c.get('stream_ids')[2])
    s_x.open()
    s_y.open()
    s_z.open()

    with BerryIMUClient() as c:
        c.calibration_object = StandardCalibration.load()
        t_start = c.timestamp
        while (c.timestamp - t_start) < 60:
            t = c.timestamp - t_start
            acc = c.read_accelerometer()
            s_x.write(dict(x=t, y=acc[0]))
            s_y.write(dict(x=t, y=acc[1]))
            s_z.write(dict(x=t, y=acc[2]))
    s_x.close()
    s_y.close()
    s_z.close()
Ejemplo n.º 10
0
    def accept(self):

        # In future we might be able to use more fine-grained exceptions
        # https://github.com/plotly/plotly.py/issues/524

        self.set_status('Signing in and plotting...', color='blue')

        auth = {}

        if self.ui.radio_account_glue.isChecked():
            auth['username'] = '******'
            auth['api_key'] = 't24aweai14'
        elif self.ui.radio_account_config.isChecked():
            auth['username'] = ''
            auth['api_key'] = ''
        else:
            if self.username == "":
                self.set_status("Username not set", color='red')
                return
            elif self.api_key == "":
                self.set_status("API key not set", color='red')
                return
            else:
                auth['username'] = self.username
                auth['api_key'] = self.api_key

        from plotly import plotly
        from plotly.exceptions import PlotlyError
        from plotly.tools import set_credentials_file

        # Signing in - at the moment this will not check the credentials so we
        # can't catch any issues until later, but I've opened an issue for this:
        # https://github.com/plotly/plotly.py/issues/525
        plotly.sign_in(auth['username'], auth['api_key'])

        if self.ui.radio_sharing_public.isChecked():
            self.plotly_kwargs['sharing'] = 'public'
        elif self.ui.radio_sharing_secret.isChecked():
            self.plotly_kwargs['sharing'] = 'secret'
        else:
            self.plotly_kwargs['sharing'] = 'private'

        # We need to fix URLs, so we can't let plotly open it yet
        # https://github.com/plotly/plotly.py/issues/526
        self.plotly_kwargs['auto_open'] = False

        # Get title and legend preferences from the window
        self.plotly_args[0]['layout']['showlegend'] = self.legend
        self.plotly_args[0]['layout']['title'] = self.title

        try:
            plotly_url = plotly.plot(*self.plotly_args, **self.plotly_kwargs)
        except PlotlyError as exc:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            if "the supplied API key doesn't match our records" in exc.args[0]:
                username = auth['username'] or plotly.get_credentials()['username']
                self.set_status("Authentication with username {0} failed".format(username), color='red')
            elif "filled its quota of private files" in exc.args[0]:
                self.set_status("Maximum number of private plots reached", color='red')
            else:
                self.set_status("An unexpected error occurred", color='red')
            return
        except:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            self.set_status("An unexpected error occurred", color='red')
            return

        self.set_status('Exporting succeeded', color='blue')

        if self.save_settings and self.ui.radio_account_manual.isChecked():
            try:
                set_credentials_file(**auth)
            except Exception:
                print("Plotly exception:")
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
                self.set_status('Exporting succeeded (but saving login failed)', color='blue')

        # We need to fix URL
        # https://github.com/plotly/plotly.py/issues/526
        if self.plotly_kwargs['sharing'] == 'secret':
            pos = plotly_url.find('?share_key')
            if pos >= 0:
                if plotly_url[pos - 1] != '/':
                    plotly_url = plotly_url.replace('?share_key', '/?share_key')

        print("Plotly URL: {0}".format(plotly_url))

        webbrowser.open_new_tab(plotly_url)

        super(QtPlotlyExporter, self).accept()
Ejemplo n.º 11
0
    def accept(self):

        # In future we might be able to use more fine-grained exceptions
        # https://github.com/plotly/plotly.py/issues/524

        self.set_status('Signing in and plotting...', color='blue')

        auth = {}

        if self.ui.radio_account_glue.isChecked():
            auth['username'] = '******'
            auth['api_key'] = 't24aweai14'
        elif self.ui.radio_account_config.isChecked():
            auth['username'] = ''
            auth['api_key'] = ''
        else:
            if self.username == "":
                self.set_status("Username not set", color='red')
                return
            elif self.api_key == "":
                self.set_status("API key not set", color='red')
                return
            else:
                auth['username'] = self.username
                auth['api_key'] = self.api_key

        from plotly import plotly
        from plotly.exceptions import PlotlyError
        from plotly.tools import set_credentials_file

        if self.ui.radio_sharing_public.isChecked():
            self.plotly_kwargs['sharing'] = 'public'
        elif self.ui.radio_sharing_secret.isChecked():
            self.plotly_kwargs['sharing'] = 'secret'
        else:
            self.plotly_kwargs['sharing'] = 'private'

        # We need to fix URLs, so we can't let plotly open it yet
        # https://github.com/plotly/plotly.py/issues/526
        self.plotly_kwargs['auto_open'] = False

        # Get title and legend preferences from the window
        self.plotly_args[0]['layout']['showlegend'] = self.legend
        self.plotly_args[0]['layout']['title'] = self.title

        try:
            plotly.sign_in(auth['username'], auth['api_key'])
            plotly_url = plotly.plot(*self.plotly_args, **self.plotly_kwargs)
        except PlotlyError as exc:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            if ('the supplied API key doesn\'t match our records' in exc.args[0] or
                    'Sign in failed' in exc.args[0]):
                username = auth['username'] or plotly.get_credentials()['username']
                self.set_status("Authentication failed".format(username), color='red')
            elif "filled its quota of private files" in exc.args[0]:
                self.set_status("Maximum number of private plots reached", color='red')
            else:
                self.set_status("An unexpected error occurred", color='red')
            return
        except Exception:
            print("Plotly exception:")
            print('-' * 60)
            traceback.print_exc(file=sys.stdout)
            print('-' * 60)
            self.set_status("An unexpected error occurred", color='red')
            return

        self.set_status('Exporting succeeded', color='blue')

        if self.save_settings and self.ui.radio_account_manual.isChecked():
            try:
                set_credentials_file(**auth)
            except Exception:
                print("Plotly exception:")
                print('-' * 60)
                traceback.print_exc(file=sys.stdout)
                print('-' * 60)
                self.set_status('Exporting succeeded (but saving login failed)', color='blue')

        # We need to fix URL
        # https://github.com/plotly/plotly.py/issues/526
        if self.plotly_kwargs['sharing'] == 'secret':
            pos = plotly_url.find('?share_key')
            if pos >= 0:
                if plotly_url[pos - 1] != '/':
                    plotly_url = plotly_url.replace('?share_key', '/?share_key')

        print("Plotly URL: {0}".format(plotly_url))

        webbrowser.open_new_tab(plotly_url)

        super(QtPlotlyExporter, self).accept()
Ejemplo n.º 12
0
        L.l.info("Plotly standard config empty, trying alt_path={}".format(
            alt_path))
        try:
            with open(alt_path, 'r') as cred_file:
                data = cred_file.read().replace('\n', '')
            if len(data) > 0:
                cred_obj = utils.json2obj(data)
                username = cred_obj['username']
                api_key = cred_obj['api_key']
                if username and api_key:
                    py.sign_in(username, api_key)
                    global initialised
                    initialised = True
                    # else:
                    #    Log.logger.info("Plotly init from db folder config {}{} not ok, trying with db data".format(os.getcwd(),
                    #        credential_file))
                    #    #alternate way if reading data from DB
                    #    py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),
                    #               model_helper.get_param(constant.P_PLOTLY_APIKEY))

        except Exception, ex:
            L.l.warning("error reading plotly credentials {}".format(ex))
    else:
        L.l.info("Plotly standard config found with username {}".format(
            py.get_credentials()['username']))
        initialised = True
    if initialised:
        L.l.info('Plotly is connected with username={}'.format(username))
        thread_pool.add_interval_callable(graph_plotly_run.thread_run,
                                          run_interval_second=60)
Ejemplo n.º 13
0
            else:
                L.l.info('Plotly config found in environment var: {}, path={}'.format(env_var, alt_path))
                alt_path = str(alt_path) + '/../data/.plotly.credentials'
        L.l.info("Plotly standard config empty, trying alt_path={}".format(alt_path))
        try:
            with open(alt_path, 'r') as cred_file:
                data = cred_file.read().replace('\n', '')
            if len(data) > 0:
                cred_obj = utils.json2obj(data)
                username = cred_obj['username']
                api_key = cred_obj['api_key']
                if username and api_key:
                    py.sign_in(username, api_key)
                    global initialised
                    initialised = True
                    # else:
                    #    Log.logger.info("Plotly init from db folder config {}{} not ok, trying with db data".format(os.getcwd(),
                    #        credential_file))
                    #    #alternate way if reading data from DB
                    #    py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),
                    #               model_helper.get_param(constant.P_PLOTLY_APIKEY))

        except Exception, ex:
            L.l.warning("error reading plotly credentials {}".format(ex))
    else:
        L.l.info("Plotly standard config found with username {}".format(py.get_credentials()['username']))
        initialised = True
    if initialised:
        L.l.info('Plotly is connected with username={}'.format(username))
        thread_pool.add_interval_callable(graph_plotly_run.thread_run, run_interval_second=60)