INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Formats props for the React template. Args: props (dict): properties to be written to the template. Returns: Two lists, one containing variable names and the other containing a list of props to be fed to the React template.
def format_props(props, prop_template="{{k}} = { {{v}} }", delim="\n"): """ Formats props for the React template. Args: props (dict): properties to be written to the template. Returns: Two lists, one containing variable names and the other containing a list of p...
register UILayout with the flask app create a function that will send props for each UILayout Args: layouts (dict): dict of UILayout objects by name app (object): flask app url (string): address of props; default is /api/props/
def register_layouts(layouts, app, url="/api/props/", brand="Pyxley"): """ register UILayout with the flask app create a function that will send props for each UILayout Args: layouts (dict): dict of UILayout objects by name app (object): flask app url (string): ...
Register the api route function with the app.
def register_route(self, app): """Register the api route function with the app.""" if "url" not in self.params["options"]: raise Exception("Component does not have a URL property") if not hasattr(self.route_func, "__call__"): raise Exception("No app route function suppli...
Render the component to a javascript file.
def render(self, path): """Render the component to a javascript file.""" return ReactComponent( self.layout, self.src_file, self.component_id, props=self.props, static_path=path)
Add a filter to the layout.
def add_filter(self, component, filter_group="pyxley-filter"): """Add a filter to the layout.""" if getattr(component, "name") != "Filter": raise Exception("Component is not an instance of Filter") if filter_group not in self.filters: self.filters[filter_group] = [] ...
Add a chart to the layout.
def add_chart(self, component): """Add a chart to the layout.""" if getattr(component, "name") != "Chart": raise Exception("Component is not an instance of Chart") self.charts.append(component)
Build the props dictionary.
def build_props(self): """Build the props dictionary.""" props = {} if self.filters: props["filters"] = {} for grp in self.filters: props["filters"][grp] = [f.params for f in self.filters[grp]] if self.charts: props["charts"] = [c.param...
Register routes with the app.
def assign_routes(self, app): """Register routes with the app.""" for grp in self.filters: for f in self.filters[grp]: if f.route_func: f.register_route(app) for c in self.charts: if c.route_func: c.register_route(app)
Write to javascript.
def render_layout(self, app, path, alias=None): """Write to javascript.""" self.assign_routes(app) return ReactComponent( self.layout, self.src_file, self.component_id, props=self.build_props(), static_path=path, alias=alias...
Format output for json response.
def to_json(df, x, y, timeseries=False): """Format output for json response.""" values = {k: [] for k in y} for i, row in df.iterrows(): for yy in y: values[yy].append({ "x": row[x], "y": row[yy] }) r...
Return the path to the javascript bundle
def default_static_path(): """ Return the path to the javascript bundle """ fdir = os.path.dirname(__file__) return os.path.abspath(os.path.join(fdir, '../assets/'))
Return the path to the index.html
def default_template_path(): """ Return the path to the index.html """ fdir = os.path.dirname(__file__) return os.path.abspath(os.path.join(fdir, '../assets/'))
create a mg line plot Args: df (pandas.DataFrame): data to plot
def create_line_plot(df): """ create a mg line plot Args: df (pandas.DataFrame): data to plot """ fig = Figure("/mg/line_plot/", "mg_line_plot") fig.graphics.transition_on_update(True) fig.graphics.animate_on_load() fig.layout.set_size(width=450, height=200) fig.layout.s...
create a mg line plot Args: df (pandas.DataFrame): data to plot
def create_histogram(df): """ create a mg line plot Args: df (pandas.DataFrame): data to plot """ fig = Figure("/mg/histogram/", "mg_histogram") fig.layout.set_size(width=450, height=200) fig.layout.set_margin(left=40, right=40) fig.graphics.animate_on_load() # Make a h...
create a mg line plot Args: df (pandas.DataFrame): data to plot
def create_scatterplot(df): """ create a mg line plot Args: df (pandas.DataFrame): data to plot """ fig = Figure("/mg/scatter/", "mg_scatter") fig.layout.set_size(width=450, height=200) fig.layout.set_margin(left=40, right=40) fig.graphics.animate_on_load() init_params ...
Set x-axis limits. Accepts a two-element list to set the x-axis limits. Args: xlim (list): lower and upper bounds Raises: ValueError: xlim must contain two elements ValueError: Min must be less than max
def set_xlim(self, xlim): """ Set x-axis limits. Accepts a two-element list to set the x-axis limits. Args: xlim (list): lower and upper bounds Raises: ValueError: xlim must contain two elements ValueError: Min must be less t...
Set y-axis limits. Accepts a two-element list to set the y-axis limits. Args: ylim (list): lower and upper bounds Raises: ValueError: ylim must contain two elements ValueError: Min must be less than max
def set_ylim(self, ylim): """ Set y-axis limits. Accepts a two-element list to set the y-axis limits. Args: ylim (list): lower and upper bounds Raises: ValueError: ylim must contain two elements ValueError: Min must be less t...
Retrieve options set by user.
def get(self): """ Retrieve options set by user.""" return {k:v for k,v in list(self.options.items()) if k in self._allowed_axes}
basic line plot dataframe to json for a line plot Args: df (pandas.DataFrame): input dataframe xypairs (list): list of tuples containing column names mode (str): plotly.js mode (e.g. lines) layout (dict): layout parameters ...
def line_plot(df, xypairs, mode, layout={}, config=_BASE_CONFIG): """ basic line plot dataframe to json for a line plot Args: df (pandas.DataFrame): input dataframe xypairs (list): list of tuples containing column names mode (str): plotly...
Format output for the json response.
def to_json(df, values): """Format output for the json response.""" records = [] if df.empty: return {"data": []} sum_ = float(np.sum([df[c].iloc[0] for c in values])) for c in values: records.append({ "label": values[c], "...
Transforms dataframe to json response
def to_json(df, state_index, color_index, fills): """Transforms dataframe to json response""" records = {} for i, row in df.iterrows(): records[row[state_index]] = { "fillKey": row[color_index] } return { "data": records, ...
**Description** Retrieve the device shadow JSON document from AWS IoT by publishing an empty JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Retrieved shadow JSON document ...
def shadowGet(self, srcCallback, srcTimeout): """ **Description** Retrieve the device shadow JSON document from AWS IoT by publishing an empty JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regardin...
**Description** Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive responses from AWS IoT regarding the result of the get operation. Response will be ...
def shadowUpdate(self, srcJSONPayload, srcCallback, srcTimeout): """ **Description** Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics. Shadow response topics will be subscribed to receive res...
**Description** Listen on delta topics for this device shadow by subscribing to delta topics. Whenever there is a difference between the desired and reported state, the registered callback will be called and the delta payload will be available in the callback. **Syntax** .. ...
def shadowRegisterDeltaCallback(self, srcCallback): """ **Description** Listen on delta topics for this device shadow by subscribing to delta topics. Whenever there is a difference between the desired and reported state, the registered callback will be called and the delta pay...
**Description** Cancel listening on delta topics for this device shadow by unsubscribing to delta topics. There will be no delta messages received after this API call even though there is a difference between the desired and reported state. **Syntax** .. code:: python ...
def shadowUnregisterDeltaCallback(self): """ **Description** Cancel listening on delta topics for this device shadow by unsubscribing to delta topics. There will be no delta messages received after this API call even though there is a difference between the desired and reporte...
**Description** Used to configure the last will topic, payload and QoS of the client. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureLastWill("last/Will/Topic", "lastWillPayload", 0) **Parameters** *topic* - Topic name tha...
def configureLastWill(self, topic, payload, QoS, retain=False): """ **Description** Used to configure the last will topic, payload and QoS of the client. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureLastWill("last/Will/Top...
**Description** Used to configure the host name and port number the client tries to connect to. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureEndpoint("random.iot.region.amazonaws.com", 8883) **Parameters** *hostN...
def configureEndpoint(self, hostName, portNumber): """ **Description** Used to configure the host name and port number the client tries to connect to. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureEndpoint("random.i...
**Description** Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureIAMCredentials(obtainedAccessKeyID, obtainedSecretAccessKey, obtainedSess...
def configureIAMCredentials(self, AWSAccessKeyID, AWSSecretAccessKey, AWSSessionToken=""): """ **Description** Used to configure/update the custom IAM credentials for Websocket SigV4 connection to AWS IoT. Should be called before connect. **Syntax** .. code:: python ...
**Description** Used to configure the rootCA, private key and certificate files. Should be called before connect. **Syntax** .. code:: python myAWSIoTMQTTClient.configureCredentials("PATH/TO/ROOT_CA", "PATH/TO/PRIVATE_KEY", "PATH/TO/CERTIFICATE") **Parameters** *C...
def configureCredentials(self, CAFilePath, KeyPath="", CertificatePath=""): # Should be good for MutualAuth certs config and Websocket rootCA config """ **Description** Used to configure the rootCA, private key and certificate files. Should be called before connect. **Syntax** ...
**Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. **Syntax** .. code:: python # Configure the auto-reconnect backoff to start with 1 second and use 128 seconds as a maximum back off time. # Connection over 20 seconds is ...
def configureAutoReconnectBackoffTime(self, baseReconnectQuietTimeSecond, maxReconnectQuietTimeSecond, stableConnectionTimeSecond): """ **Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. **Syntax** .. code:: python ...
**Description** Used to configure the queue size and drop behavior for the offline requests queueing. Should be called before connect. Queueable offline requests include publish, subscribe and unsubscribe. **Syntax** .. code:: python import AWSIoTPythonSDK.MQTTLib as AWSIoT...
def configureOfflinePublishQueueing(self, queueSize, dropBehavior=DROP_NEWEST): """ **Description** Used to configure the queue size and drop behavior for the offline requests queueing. Should be called before connect. Queueable offline requests include publish, subscribe and unsubscrib...
**Description** Connect asynchronously to AWS IoT, with user-specific keepalive interval configuration and CONNACK callback. **Syntax** .. code:: python # Connect to AWS IoT with default keepalive set to 600 seconds and a custom CONNACK callback myAWSIoTMQTTClient.connect...
def connectAsync(self, keepAliveIntervalSecond=600, ackCallback=None): """ **Description** Connect asynchronously to AWS IoT, with user-specific keepalive interval configuration and CONNACK callback. **Syntax** .. code:: python # Connect to AWS IoT with default keep...
**Description** Publish a new message to the desired topic with QoS. **Syntax** .. code:: python # Publish a QoS0 message "myPayload" to topic "myTopic" myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0) # Publish a QoS1 message "myPayloadWithQos1" to topic "...
def publish(self, topic, payload, QoS): """ **Description** Publish a new message to the desired topic with QoS. **Syntax** .. code:: python # Publish a QoS0 message "myPayload" to topic "myTopic" myAWSIoTMQTTClient.publish("myTopic", "myPayload", 0) ...
**Description** Publish a new message asynchronously to the desired topic with QoS and PUBACK callback. Note that the ack callback configuration for a QoS0 publish request will be ignored as there are no PUBACK reception. **Syntax** .. code:: python # Publish a QoS0 message...
def publishAsync(self, topic, payload, QoS, ackCallback=None): """ **Description** Publish a new message asynchronously to the desired topic with QoS and PUBACK callback. Note that the ack callback configuration for a QoS0 publish request will be ignored as there are no PUBACK reception...
**Description** Subscribe to the desired topic and register a callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0 and register a callback myAWSIoTMQTTClient.subscribe("myTopic", 0, customCallback) # Subscribe to "myTopic/#" with QoS1 and reg...
def subscribe(self, topic, QoS, callback): """ **Description** Subscribe to the desired topic and register a callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0 and register a callback myAWSIoTMQTTClient.subscribe("myTopic", 0, customC...
**Description** Subscribe to the desired topic and register a message callback with SUBACK callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0, custom SUBACK callback and a message callback myAWSIoTMQTTClient.subscribe("myTopic", 0, ackCallback=mySuba...
def subscribeAsync(self, topic, QoS, ackCallback=None, messageCallback=None): """ **Description** Subscribe to the desired topic and register a message callback with SUBACK callback. **Syntax** .. code:: python # Subscribe to "myTopic" with QoS0, custom SUBACK callb...
**Description** Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: python myShadowClient.configureLastWill("last/Will/Topic", ...
def configureLastWill(self, topic, payload, QoS): """ **Description** Used to configure the last will topic, payload and QoS of the client. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: ...
**Description** Used to configure/update the custom IAM credentials for the underneath AWS IoT MQTT Client for Websocket SigV4 connection to AWS IoT. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code...
def configureIAMCredentials(self, AWSAccessKeyID, AWSSecretAccessKey, AWSSTSToken=""): """ **Description** Used to configure/update the custom IAM credentials for the underneath AWS IoT MQTT Client for Websocket SigV4 connection to AWS IoT. Should be called before connect. This is a pu...
**Description** Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: python myShadowClient.clearLastWill("PATH/TO/ROOT_CA", "PATH/TO/...
def configureCredentials(self, CAFilePath, KeyPath="", CertificatePath=""): # Should be good for MutualAuth and Websocket """ **Description** Used to configure the rootCA, private key and certificate files. Should be called before connect. This is a public facing API inherited by appli...
**Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by application level public clients. **Syntax** .. code:: python # Configure the auto-reconnect backoff to start with 1 second and use...
def configureAutoReconnectBackoffTime(self, baseReconnectQuietTimeSecond, maxReconnectQuietTimeSecond, stableConnectionTimeSecond): """ **Description** Used to configure the auto-reconnect backoff timing. Should be called before connect. This is a public facing API inherited by applicat...
**Description** Create a device shadow handler using the specified shadow name and isPersistentSubscribe. **Syntax** .. code:: python # Create a device shadow handler for shadow named "Bot1", using persistent subscription Bot1Shadow = myAWSIoTMQTTShadowClient.createShadow...
def createShadowHandlerWithName(self, shadowName, isPersistentSubscribe): """ **Description** Create a device shadow handler using the specified shadow name and isPersistentSubscribe. **Syntax** .. code:: python # Create a device shadow handler for shadow named "Bot...
**Description** Synchronously creates an MQTT subscription to a jobs related topic based on the provided arguments **Syntax** .. code:: python #Subscribe to notify-next topic to monitor change in job referred to by $next myAWSIoTMQTTJobsClient.createJobSubscription(callba...
def createJobSubscription(self, callback, jobExecutionType=jobExecutionTopicType.JOB_WILDCARD_TOPIC, jobReplyType=jobExecutionTopicReplyType.JOB_REQUEST_TYPE, jobId=None): """ **Description** Synchronously creates an MQTT subscription to a jobs related topic based on the provided arguments ...
**Description** Asynchronously creates an MQTT subscription to a jobs related topic based on the provided arguments **Syntax** .. code:: python #Subscribe to notify-next topic to monitor change in job referred to by $next myAWSIoTMQTTJobsClient.createJobSubscriptionAsync(...
def createJobSubscriptionAsync(self, ackCallback, callback, jobExecutionType=jobExecutionTopicType.JOB_WILDCARD_TOPIC, jobReplyType=jobExecutionTopicReplyType.JOB_REQUEST_TYPE, jobId=None): """ **Description** Asynchronously creates an MQTT subscription to a jobs related topic based on the prov...
**Description** Publishes an MQTT jobs related request for a potentially specific jobId (or wildcard) **Syntax** .. code:: python #send a request to describe the next job myAWSIoTMQTTJobsClient.sendJobsQuery(jobExecutionTopicType.JOB_DESCRIBE_TOPIC, '$next') #se...
def sendJobsQuery(self, jobExecTopicType, jobId=None): """ **Description** Publishes an MQTT jobs related request for a potentially specific jobId (or wildcard) **Syntax** .. code:: python #send a request to describe the next job myAWSIoTMQTTJobsClient.sen...
**Description** Publishes an MQTT message to the StartNextJobExecution topic. This will attempt to get the next pending job execution and change its status to IN_PROGRESS. **Syntax** .. code:: python #Start next job (set status to IN_PROGRESS) and update with optional statu...
def sendJobsStartNext(self, statusDetails=None): """ **Description** Publishes an MQTT message to the StartNextJobExecution topic. This will attempt to get the next pending job execution and change its status to IN_PROGRESS. **Syntax** .. code:: python #Star...
**Description** Publishes an MQTT message to a corresponding job execution specific topic to update its status according to the parameters. Can be used to change a job from QUEUED to IN_PROGRESS to SUCEEDED or FAILED. **Syntax** .. code:: python #Update job with id 'jobId12...
def sendJobsUpdate(self, jobId, status, statusDetails=None, expectedVersion=0, executionNumber=0, includeJobExecutionState=False, includeJobDocument=False): """ **Description** Publishes an MQTT message to a corresponding job execution specific topic to update its status according to the parame...
**Description** Publishes a method to the describe topic for a particular job. **Syntax** .. code:: python #Describe job with id 'jobId1' of any executionNumber, job document will be included in response myAWSIoTMQTTJobsClient.sendJobsDescribe('jobId1') #Descri...
def sendJobsDescribe(self, jobId, executionNumber=0, includeJobDocument=True): """ **Description** Publishes a method to the describe topic for a particular job. **Syntax** .. code:: python #Describe job with id 'jobId1' of any executionNumber, job document will be ...
Return the error string associated with an mqtt error number.
def error_string(mqtt_errno): """Return the error string associated with an mqtt error number.""" if mqtt_errno == MQTT_ERR_SUCCESS: return "No error." elif mqtt_errno == MQTT_ERR_NOMEM: return "Out of memory." elif mqtt_errno == MQTT_ERR_PROTOCOL: return "A network protocol erro...
Check whether a topic matches a subscription. For example: foo/bar would match the subscription foo/# or +/bar non/matching would not match the subscription non/+/+
def topic_matches_sub(sub, topic): """Check whether a topic matches a subscription. For example: foo/bar would match the subscription foo/# or +/bar non/matching would not match the subscription non/+/+ """ result = True multilevel_wildcard = False slen = len(sub) tlen = len(topic...
TCP/IP socketpair including Windows support
def _socketpair_compat(): """TCP/IP socketpair including Windows support""" listensock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP) listensock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listensock.bind(("127.0.0.1", 0)) listensock.listen(1) iface, port = lis...
Make custom settings for backoff timing for reconnect logic srcBaseReconnectTimeSecond - The base reconnection time in seconds srcMaximumReconnectTimeSecond - The maximum reconnection time in seconds srcMinimumConnectTimeSecond - The minimum time in seconds that a connection must be maintained i...
def setBackoffTiming(self, srcBaseReconnectTimeSecond, srcMaximumReconnectTimeSecond, srcMinimumConnectTimeSecond): """ Make custom settings for backoff timing for reconnect logic srcBaseReconnectTimeSecond - The base reconnection time in seconds srcMaximumReconnectTimeSecond - The maxim...
Make custom settings for IAM credentials for websocket connection srcAWSAccessKeyID - AWS IAM access key srcAWSSecretAccessKey - AWS IAM secret key srcAWSSessionToken - AWS Session Token
def configIAMCredentials(self, srcAWSAccessKeyID, srcAWSSecretAccessKey, srcAWSSessionToken): """ Make custom settings for IAM credentials for websocket connection srcAWSAccessKeyID - AWS IAM access key srcAWSSecretAccessKey - AWS IAM secret key srcAWSSessionToken - AWS Session T...
Configure network encryption and authentication options. Enables SSL/TLS support. ca_certs : a string path to the Certificate Authority certificate files that are to be treated as trusted by this client. If this is the only option given then the client will operate in a similar manner to a web ...
def tls_set(self, ca_certs, certfile=None, keyfile=None, cert_reqs=cert_reqs, tls_version=tls_version, ciphers=None): """Configure network encryption and authentication options. Enables SSL/TLS support. ca_certs : a string path to the Certificate Authority certificate files that are to be treat...
Connect to a remote broker. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 8883 so if you are using tls_set() the port may need providing. k...
def connect(self, host, port=1883, keepalive=60, bind_address=""): """Connect to a remote broker. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. Note that the default port for MQTT over SSL/TLS is 888...
Connect to a remote broker. domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive and bind_address are as for connect()
def connect_srv(self, domain=None, keepalive=60, bind_address=""): """Connect to a remote broker. domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive and bind_address are as for connect() """ if HAVE_DNS is False: ...
Connect to a remote broker asynchronously. This is a non-blocking connect call that can be used with loop_start() to provide very quick start. host is the hostname or IP address of the remote broker. port is the network port of the server host to connect to. Defaults to 1883. No...
def connect_async(self, host, port=1883, keepalive=60, bind_address=""): """Connect to a remote broker asynchronously. This is a non-blocking connect call that can be used with loop_start() to provide very quick start. host is the hostname or IP address of the remote broker. por...
Reconnect the client after a disconnect. Can only be called after connect()/connect_async().
def reconnect(self): """Reconnect the client after a disconnect. Can only be called after connect()/connect_async().""" if len(self._host) == 0: raise ValueError('Invalid host.') if self._port <= 0: raise ValueError('Invalid port number.') self._in_packet...
Process network events. This function must be called regularly to ensure communication with the broker is carried out. It calls select() on the network socket to wait for network events. If incoming data is present it will then be processed. Outgoing commands, from e.g. publish(), are n...
def loop(self, timeout=1.0, max_packets=1): """Process network events. This function must be called regularly to ensure communication with the broker is carried out. It calls select() on the network socket to wait for network events. If incoming data is present it will then be p...
Publish a message on a topic. This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics. topic: The topic that the message should be published on. payload: The actual message to send. If not given, or set to None a ...
def publish(self, topic, payload=None, qos=0, retain=False): """Publish a message on a topic. This causes a message to be sent to the broker and subsequently from the broker to any clients subscribing to matching topics. topic: The topic that the message should be published on. ...
Set a username and optionally a password for broker authentication. Must be called before connect() to have any effect. Requires a broker that supports MQTT v3.1. username: The username to authenticate with. Need have no relationship to the client id. password: The password to authenti...
def username_pw_set(self, username, password=None): """Set a username and optionally a password for broker authentication. Must be called before connect() to have any effect. Requires a broker that supports MQTT v3.1. username: The username to authenticate with. Need have no relationsh...
Disconnect a connected client from the broker.
def disconnect(self): """Disconnect a connected client from the broker.""" self._state_mutex.acquire() self._state = mqtt_cs_disconnecting self._state_mutex.release() self._backoffCore.stopStableConnectionTimer() if self._sock is None and self._ssl is None: ...
Subscribe the client to one or more topics. This function may be called in three different ways: Simple string and integer ------------------------- e.g. subscribe("my/topic", 2) topic: A string specifying the subscription topic to subscribe to. qos: The desired qualit...
def subscribe(self, topic, qos=0): """Subscribe the client to one or more topics. This function may be called in three different ways: Simple string and integer ------------------------- e.g. subscribe("my/topic", 2) topic: A string specifying the subscription topic to...
Unsubscribe the client from one or more topics. topic: A single string, or list of strings that are the subscription topics to unsubscribe from. Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_ERR_NO_CONN, None) if the client is not ...
def unsubscribe(self, topic): """Unsubscribe the client from one or more topics. topic: A single string, or list of strings that are the subscription topics to unsubscribe from. Returns a tuple (result, mid), where result is MQTT_ERR_SUCCESS to indicate success or (MQTT_...
Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application. Use socket() to obtain the client socket to call select() or equivalent on. Do not use if you are using the threaded interface loop_start().
def loop_read(self, max_packets=1): """Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application. Use socket() to obtain the client socket to call select() or equivalent on. Do not use if you are using th...
Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application. Use socket() to obtain the client socket to call select() or equivalent on. Use want_write() to determine if there is data waiting to be written. ...
def loop_write(self, max_packets=1): """Process read network events. Use in place of calling loop() if you wish to handle your client reads as part of your own application. Use socket() to obtain the client socket to call select() or equivalent on. Use want_write() to determine...
Process miscellaneous network events. Use in place of calling loop() if you wish to call select() or equivalent on. Do not use if you are using the threaded interface loop_start().
def loop_misc(self): """Process miscellaneous network events. Use in place of calling loop() if you wish to call select() or equivalent on. Do not use if you are using the threaded interface loop_start().""" if self._sock is None and self._ssl is None: return MQTT_ERR_NO_CON...
Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message to send as a will. If not given, or set to None a zero length me...
def will_set(self, topic, payload=None, qos=0, retain=False): """Set a Will to be sent by the broker in case the client disconnects unexpectedly. This must be called before connect() to have any effect. topic: The topic that the will message should be published on. payload: The message...
Removes a will that was previously configured with will_set(). Must be called before connect() to have any effect.
def will_clear(self): """ Removes a will that was previously configured with will_set(). Must be called before connect() to have any effect.""" self._will = False self._will_topic = "" self._will_payload = None self._will_qos = 0 self._will_retain = False
Return the socket or ssl object for this client.
def socket(self): """Return the socket or ssl object for this client.""" if self._ssl: if self._useSecuredWebsocket: return self._ssl.getSSLSocket() else: return self._ssl else: return self._sock
This function call loop() for you in an infinite blocking loop. It is useful for the case where you only want to run the MQTT client loop in your program. loop_forever() will handle reconnecting for you. If you call disconnect() in a callback it will return. timeout: The time ...
def loop_forever(self, timeout=1.0, max_packets=1, retry_first_connection=False): """This function call loop() for you in an infinite blocking loop. It is useful for the case where you only want to run the MQTT client loop in your program. loop_forever() will handle reconnecting for you...
This is part of the threaded client interface. Call this once to start a new thread to process network traffic. This provides an alternative to repeatedly calling loop() yourself.
def loop_start(self): """This is part of the threaded client interface. Call this once to start a new thread to process network traffic. This provides an alternative to repeatedly calling loop() yourself. """ if self._thread is not None: return MQTT_ERR_INVAL ...
This is part of the threaded client interface. Call this once to stop the network thread previously created with loop_start(). This call will block until the network thread finishes. The force parameter is currently ignored.
def loop_stop(self, force=False): """This is part of the threaded client interface. Call this once to stop the network thread previously created with loop_start(). This call will block until the network thread finishes. The force parameter is currently ignored. """ if se...
Register a message callback for a specific topic. Messages that match 'sub' will be passed to 'callback'. Any non-matching messages will be passed to the default on_message callback. Call multiple times with different 'sub' to define multiple topic specific callbacks. ...
def message_callback_add(self, sub, callback): """Register a message callback for a specific topic. Messages that match 'sub' will be passed to 'callback'. Any non-matching messages will be passed to the default on_message callback. Call multiple times with different 'su...
Remove a message callback previously registered with message_callback_add().
def message_callback_remove(self, sub): """Remove a message callback previously registered with message_callback_add().""" if sub is None: raise ValueError("sub must defined.") self._callback_mutex.acquire() for i in range(0, len(self.on_message_filtered)): ...
compile for the platform we are running on
def createproject(): """ compile for the platform we are running on """ os.chdir(build_dir) if windows_build: command = 'cmake -A {} -DPYTHON_EXECUTABLE:FILEPATH="{}" ../..'.format("win32" if bitness==32 else "x64", sys.executable) os.system(command) if bitness==64: for l...
A basic request: >>> responses.add(responses.GET, 'http://example.com') You can also directly pass an object which implements the ``BaseResponse`` interface: >>> responses.add(Response(...)) A JSON payload: >>> responses.add( >>> method='GET', >>>...
def add( self, method=None, # method or ``Response`` url=None, body="", adding_headers=None, *args, **kwargs ): """ A basic request: >>> responses.add(responses.GET, 'http://example.com') You can also directly pass an object ...
Register a URL prefix to passthru any non-matching mock requests to. For example, to allow any request to 'https://example.com', but require mocks for the remainder, you would add the prefix as so: >>> responses.add_passthru('https://example.com')
def add_passthru(self, prefix): """ Register a URL prefix to passthru any non-matching mock requests to. For example, to allow any request to 'https://example.com', but require mocks for the remainder, you would add the prefix as so: >>> responses.add_passthru('https://example....
Removes a response previously added using ``add()``, identified either by a response object inheriting ``BaseResponse`` or ``method`` and ``url``. Removes all matching responses. >>> response.add(responses.GET, 'http://example.org') >>> response.remove(responses.GET, 'http://example.org...
def remove(self, method_or_response=None, url=None): """ Removes a response previously added using ``add()``, identified either by a response object inheriting ``BaseResponse`` or ``method`` and ``url``. Removes all matching responses. >>> response.add(responses.GET, 'http://exa...
Replaces a response previously added using ``add()``. The signature is identical to ``add()``. The response is identified using ``method`` and ``url``, and the first matching response is replaced. >>> responses.add(responses.GET, 'http://example.org', json={'data': 1}) >>> responses.rep...
def replace(self, method_or_response=None, url=None, body="", *args, **kwargs): """ Replaces a response previously added using ``add()``. The signature is identical to ``add()``. The response is identified using ``method`` and ``url``, and the first matching response is replaced. ...
Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string`, a file-like object, or a generator of strings. If `xml_attribs` is `True`, element attributes are put in the dictionary among regular child elements, using `@` as a prefix to avoid collisions. If set to `...
def parse(xml_input, encoding=None, expat=expat, process_namespaces=False, namespace_separator=':', disable_entities=True, **kwargs): """Parse the given XML input and convert it into a dictionary. `xml_input` can either be a `string`, a file-like object, or a generator of strings. If `xml_attrib...
Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is specified, it is written there instead. Dictionary keys prefixed with `attr_prefix` (default=`'@'`) are interpreted as XML node attributes, ...
def unparse(input_dict, output=None, encoding='utf-8', full_document=True, short_empty_elements=False, **kwargs): """Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is spec...
Build Setuptools egg.
def _build_egg(egg, archive_filename, to_dir): """Build Setuptools egg.""" with archive_context(archive_filename): # building an egg log.warn('Building a Setuptools egg in %s', to_dir) _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) # returning the result log.war...
Install Setuptools.
def _install(archive_filename, install_args=()): """Install Setuptools.""" with archive_context(archive_filename): # installing log.warn('Installing Setuptools') if not _python_cmd('setup.py', 'install', *install_args): log.warn('Something went wrong during the installation.'...
Unzip filename to a temporary directory, set to the cwd. The unzipped target is cleaned up after.
def archive_context(filename): """ Unzip filename to a temporary directory, set to the cwd. The unzipped target is cleaned up after. """ tmpdir = tempfile.mkdtemp() log.warn('Extracting in %s', tmpdir) old_wd = os.getcwd() try: os.chdir(tmpdir) try: with Cont...
Download Setuptools.
def _do_download(version, download_base, to_dir, download_delay): """Download Setuptools.""" py_desig = 'py{sys.version_info[0]}.{sys.version_info[1]}'.format(sys=sys) tp = 'setuptools-{version}-{py_desig}.egg' egg = os.path.join(to_dir, tp.format(**locals())) if not os.path.exists(egg): arc...
Ensure that a setuptools version is installed. Return None. Raise SystemExit if the requested version or later cannot be installed.
def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=DEFAULT_SAVE_DIR, download_delay=15): """ Ensure that a setuptools version is installed. Return None. Raise SystemExit if the requested version or later cannot be installed. """ to_dir = os.path.abspa...
Setuptools was imported prior to invocation, so it is unsafe to unload it. Bail out.
def _conflict_bail(VC_err, version): """ Setuptools was imported prior to invocation, so it is unsafe to unload it. Bail out. """ conflict_tmpl = textwrap.dedent(""" The required version of setuptools (>={version}) is not available, and can't be installed while this script is running...
Use Python to download the file, without connection authentication.
def download_file_insecure(url, target): """Use Python to download the file, without connection authentication.""" src = urlopen(url) try: # Read all the data in one block. data = src.read() finally: src.close() # Write all the data in one block to avoid creating a partial f...
Return args for download_setuptools function from cmdline args.
def _download_args(options): """Return args for download_setuptools function from cmdline args.""" return dict( version=options.version, download_base=options.download_base, downloader_factory=options.downloader_factory, to_dir=options.to_dir, )
Install or upgrade setuptools and EasyInstall.
def main(): """Install or upgrade setuptools and EasyInstall.""" options = _parse_args() archive = download_setuptools(**_download_args(options)) return _install(archive, _build_install_args(options))
round to closest resolution
def roundClosestValid(val, res, decimals=None): """ round to closest resolution """ if decimals is None and "." in str(res): decimals = len(str(res).split('.')[1]) return round(round(val / res) * res, decimals)
Establish connection to TWS/IBGW
def connect(self, clientId=0, host="localhost", port=4001): """ Establish connection to TWS/IBGW """ self.clientId = clientId self.host = host self.port = port self.ibConn = Connection.create( host=self.host, port=int(self.port), clientId=self....
Disconnect from TWS/IBGW
def disconnect(self): """ Disconnect from TWS/IBGW """ if self.ibConn is not None: self.log.info("[DISCONNECT FROM IB]") self.ibConn.disconnect() self._disconnected_by_user = True
used for when callback receives a contract that isn't found in local database
def registerContract(self, contract): """ used for when callback receives a contract that isn't found in local database """ if contract.m_exchange == "": return """ if contract not in self.contracts.values(): contract_tuple = self.contract_to_tuple(contr...
logs error messages
def handleErrorEvents(self, msg): """ logs error messages """ # https://www.interactivebrokers.com/en/software/api/apiguide/tables/api_message_codes.htm if msg.errorCode is not None and msg.errorCode != -1 and \ msg.errorCode not in dataTypes["BENIGN_ERROR_CODES"]: l...
dispatch msg to the right handler
def handleServerEvents(self, msg): """ dispatch msg to the right handler """ self.log.debug('MSG %s', msg) self.handleConnectionState(msg) if msg.typeName == "error": self.handleErrorEvents(msg) elif msg.typeName == dataTypes["MSG_CURRENT_TIME"]: if sel...
:Return: True if IBPy message `msg` indicates the connection is unavailable for any reason, else False.
def handleConnectionState(self, msg): """:Return: True if IBPy message `msg` indicates the connection is unavailable for any reason, else False.""" self.connected = not (msg.typeName == "error" and msg.errorCode in dataTypes["DISCONNECT_ERROR_CODES"]) if self.conne...
handles contractDetails and contractDetailsEnd
def handleContractDetails(self, msg, end=False): """ handles contractDetails and contractDetailsEnd """ if end: # mark as downloaded self._contract_details[msg.reqId]['downloaded'] = True # move details from temp to permanent collector self.contract_deta...
handle account info update https://www.interactivebrokers.com/en/software/api/apiguide/java/updateaccountvalue.htm
def handleAccount(self, msg): """ handle account info update https://www.interactivebrokers.com/en/software/api/apiguide/java/updateaccountvalue.htm """ # parse value try: msg.value = float(msg.value) except Exception: msg.value = msg.valu...
handle positions changes
def handlePosition(self, msg): """ handle positions changes """ # log handler msg self.log_msg("position", msg) # contract identifier contract_tuple = self.contract_to_tuple(msg.contract) contractString = self.contractString(contract_tuple) # try creating the c...