Once you have connected your script using the Agent, you can use the “IOT.Client” of the Agent to connect a Thing. This is the final step in creating a complete Iotic Thing, with both representation in Iotic Space, and application in code.
If this is a new session, open a terminal and set the pythonpath in the directory py-IoticAgent.git with:
export PYTHONPATH=`pwd`/3rd:`pwd`/src
From a basic connected script, an addition of a few lines connects your Thing.
The same line is used to connect a Thing you have already created (eg in the browser), or, to create a new Thing. Calling create_thing
will create a new Thing in your specified Agent, or, if you have already created a Thing with that name, it will connect the script to that Thing. Here, we are using it to connect your Thing “My_First_Thing”. The name you give your Thing acts as its local ID (lid), allowing you to use it this way in code.
# PYTHON2 COMPATIBILITY -----------------------------------------------------------------------------------------------
from __future__ import unicode_literals, print_function # pylint: disable=unused-import
# LOGGING -------------------------------------------------------------------------------------------------------------
# Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s',
level=logging.CRITICAL)
# IMPORTS -------------------------------------------------------------------------------------------------------------
import time
# IOTIC AGENT IMPORTS -------------------------------------------------------------------------------------------------
from IoticAgent import IOT
# ---------------------------------------------------------------------------------------------------------------------
def connect_thing(client):
print("Connecting my first Thing")
# Create your Thing in this script
# Note:
# Calling 'create_thing' will connect a your script to a virtual Thing if the Local id (lid) is already in use,
# if not it creates a new Thing with this lid.
my_thing = client.create_thing('My_First_Thing') # GIVE IT A NAME
# That's all you need to connect (or create) a Thing.
return my_thing
# MAIN -------------------------------------------------------------------------------------------------------------
def main():
with IOT.Client(config='Getting_Started.ini') as client: # ADD OWN CONFIG .ini HERE
connect_thing(client)
while True:
try:
print("Main running, press ctrl+c to quit.")
time.sleep(10)
except KeyboardInterrupt:
break
# RUN --------------------------------------------------------------------------------------------------
if __name__ == '__main__':
main()
# END --------------------------------------------------------------------------------------------------
If you were to run this, you wouldn’t see any useful evidence of what you have done, so we will add a few lines to have a look at your Thing.
# PYTHON2 COMPATIBILITY -----------------------------------------------------------------------------------------------
from __future__ import unicode_literals, print_function # pylint: disable=unused-import
# LOGGING -------------------------------------------------------------------------------------------------------------
# Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s',
level=logging.CRITICAL)
# IMPORTS -------------------------------------------------------------------------------------------------------------
import time
# IOTIC AGENT IMPORTS -------------------------------------------------------------------------------------------------
from IoticAgent import IOT
# ---------------------------------------------------------------------------------------------------------------------
def connect_thing(client):
print("Connecting my first Thing")
# Create your Thing in this script
# Note:
# Calling 'create_thing' will connect a your script to a virtual Thing if the Local id (lid) is already in use,
# if not it creates a new Thing with this lid.
my_thing = client.create_thing('My_First_Thing') # GIVE IT A NAME
# That's all you need to connect (or create) a Thing.
# Let's have a look at it
# Print some information about your Thing
print("About my Thing")
print("My Thing object:", my_thing)
print("My Thing local ID (lid):", my_thing.lid)
print("My Thing globally unique ID (guid):", my_thing.guid)
return my_thing
# MAIN -------------------------------------------------------------------------------------------------------------
def main():
with IOT.Client(config='Getting_Started.ini') as client: # ADD OWN CONFIG .ini HERE
connect_thing(client)
while True:
try:
print("Main running, press ctrl+c to quit.")
time.sleep(10)
except KeyboardInterrupt:
break
# RUN --------------------------------------------------------------------------------------------------
if __name__ == '__main__':
main()
# END --------------------------------------------------------------------------------------------------
Save your work in your project folder as “connect_thing.py”.
In the terminal, navigate to that directory and run the script:
python3 connect_thing.py
You will see it print to screen your Thing object, your Thing local ID (lid), and your Thing globally unique ID (GUID).
Press ctrl+c to stop your script.
Now you have an Iotic Thing. You have set it up in your browser, assigned it to an Agent, and used that Agent to connect it to a script. Your application is now Iotic, with a representation in Iotic Space. Your application can access anything your representation can. They are now one-and-the same.
Let’s try this out by printing your Things metadata, tags, and information about interactions you set in your browser.
Add the following to print your metadata and subscriptions (Feeds you are following):
# PYTHON2 COMPATIBILITY -----------------------------------------------------------------------------------------------
from __future__ import unicode_literals, print_function
# LOGGING -------------------------------------------------------------------------------------------------------------
# Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s',
level=logging.CRITICAL)
# IMPORTS -------------------------------------------------------------------------------------------------------------
import time
# IOTIC AGENT IMPORTS -------------------------------------------------------------------------------------------------
from IoticAgent import IOT
# ---------------------------------------------------------------------------------------------------------------------
def connect_thing(client):
print("Connecting My First Thing")
# Create your Thing in this script
# Note:
# Calling 'create_thing' will connect a your script to a virtual Thing if the Local id (lid) is already in use,
# if not it creates a new Thing with this lid.
my_thing = client.create_thing('My_First_Thing') # GIVE IT A NAME
# Let's have a look at it
# print some information about your Thing
print("About my Thing")
print("My Thing object:", my_thing)
print("My Thing local ID (lid):", my_thing.lid)
print("My Thing globally unique ID (guid):", my_thing.guid)
return my_thing
def show_metadata(my_thing):
print("My metadata (simplified)")
# Get and print the metadata you set in the UI
with my_thing.get_meta() as my_metadata:
# get the label
my_labels = my_metadata.get_labels()
print("Returned labels:")
print(my_labels)
# get the description
my_descriptions = my_metadata.get_descriptions()
print("Returned descriptions:")
print(my_descriptions)
# get the location
# Note:
# If location not set, returns error
my_lat, my_lon = my_metadata.get_location()
print("Returned location lat = %f & lon = %f" % (my_lat, my_lon))
# List and print tags you set in the UI
print("Tags")
print("List of Tags for this Thing:")
tag_list = my_thing.list_tag()
print(tag_list)
def show_subscriptions(my_thing):
print("My subscriptions")
# List and print any subscriptions (Feeds following or Controls attached to)
# Note:
# In sub_list, 'id' is the Feed/Control global point ID (gpid)
sub_list = my_thing.list_connections()
print("Subscription list: ", sub_list)
# MAIN -------------------------------------------------------------------------------------------------------------
def main():
with IOT.Client(config='Getting_Started.ini') as client: # ADD OWN CONFIG .ini HERE
my_thing = connect_thing(client)
show_metadata(my_thing)
show_subscriptions(my_thing)
while True:
try:
print("Main running, press ctrl+c to quit.")
time.sleep(10)
except KeyboardInterrupt:
break
# RUN --------------------------------------------------------------------------------------------------
if __name__ == '__main__':
main()
# END --------------------------------------------------------------------------------------------------
Save and run your script. You will now see the following:
Your application can access anything its representation in Iotic Space knows. And in Iotic Space, this knowledge is power. Access to this metadata and subscription information gives you more than just the ability to view what you have set up, it gives you the power to use it in your code. For example, here we will use the subscription information to bring in the data from any feed you set your Thing to follow in the browser.
# PYTHON2 COMPATIBILITY -----------------------------------------------------------------------------------------------
from __future__ import unicode_literals, print_function # pylint: disable=unused-import
# LOGGING -------------------------------------------------------------------------------------------------------------
# Logging set to only CRITICAL messages by default. To see more, use logging.INFO, or to see loads, logging.DEBUG
import logging
logging.basicConfig(format='%(asctime)s,%(msecs)03d %(levelname)s [%(name)s] {%(threadName)s} %(message)s',
level=logging.CRITICAL)
# IMPORTS -------------------------------------------------------------------------------------------------------------
import time
# IOTIC AGENT IMPORTS -------------------------------------------------------------------------------------------------
from IoticAgent import IOT
from IoticAgent.Core.Const import R_FEED
# ---------------------------------------------------------------------------------------------------------------------
def connect_thing(client):
print("Connecting My First Thing")
# Create your Thing in this script
# Note:
# Calling 'create_thing' will connect a your script to a virtual Thing if the Local id (lid) is already in use,
# if not it creates a new Thing with this lid.
my_thing = client.create_thing('My_First_Thing') # GIVE IT A NAME
# Let's have a look at it
# print some information about your Thing
print("About my Thing")
print("My Thing object:", my_thing)
print("My Thing local ID (lid):", my_thing.lid)
print("My Thing globally unique ID (guid):", my_thing.guid)
return my_thing
def show_metadata(my_thing):
print("My metadata (simplified)")
# Get and print the metadata you set in the UI
with my_thing.get_meta() as my_metadata:
# get the label
my_labels = my_metadata.get_labels()
print("Returned labels:")
print(my_labels)
# get the description
my_descriptions = my_metadata.get_descriptions()
print("Returned descriptions:")
print(my_descriptions)
# get the location
# Note:
# If location not set, returns error.
my_lat, my_lon = my_metadata.get_location()
print("Returned location lat = %f & lon = %f" % (my_lat, my_lon))
# List and print tags you set in the UI
print("Tags")
print("List of Tags for this Thing:")
tag_list = my_thing.list_tag()
print(tag_list)
def connect_subscriptions(my_thing):
print("My subscriptions")
# List and print any subscriptions (Feeds following or Controls attached to)
# Note:
# In sub_list, 'id' is the Feed/Control global point ID (gpid)
sub_list = my_thing.list_connections()
# Get global Point ID (gpid) from this information and wire up the follow to the callback
for key in sub_list:
gpid = sub_list[key]['id']
if sub_list[key]['type'] == R_FEED:
my_thing.follow(gpid, follow_feed_callback)
print("Subscription gpid:", gpid)
def follow_feed_callback(args):
print("Printing data received from followed Feed")
# Tells your Thing what to do with data received from the Feed you are following
# Print data recieved from followed feed
print("This is the Feed Callback with data:", args['data'])
# MAIN -------------------------------------------------------------------------------------------------------------
def main():
with IOT.Client(config='Getting_Started.ini') as client: # ADD OWN CONFIG .ini HERE
my_thing = connect_thing(client)
show_metadata(my_thing)
while True:
try:
print("Main running, press ctrl+c to quit.")
connect_subscriptions(my_thing)
time.sleep(10)
except KeyboardInterrupt:
break
# RUN --------------------------------------------------------------------------------------------------
if __name__ == '__main__':
main()
# END --------------------------------------------------------------------------------------------------
This wires up your interactions, and removes printing your subscription list to avoid clutter.
Save your code, and run in the terminal. You will now see the interaction wired up to your application, and printing live data received from the uppercase alphabet Feed.
Leave your code running.
You have just created a very basic Iotic application. At the moment it only prints data, but that can be re-purposed as anything you like.
You also have ongoing flexibility over the data source itself. Iotic Space allows you to create systems in which interactions can be linked and released on-the fly, either programatically or in your browser.
Let’s change the feed you are following. You can do this while your application is running. It will pick up any changes you make.
As you follow many feeds with this application, your printouts will start to look a bit less orderly. This is because you are following live data – you receive it when the Thing you are following shares.
Interactions can be released as well as linked in the browser.
You can unfollow as well as follow Feeds.
You will see the number of feeds you are following in the little circle. Hover over the information bar for each thing, and you will see a small “unfollow” icon appear. Click that to unfollow that feed.
Look back at your terminal, and you will see that feed removed from your subscription list.
Now you have a complete Iotic Thing – with both representation in Iotic Space, and application in code.
You have created a very handy application for having a quick look at data from any available Feed. You can add other functionality to turn this Thing into anything you like.
Try following this Met Office Feed to turn your Thing into a sunshine monitor, or this Environment Agency Feed to turn your Thing into a flood warning device!
By continuing to use the site, you agree to the use of cookies. more information
This website uses cookies via Google Analytics to give you the best browsing experience possible. No personally-identifiable information is collected about you unless you explicitly submit that information on this website. Click "Accept" to continue.