coordinateSetReady = True # create tuple containing coordinate data and insert record into database if coordinateSetReady: timestamp = datetime.datetime.now().replace(microsecond=0).isoformat() try: new_record = (None, timestamp, coordinateX, coordinateY, coordinateZ) record_count += 1 print('- inserting record ' + str(record_count) + '\r', end='') db_conn = sqlite3.connect(globalvar.mqttdb) db_cursor = db_conn.cursor() db_cursor.execute('INSERT INTO acceleration VALUES (?,?,?,?,?)', new_record) db_conn.commit() db_conn.close() except: print('- error with creating record') reset_coordinate_set() if __name__ == '__main__': global record_count record_count = 0 mqtt_broker = globalvar.mqtt_broker mqtt_topic = globalvar.mqtt_topic reset_coordinate_set() print('Listening topic "' + mqtt_topic + '" on ' + mqtt_broker + '...') subscribe.callback(on_message_print, mqtt_topic, hostname=mqtt_broker)
def overall_func(origin,robot,target): logger('@cps running algorithm') current_id = 0 # snippet for robot in origin itself global ax # generate nodes x = [[j, i] for j in range(start, stop, spacing) for i in range(start, stop, spacing)] print x # generate Ids marker_ref = {} for ids, i in enumerate(x, 1): marker_ref[ids] = i scatterplot(x, color='r') scatterplot(robot, color='b') scatterplot(target, color='g') scatterplot(origin, color='b') #plt.show() # reaching row reference # calculaing the number of nodes that should be crossed x_nodes = (target[0][0] - start) / spacing y_nodes = (target[0][1] - start) / spacing print x_nodes, y_nodes x_n = x_nodes y_n = y_nodes # get route nodes route = [] bot_node = x[0][:] route.append(bot_node[:]) while x_n > 0: bot_node[0] = bot_node[0] + spacing route.append(bot_node[:]) x_n = x_n - 1 while y_n > 0: bot_node[1] = bot_node[1] + spacing route.append(bot_node[:]) y_n = y_n - 1 print "this is the route", route # trackback ids id_route = [] for r in route: [id_route.append(key) for key, val in marker_ref.iteritems() if val == r] print id_route x_id = id_route[:x_nodes+1] y_id = id_route[-(y_nodes+1):] print x_id, y_id logger('@cps calculated the route and Ids') if origin==robot: for kx in x_id: while 1: ax = 0 # marker check sen = encoder(kx, 'f') print "giving marker to rpi", sen mqttc.publish("rpi", sen, 2) logger('@cps giving values to rpi') subscribe.callback(on_message, "cps", hostname=host) print "found marker by rpi" logger('@cps found marker by rpi') current_id = kx flag = ax # flag=raw_input() if flag == str(kx): logger('@cps {} nodes to reach'.format(x_nodes)) print "{} more nodes to cross".format(x_nodes) robot[0][0] = robot[0][0] + spacing direction(robot, 'right') scatterplot(robot, 'b') x_nodes = x_nodes - 1 break logger('@cps horizontal movement complete') print "x-ref reached.........." time.sleep(3) # reorienting itself sen = encoder(current_id, 'l') mqttc.publish("rpi", sen, 2) print "giving marker to rpi", sen subscribe.callback(on_message, "cps", hostname=host) print "found marker by rpi" # robot[0][1] = robot[0][1] + 15 direction(robot, 'fwd') scatterplot(robot, 'b') # direction(robot, 'fwd') for ky in y_id: while 1: # marker check sen = encoder(ky, 'f') print "giving marker to rpi", sen mqttc.publish("rpi", sen, 2) logger('@cps giving values to rpi') subscribe.callback(on_message, "cps", hostname=host) print "found marker by rpi" logger('@cps found marker by rpi') flag = ax current_id = ky # flag=raw_input() if flag == str(ky): logger('@cps {} nodes to reach'.format(x_nodes)) print "{} more nodes to cross".format(y_nodes) robot[0][1] = robot[0][1] + spacing direction(robot, 'fwd') scatterplot(robot, 'b') y_nodes = y_nodes - 1 break logger('@cps vertical movement complete') print "y-ref reached..........." logger('@cps Destination reached') print "........................reached destination.........................." else: if robot[0][1] < target[0][1]: x_ref = "up" else: x_ref = 'down' print x_ref rout = [] id_rout = [] pass
def Listen(topic): subscribe.callback(on_message, topic, qos=0, userdata=None, hostname="localhost", port=1883, client_id="digi_mqtt_test", keepalive=60, will=None, auth=None, tls=None)
import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.bind((socket.gethostname(),9003)) s.listen() #assigning the dynamic parameters HOST = sys.argv[1] PORT = 1883 def print_received_message_mqtt(msg): print("Message received. Payload: {}".format(str(msg.payload))) # for subscribing the data request and symmentric key (KIE) def on_message_print(client, userdata, msg): if msg.topic == "sensor_data_req": # print_received_message_mqtt(msg) mess=msg.payload.decode("utf-8") clientsocket,address = s.accept() clientsocket.send(bytes(mess,"utf-8")) # pb.single(TOPIC, key, 0, False, CONTAINER_MQTT_HOST, PORT) elif msg.topic == "sensor_sym_key": # print_received_message_mqtt(msg) mess=msg.payload.decode("utf-8") clientsocket,address = s.accept() clientsocket.send(bytes(mess,"utf-8")) logging.info("Subscription started.") #calling subscription process sub.callback(on_message_print, ["sensor_data_req","sensor_sym_key"], hostname=HOST, port=PORT)
return else: # create a lock until the user tries to kill all instances of VLC x = input(YELLOW+"Please make sure no instances of VLC are running. Press any key to continue"+NC) # sanity check killAllVLC() helper.getChatKey() killAllVLC() startHostServer() time.sleep(1) connectToHost() if(helper.serverChoice == 1): try: subscribe.callback(on_message_print, helper.mqttTopic, hostname=helper.mqttBrokerIP, port=int(helper.mqttPort)) except KeyboardInterrupt: tnh.read_all() # might be helpful later tnh.close() killAllVLC() print("\nExiting") sys.exit() except: print("Network Error!") sys.exit() else: authen = {'username':helper.mqttUsername, 'password':helper.mqttPassword} try: subscribe.callback(on_message_print, helper.mqttTopic, hostname=helper.mqttBrokerIP, auth=authen, port=int(helper.mqttPort)) except KeyboardInterrupt: tnh.read_all() # might be helpful later
def run(self): subscribe.callback(self.onMessage, "door/+/status", hostname=self.host)
#from pypozyx import PozyxSerial #port = '/dev/tty/ACM0' #p = PozyxSerial(port) import paho.mqtt.subscribe as subscribe def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) subscribe.callback(on_message_print, "tags", hostname="localhost")
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 Roger Light <*****@*****.**> # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Distribution License v1.0 # which accompanies this distribution. # # The Eclipse Distribution License is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # Contributors: # Roger Light - initial implementation # This shows an example of using the subscribe.callback helper function. import context # Ensures paho is in PYTHONPATH import paho.mqtt.subscribe as subscribe def print_msg(client, userdata, message): print("%s : %s" % (message.topic, message.payload)) subscribe.callback(print_msg, "#", hostname="mqtt.eclipseprojects.io")
import paho.mqtt.subscribe as subscribe topic_key = dict() def print_msg(client, userdata, message): print(message.topic, str(message.payload.decode("utf-8"))) if message.topic is "GCKS/participant1001": topic_key.append(str(message.payload.decode("utf-8"))) print(topic_key) # loops forever subscribe.callback(print_msg, "GCKS/participant1001", hostname="iot.eclipse.org")
time.sleep(0.1) print("rPi Fan MQTT Control v1.0\n") print("MQTT broker: " + MQTT_HOST) print("MQTT topic prefix: " + cfg['mqtt']['topic_prefix'] + "\n") GPIO.setmode(GPIO.BOARD) GPIO.setup(PIN1, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PIN2, GPIO.OUT, initial=GPIO.HIGH) GPIO.setup(PIN3, GPIO.OUT, initial=GPIO.HIGH) mqttpub.single(MQTT_ON_TOPIC, "true", hostname=MQTT_HOST) mqttpub.single(MQTT_SPEED_TOPIC, "low", hostname=MQTT_HOST) try: mqttsub.callback(change_fan, MQTT_TOPIC_FILTER, hostname=MQTT_HOST) except KeyboardInterrupt: print("\nQuitting...") except: print("\nOther error or exception occurred!") finally: mqttpub.single(MQTT_ON_TOPIC, "true", hostname=MQTT_HOST) mqttpub.single(MQTT_SPEED_TOPIC, "low", hostname=MQTT_HOST) GPIO.cleanup()
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 Roger Light <*****@*****.**> # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Distribution License v1.0 # which accompanies this distribution. # # The Eclipse Distribution License is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # Contributors: # Roger Light - initial implementation # This shows an example of using the subscribe.callback helper function. import context # Ensures paho is in PYTHONPATH import paho.mqtt.subscribe as subscribe def print_msg(client, userdata, message): print("%s : %s" % (message.topic, message.payload)) subscribe.callback(print_msg, "#", hostname="iot.eclipse.org")
json_body = [{ 'measurement': 'P1P2', 'tags': { 'topic': topic }, 'fields': { 'value': value } }] try: result = influxdb_client.write_points(json_body) log.debug(" Sent.") except Exception as e: print(e) influxdb_client = InfluxDBClient(host=INFLUXDB_HOST, port=8086, timeout=10, username=None, password=None, database=INFLUXDB_DBNAME) log.info("Connected to InfluxDB.") subscribe.callback(callback=on_message, topics=TOPICS, hostname=MQTT_HOST, client_id=CLIENT_ID, clean_session=True) influxdb_client.close() log.info("Quit.")
# MQTT Client for LinkedIn Learning Raspberry Pi Weekly import paho.mqtt.subscribe as subscribe import numpy as np import cv2 import matplotlib.pyplot as plt from io import BytesIO broker_location = "192.168.4.1" def on_mqtt_message(client, userdata, message): # print(message.topic + " " +str(message.payload)) f = BytesIO(message.payload) loaded_np = np.load(f, allow_pickle=True) cv2.imshow("image", loaded_np) subscribe.callback(on_mqtt_message, "FirstTry/Test", hostname = broker_location)
def main(): topic = 'odsi/raspberry/marina_barbu' while True: subscribe.callback(on_message_print,topic, hostname=MQTT_server, port=MQTT_port)
# Set varibles httphost = "localhost" httpuser = "******" httppass = "******" rt_container = 3 rt_contentInstance = 4 def create_container(container_name): attr = '"rn":%s' %(container_name) container_resp = connect.create("InCSE1", rt_container, attr) # print container_resp.text def create_cin(path, payload): payload1 = json.dumps(payload) attr = '"con":%s' %(payload1) conIn_resp = connect.create(path, rt_contentInstance, attr) # print conIn_resp.text def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) payload = json.loads(message.payload) # print(payload['deviceName']) create_container(payload['deviceName']) path = "InCSE1/" + payload['deviceName'] create_cin(path, message.payload) connect = criotdm.connect_to_iotdm(httphost, httpuser, httppass, "http") subscribe.callback(on_message_print, "/tdf/test", hostname="168.128.108.105")
"light": data["value"], "time": t.strftime('%Y-%m-%d %H:%M:%S') }) db.commit() finally: db.close() print("Done") # get real data # if data[0]["values"][0] > light_threshold: # device_control() # try: # db.execute("INSERT INTO light (device_id, light_intensity, time) VALUES (:device_id, :light, :time)",{"device_id": 2, "light": data[0]["values"][0],"time": t.strftime('%Y-%m-%d %H:%M:%S')}) # db.commit() # finally: # db.close() # print(f"""Intensity: {data[0]["values"][0]}""") def device_control(): p_data = {} p_data["device_id"] = "Light_D" p_data["value"] = ["1", "50"] data = json.dumps(p_data) publish.single("Topic/LightD", data, hostname="52.230.126.225") # publish.single("Topic/LightD", data, hostname="13.76.250.158", auth={'username': "******", 'password': "******"}) sub.callback(print_msg, "Temp/Air/Light", hostname="52.230.126.225") # sub.callback(print_msg, "Topic/Light", hostname="13.76.250.158", auth={'username':"******", 'password':"******"})
lines = fp.readlines() topic = str(lines[1]).rstrip() ip_broker = str(lines[3]).rstrip() port_broker = str(lines[5]).rstrip() ip_cloud = str(lines[7]).rstrip() port_cloud = str(lines[9]).rstrip() print topic print ip_broker print "Subscribing to broker..." subscribe.callback(on_message, topic, hostname=ip_broker) # client = mqttClient.Client("Python") #create new instance # client.on_connect= on_connect #attach function to callback # client.on_message= on_message #attach function to callback # # client.connect(str(ip_broker), port=int(port_broker)) #connect to broker # # client.loop_start() #start the loop # time.sleep(0.1) #wait for connection # # client.subscribe(topic) # # try: # while True: # time.sleep(1)
# put the new data in to the buffer as strings _buffer.append(str(tgain)) _buffer.append(str(hrs_pumped)) if debug: print("_buffer now contains:") print(_buffer) # so we now have some data so store it in a file # for the HEC-code to pick up # ensure we can write a file try: f = open(_datafile, "w+") # open the file for non binary write f.write(','.join(_buffer)) # write the buffer as a CSV string f.close() # close the file except: print("Error writing to %s " % _datafile) f.close() # ensure file handle is closed # ---------------------- main ----------------------------------------- # Setup connection to MQTT queue and wait for a message. # when a message arrives call funcion got_msg # # line below will sit and wait for a message and then run got_msg() subscribe.callback(got_msg, _mqtt_topic, hostname=_mqtt_host) sys.exit(0)
sm = int(mqttmessage[35:38]) at = float(mqttmessage[39:46]) ah = float(mqttmessage[47:54]) print(mqttmessage) print(dt) print(st) print(sm) print(at) print(ah) sqliteConnection = sqlite3.connect(DB_Name) cursorObject = sqliteConnection.cursor() sqliteConnection.execute('pragma journal_mode=wal;') cursorObject.execute( "INSERT INTO DATASEN (date_time,soil_temp,soil_moist,atmp_temp,atmp_hum) VALUES(?,?,?,?,?)", [dt, st, sm, at, ah]) cursorObject.execute("COMMIT") cursorObject.close() print("Inserted Data into DATASEN Database.") topics = ["agristick1", "agristick2"] subscribe.callback(on_message, topics, hostname="13.232.96.33", auth={ 'username': "******", 'password': "******" }) #10.134.67.132
# which accompanies this distribution. # # The Eclipse Distribution License is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # Contributors: # Roger Light - initial implementation # This shows an example of using the subscribe.callback helper function. import sys try: import paho.mqtt.subscribe as subscribe except ImportError: # This part is only required to run the example from within the examples # directory when the module itself is not installed. # # If you have the module installed, just use "import paho.mqtt.subscribe" import os import inspect cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"../src"))) if cmd_subfolder not in sys.path: sys.path.insert(0, cmd_subfolder) import paho.mqtt.subscribe as subscribe import paho.mqtt.client def print_msg(client, userdata, message): print("%s : %s" % (message.topic, message.payload)) subscribe.callback(print_msg, "#", hostname="iot.eclipse.org")
import paho.mqtt.subscribe as subscribe def on_message_print(client, userdata, message): a= (message.payload) print a with open("loge.txt", "a") as log_file: log_file.write('{}\n'.format(a)) client.disconnect() with open('loge.txt','w'): pass while 1: subscribe.callback(on_message_print, "log", hostname='52.90.36.67')
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2016 Roger Light <*****@*****.**> # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Distribution License v1.0 # which accompanies this distribution. # # The Eclipse Distribution License is available at # http://www.eclipse.org/org/documents/edl-v10.php. # # Contributors: # Roger Light - initial implementation # This shows an example of using the subscribe.callback helper function. import context # Ensures paho is in PYTHONPATH import paho.mqtt.subscribe as subscribe import paho.mqtt.client as mqtt while True: def print_msg(client, userdata, message): print("%s : %s" % (message.topic, message.payload)) mqttc = mqtt.Client() mqttc.username_pw_set("eprchuzr","UEydS74yuz2b") subscribe.callback(print_msg, "truck3", hostname="m14.cloudmqtt.com")
import json import time arduinoSerialData = serial.Serial('com5',9600) #Create Serial port object called arduinoSerialData while True: if (arduinoSerialData.inWaiting()>0): ts = time.time() myData = arduinoSerialData.readline() myData = myData.decode("utf-8") myData = myData.rstrip() temp = myData[0:3] temp = float(temp) hum = myData[4:8] direction = myData[8] if direction == "0": direction = "SE" elif direction == "1": direction = "SW" myData = json.dumps( {'latitude':35.6133125,'longitude': -83.4990472,'airHumidity': hum, 'airTemperature': temp, 'windDirection': direction, 'timestamp': ts} ) print (myData) #publish.single("weatherbot-accmty2018", myData, hostname="test.mosquitto.org") '''def print_msg(client, userdata, message): print("%s : %s" % (message.topic, message.payload)) subscribe.callback(print_msg, "topic1", hostname="test.mosquitto.org") '''
from paho.mqtt.client import MQTTv311, MQTTv31 from paho.mqtt.subscribe import callback PORT = 5000 PROTOCOL = MQTTv311 # Callback function to print out message topics and payloads def listen(client, userdata, message): print message.topic, message.payload # Subscribe to all messages and loop forever callback(listen, '#', port=PORT, protocol=PROTOCOL)
logger('@cps Destination reached') print "........................reached destination.........................." else: if robot[0][1] < target[0][1]: x_ref = "up" else: x_ref = 'down' print x_ref rout = [] id_rout = [] pass if __name__== "__main__": logger('@cps CPS ONLINE') while 1: subscribe.callback(on_message, "gui", hostname=host) logger('@cps got item from gui') #ax='snacks' print ax crossrefval=csvfunc(ax) crossrefval=list(crossrefval[0]) target=[ast.literal_eval(crossrefval[0])] print target overall_func(origin,robot,target) mqttc.loop_stop() mqttc.disconnect() plt.show()
devices = db.execute( "SELECT device_id FROM device WHERE type = 'light' AND room_id=" + data["room"]) for device in devices: device_control(device["device_id"]) # device_control(data["room"]) print(f"""Light: {data["value"]}""") try: # db.execute("INSERT INTO light (device_id, light_intensity, time) VALUES (:device_id, :light, :time)", # {"device_id": 2, "light": data["value"], "time": t.strftime('%Y-%m-%d %H:%M:%S')}) db.execute( "UPDATE device SET status=0 WHERE type='light' AND room_id=" + data["room"]) db.commit() finally: db.close() print("Done") def device_control(device_id): p_data = {} p_data["device_id"] = device_id p_data["value"] = 0 data = json.dumps(p_data) publish.single("Topic/Light", data, hostname="broker.hivemq.com") # publish.single("Topic/LightD", data, hostname="13.76.250.158", auth={'username': "******", 'password': "******"}) sub.callback(print_msg, "LightSensor", hostname="broker.hivemq.com") # sub.callback(print_msg, "Topic/Light", hostname="13.76.250.158", auth={'username':"******", 'password':"******"})
#!/usr/bin/python # Simple utility to subscribe to mqtt import sys import paho.mqtt.subscribe as subscribe if len(sys.argv) < 3: print("mqtt-subscribe host[:port] topic") exit(1) hostport = sys.argv[1].split(':') host = hostport[0] port = hostport[1] if len(hostport) > 1 else 1883 topic = sys.argv[2] def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) try: subscribe.callback(on_message_print, topic, hostname=host, port=port) except KeyboardInterrupt: pass
def on_message_light(client, userdata, message): global last_light_message_nonce key = "Sixteen byte key" hash = message.payload[:64] nonce = message.payload[64:80] ciphertext = message.payload[80:] message_authenticity = is_message_authentic(key, hash, nonce, ciphertext, last_light_message_nonce) if message_authenticity == 1: print "Message Not Authenticated - Key False" elif message_authenticity == 2: print "Message Not Authenticated - Nonce Expired" elif message_authenticity == 0: print "Message Authenticated" last_light_message_nonce = nonce cipher = AES.new(key, AES.MODE_CFB, nonce) plaintext = cipher.decrypt(ciphertext) if plaintext == '0': print 'Light Off' elif plaintext == '1': print 'Light On' else: print 'Value Not Valid' print if __name__ == "__main__": hostname = "localhost" subscribe.callback(on_message_light, "things/1/light", hostname=hostname)
from datetime import datetime import json import paho.mqtt.subscribe as subscribe import redis import sys import time sensor_key = 'temperature' if len(sys.argv) == 3 else sys.argv[3] print('Starting topic %s key %s, parameter: %s' % (sys.argv[1], sys.argv[2], sensor_key)) redis = redis.StrictRedis(host='localhost', port=6379, db=0) def on_msg(client, userdata, message): print('message received %s, searching for %s' % (str(message.payload.decode('utf-8')), sensor_key)) data = json.loads(message.payload.decode('utf-8')) data['value'] = data[sensor_key] data['when'] = str(datetime.now()) redis.lpush(sys.argv[2], json.dumps(data)) redis.ltrim(sys.argv[2], 0, 50) subscribe.callback(on_msg, sys.argv[1], hostname='localhost') # $1 - topic name # $2 - redis key name #echo '$0 fetching from MQTT topic $1 and saving to Redis list $2' #mosquitto_sub -t $1 -F %I,%p | parallel redis-cli lpush $2
import os import paho.mqtt.subscribe as subscribe def on_message(client, userdata, msg): print(msg.topic, msg.payload) subscribe.callback(on_message, "channels/758180/subscribe/fields/field1", hostname="mqtt.thingspeak.com", auth={ 'username': "******", 'password': os.environ['TS_MQTT_API_KEY'] })
def decoder(ctx): lis = ctx.split('|') return lis[0], lis[-1] def logger(val): mqttc.publish("log", val, 2) pass def arucoid(ide, dire): global an #print ide, dire if __name__ == "__main__": while 1: subscribe.callback(on_message_print, "rpi3", hostname=host) print "received marker from cps", an ids, dire = decoder(an) #ogger('@rasp received marker {} from cps'.format(ids)) arucoid(ids, dire) time.sleep(3) #logger('@rasp found one marker moving to next marker') mqttc.publish("cps3", ids, 2) print "sending to cps" mqttc.loop_stop() mqttc.disconnect()
import paho.mqtt.subscribe as subscribe import currency as cur def print_msg(client, userdata, message): pesan = message.payload if pesan.upper() == "USD": x = "USD sekarang adalah Rp " + str(cur.IDR()) elif pesan.upper() == "SGD": x = "SGD sekarang adalah Rp " + str(cur.SGDIDR()) elif pesan.upper() == "EUR": x = "EUR sekarang adalah Rp " + str(cur.EURIDR()) print message.topic + ": " + str(x) subscribe.callback(print_msg, "kolla/kresna", hostname="test.mosquitto.org")
connect.create(path, rt_contentInstance, attr) print criotdm.text(connect.response) if criotdm.status_code(connect.response) > 299: create_container(parentpath, payloadjson['deviceName']) connect.create(path, rt_contentInstance, attr) def on_message_print(client, userdata, message): print("%s %s" % (message.topic, message.payload)) create_cin(inputPath, message.payload) def getCSEName(path): return path.split('/')[0] def createContainerPath(path): pathArray = path.split('/') print pathArray parent = CSEName for resource in pathArray: create_container(parent, resource) parent = parent + "/" + resource inputHost = raw_input("Please enter the hostname of the MQTT broker (like 168.128.108.105):") inputPort = raw_input("Please enter the port number (like 1883):") inputTopic = raw_input("Please enter the topic you want to subscribe (like /tdf/test):") inputPath = raw_input("Please enter the path of IOTDM to store the data(like InCSE1/MQTTMessage):") CSEName = getCSEName(inputPath) connect = ciotdm.connect(httphost, base=CSEName, auth=(httpuser, httppass), protocol="http") createContainerPath(inputPath.lstrip(CSEName+"/")) subscribe.callback(on_message_print, topics = inputTopic, hostname = inputHost, port = inputPort) # subscribe.callback(on_message_print, topics = "/tdf/test", hostname = "168.128.108.105", port = 1883)