This is Part 2 of 3 in the Up and Running with Xively on Python with xiPy Series
Now that we've got the Xively xiPy library installed we can start having some fun. In this part we'll:
- Create an Organization to group our devices and users
- Create a Device Template that defines our device properties and communication channels
- Create a Device using this template
- Configure our IoT device to connect to Xively's MQTT broker
The first thing to do is create a new device in the Xively Management App. Your login credentials for the Managment App were rel="noopener noreferrer" sent to you when you created your rel="noopener noreferrer" Xively account.
Log in to the Xively Management App.
If you haven't already created an Organization, navigate to Templates → Organization Templates, and select the Default Organization Template. Click the Add New Organization button at the top-right of your screen.
In this case, we've called our new Organization Coria, but you can call it whatever you like. An Organization is a logical grouping of devices and users.
Our new device type is going to have its own set of communication channels, and those channels are defined at the device template level. Navigate to Templates→ Device Templates and click the Add New Device Template button at the top-right of the screen.
Again, we've called ours xiPy Demo Device Template, but you can call it what you see fit. For now, just ignore the Custom Fields and Channels, we'll get to them later.
The important thing to remember is that the communications channels used by all devices using this template are defined in the template. Later on in this tutorial we'll add communication channels to the template, and all the devices using this template will inherit those new channels even after they've been created. This comes in very handy, because it gives us the ability to easily add and remove channels from devices after they've been deployed in the field.
The next step is to register our newfangled IoT device in the Management App. We'll want to uniquely identify our device. We typically use the serial number of the processor board, but any unique identifier such as a MAC address will do. For the purpose of this tutorial, you can use anything. The important concept to understand is that later on, this identifier will be what you use to identify this specific device among the millions you have deployed in the field.
When you create your Device, you'll be taken to the Device Details screen.
Create a new file in your working directory called
config.py with the following content:
device_id = '<device_id>'
password = '<device_password>'
topic = '<device_topic_url>'
max_attempts = 3
At the bottom of the details panel you'll see your Device ID and Account ID. Paste the Device ID into
Click the Get Password button at the top right of the screen. The device password will be displayed. This is the only opportunity you will have to view and/or download this password (though it can be invalidated and regenerated at any time). Paste the password into
At the top of your screen you'll see three tabs: Overview, Messaging, and Logs. Click on the Messaging tab.
In the Messaging box you'll see your Device Topic URL. Paste your Device Topic URL into
Replace the content from the
xively.py file you created in Part 1 with the following:
import config from xiPy.xively_connection_parameters import XivelyConnectionParameters from xiPy.xively_client import XivelyClient from xiPy.xively_error_codes import XivelyErrorCodes max_attempts = config.max_attempts
def attempt_gen(): attempt = 0 while attempt < max_attempts: attempt += 1 yield attempt def on_connect_finished(client,result): if result == XivelyErrorCodes.XI_STATE_OK : print("[SUCCESS] Connected to Xively") else : try: attempt_number = next(attempt_gen()) except StopIteration: print(" [FAIL] Unable to connect after %d attempts." % max_attempts) sys.exit(-1) print(" [INFO] Connection try %d/%d" % (attempt_number, max_attempts)) print(" [ERROR] Connection error :" , result) print(" [INFO] Reconnecting to the broker ... ") client.connect(params) if __name__ == '__main__': client = XivelyClient() client.on_connect_finished = on_connect_finished params = XivelyConnectionParameters() params.use_websocket = False params.publish_count_send_time_period = 5 params.client_id = config.device_id params.username = config.device_id params.password = config.password print(" [INFO] ClientID: %s" %(params.client_id)) print(" [INFO] Username: %s" %(params.username)) print(" [INFO] Password: %s" %(params.password)) print(" [INFO] Connecting to Xively...") client.connect(params) client.join()
There are just a couple of things of note:
- The Client ID and Username are the same for the MQTT Broker. You can safely append a GUID to the end of the Client ID if you need multiple concurrent connections from the same device.
- It's a good idea to implement the automatic connection retries and auto-reconnect. Your device is inevitably going to have to deal with suboptimal network conditions. This device does not auto-reconnect, and that functionality does not (yet) exist in the core xiPy library. I certainly wouldn't rely on this snippet for anything other than tooling around.
- XivelyClient.on_connect_finished() is just one of several event handlers in the xiPy library that we'll get rel="noopener noreferrer" into later in this series. There's considerable rel="noopener noreferrer" documentation in the source.
Give it a quick test:
(venv) $ python xively.py [INFO] ClientID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx [INFO] Username: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx [INFO] Password: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX= [INFO] Connecting to Xively... [SUCCESS] Connected to Xively
In Part 3 of the Up and Running with Xively on Python with xiPy Series we'll subscribe to a Xively Topic and start sending commands to our IoT device. In Part 4 we'll start emitting simple notifications from our device. Part 5 will cover how to send time-series data to Xively. In Part 6 we'll throw together a lightweight front-end to control the device, and build an information radiator you can use to wow your PM.