def __init__(self, domain, organization, clientId, username, password, logHandlers=None, cleanSession="true"): self.organization = organization self.username = username self.password = password self.address = organization + ".messaging." + domain self.port = 1883 self.keepAlive = 60 self.connectEvent = threading.Event() self._recvLock = threading.Lock() self._messagesLock = threading.Lock() self.messages = 0 self.recv = 0 self.clientId = clientId # Configure logging self.logger = logging.getLogger(self.__module__ + "." + self.__class__.__name__) self.logger.setLevel(logging.INFO) # Remove any existing log handlers we may have picked up from getLogger() self.logger.handlers = [] if logHandlers: if isinstance(logHandlers, list): # Add all supplied log handlers for handler in logHandlers: self.logger.addHandler(handler) else: # Add the supplied log handler self.logger.addHandler(logHandlers) else: # Generate a default rotating file log handler and stream handler logFileName = '%s.log' % (clientId.replace(":", "_")) fhFormatter = logging.Formatter('%(asctime)-25s %(name)-25s ' + ' %(levelname)-7s %(message)s') rfh = RotatingFileHandler(logFileName, mode='a', maxBytes=1024000, backupCount=0, encoding=None, delay=True) rfh.setFormatter(fhFormatter) ch = logging.StreamHandler() ch.setFormatter(fhFormatter) ch.setLevel(logging.DEBUG) self.logger.addHandler(rfh) self.logger.addHandler(ch) self.client = paho.Client( self.clientId, clean_session=False if cleanSession == "false" else True) try: self.tlsVersion = ssl.PROTOCOL_TLSv1_2 except: self.tlsVersion = None # Configure authentication if self.username is not None: # In environments where either ssl is not available, or TLSv1.2 is not available we will fallback to MQTT over TCP if self.tlsVersion is not None: self.port = 8883 # Path to certificate caFile = os.path.dirname( os.path.abspath(__file__)) + "/messaging.pem" self.client.tls_set(ca_certs=caFile, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2) # Pre Python 3.2 the Paho MQTT client will use a bespoke hostname check which does not support wildcard certificates # Fix is included in 1.1 - https://bugs.eclipse.org/bugs/show_bug.cgi?id=440547 if float(get_distribution('paho-mqtt').version) < 1.1 and ( sys.version_info[0] < 3 or (sys.version_info[0] == 3 and sys.version_info[1] < 2)): self.logger.warning( "Disabling TLS certificate hostname checking - Versions of the Paho MQTT client pre 1.1 do not support TLS wildcarded certificates on Python 3.2 or earlier: https://bugs.eclipse.org/bugs/show_bug.cgi?id=440547" ) self.client.tls_insecure_set(True) else: self.logger.warning( "Unable to encrypt messages because TLSv1.2 is unavailable (MQTT over SSL requires at least Python v2.7.9 or 3.4 and openssl v1.0.1)" ) self.client.username_pw_set(self.username, self.password) # Attach MQTT callbacks self.client.on_log = self.on_log self.client.on_connect = self.on_connect self.client.on_disconnect = self.on_disconnect self.client.on_publish = self.on_publish # Initialize default message encoders and decoders. self._messageEncoderModules = {} self.start = time.time() # initialize callbacks self._onPublishCallbacks = {}
# Extract the data from each sensor, even if the MQTT message contain multiple entries for entry in obj["readings"]: print("Sensor: %s: Reading: %s" % (entry["name"], entry["value"])) device = entry["device"] sensorName = entry["name"] sensorValue = entry["value"] # Write data to influxDB influxDBwrite(device, sensorName, sensorValue) influxDBConnection = influxDBconnect() print("Creating new instance ...") client = mqtt.Client("sub1") #create new instance client.on_message = on_message #attach function to callback client.username_pw_set(p4mqttUser, p4mqttPass) print("Connecting to broker ...") client.connect(broker_address, 12967) #connect to broker print("...done") client.loop_start() while True: client.subscribe(topic) time.sleep(1) client.loop_stop()
csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: key_values = row key_value_count = len(key_values) line_count += 1 else: temp_val = {} data_val = row count = 0 for value in key_values: temp_val[value] = data_val[count] count += 1 data_value[line_count] = temp_val line_count += 1 # Connecting to MQTT for publishing. client = mqtt.Client() client.on_connect = on_connect # On Connect Callback. client.on_publish = on_publish # On Publish Callback. client.connect(MQTT_BROKER, 1883, 60) # Connecting to the MQTT Broker. while 1: for value in data_value: temp_data_val = str(data_value[value]).replace("'", '"') try: client.publish(MQTT_TOPIC, temp_data_val) time.sleep(1) except: print("Publish Failed.")
def setup(self, timeout=20): """ This method sets up the actual MQTT client, assigns all callback functions for event handling and sets a last will and testament (LWT) message. It then attempts to connect to the broker. The connection call is blocking; it continues until a connection acknowlegement message is received from the broker or until the timeout is reached. After connection has been acheived, it subscribes to the topics: oxpe2elib/[name]/public oxpe2elib/[name]/protected oxpe2elib/[name]/private oxpe2elib/[name]/public/pinreq oxpe2elib/[name]/public/pingack If another device wants to contact this smart agent, it must publish to one of these topics. Finally, this method starts the MQTT loop running on a separate thread. This loop thread handles publishing and receiving messages, and also routinely pings the broker to check the connection status. If the connection is lost, the thread automatically buffers messages and attempts to reconnect """ global connack global incoming_message_buffer # Setting clean_session = False means that subsciption information and # queued messages are retained after the client disconnects. It is suitable # in an environment where disconnects are frequent. mqtt_client = mqtt.Client(protocol=self.protocol, client_id=self.name, clean_session=False) mqtt_client.on_connect = Agent.on_connect mqtt_client.on_message = Agent.on_message mqtt_client.on_publish = Agent.on_publish mqtt_client.on_disconnect = Agent.on_disconnect # Connect to the broker # keepalive is maximum number of seconds allowed between communications # with the broker. If no other messages are sent, the client will send a # ping request at this interval logging.info('Attempting to connect to broker at ' + self.hostname) mqtt_client.connect(self.hostname, self.port, keepalive=60) # Force function to block until connack is sent from the broker, or timeout connack = False start_time = time.time() while not connack: time.sleep(0.1) mqtt_client.loop() if time.time() - start_time > timeout: raise MqttTimeOutError("The program timed out while trying to connect to the broker!") break # When connected, subscribe to the relevant channels mqtt_client.subscribe(self.STATUS, 1) self.client = mqtt_client # Set a message buffer incoming_message_buffer = [] # Start the loop. This method is preferable to repeatedly calling loop # since it handles reconnections automatically. It is non-blocking and # handles interactions with the broker in the background. logging.info('Starting loop') self.client.loop_start()
lastwill = mqttConfig["MQTT"]["lastwill"] lwt = mqttConfig["MQTT"]["lwt"] clientid = mqttConfig["MQTT"]["clientid"] receiver = mqttConfig["MQTT"]["receivername"] subtopics = mqttConfig["MQTT"]["subtopics"] if len(subtopics) > 0: subtopics = subtopics.split(",") if "nojson" in subtopics: subtopics.remove("nojson") mqttJSONDisabled = True if len(receiver) == 0: import socket receiver = socket.gethostname() client = mqtt.Client(clientid) client.on_connect = MQTTOnConnect client.on_publish = MQTTOnPublish client.on_disconnect = MQTTOnDisconnect client.reconnect_delay_set(min_delay=1, max_delay=60) client.loop_start() client.username_pw_set(username, password) if len(lwt) > 0: print("Using lastwill with topic:", lwt, "and message:", lastwill) client.will_set(lwt, lastwill, qos=1) client.connect_async(broker, port) MQTTClient = client if args.device: if re.match("[0-9a-fA-F]{2}([:]?)[0-9a-fA-F]{2}(\\1[0-9a-fA-F]{2}){4}$",
#print("message topic=",message.topic) #print("message qos=",message.qos) #print("message retain flag=",message.retain) ########################################################### ##### Main ########################### ### Check Radis connection ret = check_db() if ret is None: # for debug print("***** Failed check Radis *****") exit(1) ### Connect MQTT broker print("Connecting to MQTT broker:" + BrokerAddress) client = mqtt.Client() # Create new instance with Any clientID client.on_message=on_message # Attach function to callback try: client.connect(BrokerAddress) #connect to broker except: print("***** Broker connection failed *****") exit(1) ### Subscribe ### print("Subscribe topic:", MqttTopic) client.subscribe(MqttTopic) # Subscribe MQTT ### loop forever to wait a message ### print("Waiting message...") client.loop_forever() # Loop forever
import paho.mqtt.client as mqtt import cv2 import numpy as np buff=[] imgready = False def on_message(client, userdata, message): global buff global imgready print("message received ") imgready = True buff = message.payload broker_address="BROKER IP" #Replace with your broker adress client = mqtt.Client("Test") client.on_message=on_message client.username_pw_set("USER", "PASSWORD") #Replace with your User/Pass client.connect(broker_address) client.subscribe("MQTT TOPIC") #Replace with your Topic while(True): client.loop_start() if(imgready == True): nparr = np.frombuffer(buff, np.uint8) img = cv2.imdecode(nparr,1) cv2.imshow('Demo', img) if cv2.waitKey(1) & 0xFF == ord('q'):
else: print("Out of range.") msg_txt_formatted = MSG_TXT % (distance) message = msg_txt_formatted # Send the message. print("Sending message: %s" % message) client.publish("devices/" + devicename + "/messages/events/", message, qos=1) time.sleep(3) except IoTHubError as iothub_error: print("Unexpected error %s from IoTHub" % iothub_error) return except KeyboardInterrupt: print("IoTHubClient sample stopped") client = mqtt.Client(client_id=devicename, protocol=mqtt.MQTTv311) client.username_pw_set(username=HubName + "/" + devicename, password=None) client.tls_set(certfile=deviceCert, keyfile=deviceCertKey, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) client.connect(HubName, port=8883) iothub_client_telemetry_sample_run() client.loop_forever()
def connect_mqtt(): ### TODO: Connect to the MQTT client ### client = mqtt.Client() client.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL) return client
def im920callback(s): global mes, wdf semaphore.acquire() if wdf == False: mes = s.data semaphore.release() def mqtt_loop(): client.loop_forever() if __name__ == '__main__': client = mqtt.Client(protocol=mqtt.MQTTv311) client.on_connect = on_connect client.on_message = on_message client.connect(host, port=port, keepalive=60) rospy.init_node('agv_recv') pub = rospy.Publisher('/agv', agv_msgs, queue_size=1) pub_velAY = rospy.Publisher('/agv/velAY', Float32, queue_size=1) pub_velBX = rospy.Publisher('/agv/velBX', Float32, queue_size=1) pub_voltM = rospy.Publisher('/agv/voltM', Float32, queue_size=1) sub = rospy.Subscriber('im920', String, im920callback) rate = rospy.Rate(20) Thread(target=mqtt_loop).start() agv = agv_msgs()
root_mac = msg.topic.split("/").pop() print(root_mac) data = msg.payload.decode("utf-8").split("|") print(data) try: c.execute( """ INSERT INTO Originale('MAC','ISPUB','RSSI','TIMESTAMP','ROOT') VALUES ('{}', {}, {}, '{}', '{}')""".format( data[0], data[3], data[1], data[2], root_mac)) except sqlite3.Error as e: print("Database error: %s" % e) conn.commit() def random_char(y): return ''.join(random.choice(string.ascii_letters) for x in range(y)) print("Start MQTT") client_id = "server-" + random_char(5) client = mqtt.Client(client_id) client.username_pw_set(mqtt_user, mqtt_pwd) client.on_connect = on_connect client.on_message = on_message client.connect(mqtt_server, mqtt_port, 60) client.loop_forever() conn.close()
def main(): client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect('broker.mqttdashboard.com', 1883, 60) client.loop_forever()
def connect(self): self.client = mqtt.Client() self.client.connect(self.ip)
connflag = False def on_connect(client, userdata, flags, rc): # func for making connection global connflag print ("Connected to AWS") connflag = True print("Connection returned result: " + str(rc) ) def on_message(client, userdata, msg): # Func for Sending msg print(msg.topic+" "+str(msg.payload)) #def on_log(client, userdata, level, buf): # print(msg.topic+" "+str(msg.payload)) mqttc = paho.Client() # mqttc object mqttc.on_connect = on_connect # assign on_connect func mqttc.on_message = on_message # assign on_message func #mqttc.on_log = on_log #### Change following parameters #### awshost = "a1kudj94y1eid7-ats.iot.us-east-1.amazonaws.com" # Endpoint awsport = 8883 # Port no. clientId = "aws_thing1" # Thing_Name thingName = "aws_thing1" # Thing_Name caPath = "./ACI_Project/root-CA.crt" # Root_CA_Certificate_Name certPath = "./ACI_Project/aws_thing1.cert.pem" # <Thing_Name>.cert.pem keyPath = "./ACI_Project/aws_thing1.private.key" # <Thing_Name>.private.key mqttc.tls_set(caPath, certfile=certPath, keyfile=keyPath, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None) # pass parameters
print("---------------") print(string) def on_publish(mosq, obj, mid): print("mid: " + str(mid)) publish_data() def teardown(): mqttClient.disconnect() mqttClient.loop_stop() sys.exit() mqttClient = mqtt.Client(client_id=mqttClientId) mqttClient.on_connect = on_connect mqttClient.on_disconnect = on_disconnect mqttClient.on_publish = on_publish mqttClient.on_log = on_log mqttClient.tls_set(mqttCert_ca, certfile=mqttCert, keyfile=mqttCert_priv, tls_version=mqttCert_Protocol, ciphers=None) print("Start connecting to " + mqttEndpoint + ":" + str(mqttPort) + " ...") try: mqttClient.connect(mqttEndpoint, port=mqttPort)
ser) if (command == "POWER_Z1"): if (msg.payload.upper() == "ON"): sendAVR(CmdMsg["ON_Z1"], ser) time.sleep(1) if (msg.payload.upper() == "OFF"): sendAVR(CmdMsg["OFF_Z1"], ser) else: print("unknown command: %s" % command) time.sleep(0.06) lockser = 0 def on_log(client, userdata, level, buf): print("log: ", buf) client = paho.Client("AVR") client.on_connect = on_connect client.on_message = on_message client.username_pw_set("AVR", "<password>") client.connect("127.0.0.1", 1883, 60) lockser = 0 run = True while run: client.loop() if lockser == 0: readAVR(ser)
import json import time from datetime import datetime ACCESS_TOKEN = "llXBwVFfveFQaVUJbhbv" #Token of your device broker = "demo.thingsboard.io" #host name port = 1883 #data listening port level = 1 def on_publish(client, userdata, result): #create function for callback print("data published to thingsboard \n") pass client1 = paho.Client("control1") #create client object client1.on_publish = on_publish #assign function to callback client1.username_pw_set(ACCESS_TOKEN) #access token from thingsboard device client1.connect(broker, port, keepalive=60) #establish connection while True: level = level - 0.001 payload = "{" payload += "\"level\":{}".format(level) payload += "}" ret = client1.publish("v1/devices/me/telemetry", payload) #topic-v1/devices/me/telemetry print("Please check LATEST TELEMETRY field of your device") print(payload) time.sleep(5)
import json import sha2 # Import library paho-mqtt import paho.mqtt.client as mqtt # Inisiasi object mqtte mqttc = mqtt.Client("sub1", clean_session=True) # Buat koneksi ke broker mqttc.connect("192.168.201.100", 1883) def on_connect(mqttc, obj, flags, rc): print("Connected") def on_message(mqttc, obj, msg): #json encoding data_str = json.loads(str(msg.payload.decode("utf-8"))) mac_pub = data_str["mac"] data_sensor = data_str["sensor"] #baca array dalam json data_sensor_ketinggian = data_sensor[0] data_sensor_suhu = data_sensor[1] data_sensor_kekeruhan = data_sensor[2] #string sensor 1 + sensor 2 + sensor 3 group_data_sensor = data_sensor_kekeruhan + data_sensor_suhu + data_sensor_ketinggian mac_sub = sha2.hmac_sha256("key_publisher", group_data_sensor)
def main(): args = parse_command_line_args() subscriber = pubsub.SubscriberClient() subscription_path = subscriber.subscription_path( args.project_id, args.pubsub_subscription) publisher = pubsub_v1.PublisherClient() global count count = 0 # Create the MQTT client and connect to Cloud IoT. client = mqtt.Client( client_id='projects/{}/locations/{}/registries/{}/devices/{}'.format( args.project_id, args.cloud_region, args.registry_id, args.device_id)) client.username_pw_set( username='******', password=create_jwt( args.project_id, args.private_key_file, args.algorithm)) client.tls_set(ca_certs=args.ca_certs, tls_version=ssl.PROTOCOL_TLSv1_2) device = Device(args.device_id, args.service_account_json) os.system("rm -rf receieved_images" + device.get_id()) os.system("mkdir receieved_images" + device.get_id()) client.on_connect = device.on_connect client.on_publish = device.on_publish client.on_disconnect = device.on_disconnect client.on_subscribe = device.on_subscribe client.on_message = device.on_message client.connect(args.mqtt_bridge_hostname, args.mqtt_bridge_port) client.loop_start() mqtt_service_topic = 'projects/project2-277316/topics/my-topic' #central mqtt_config_topic = '/devices/{}/config'.format(args.device_id) # Wait up to 5 seconds for the device to connect. device.wait_for_connection(5) def callback(message): """Logic executed when a message is received from subscribed topic. """ ''' try: data = json.loads(message.data.decode('utf-8')) except ValueError as e: print('Loading Payload ({}) threw an Exception: {}.'.format( message.data, e)) message.ack() return ''' global count try: try: data = json.loads(message.data.decode('utf-8')) except ValueError as e: print('Loading Payload ({}) threw an Exception: {}.'.format( message.data, e)) message.ack() return if data['type'] == 'REK': dev_id = data['dev_id'] img = data['img_name'] print("Recieved initial request from device " + dev_id + "for image " + img + "\n\n\n") message.ack() mqtt_config_topic = '/devices/{}/config/'.format(dev_id) payload_json = {'type' : 'REKSYM', 'img_name':img, 'node_id': device.get_id()} payload = json.dumps(payload_json) device_project_id = args.project_id device_registry_id = args.registry_id device_id = dev_id device_region = args.cloud_region print("Sending acknowledgement to device " + dev_id + "for image " + img + "\n\n\n") # Send the config to the device. device._update_device_config( device_project_id, device_region, device_registry_id, device_id, payload) # print("10.....................") time.sleep(1) elif data['type'] == 'REKACK': if(data['node_id'] == device.get_id()): image_data = base64.b64decode(data['img_data']) print("Recieved acknowledgement from device " + data['dev_id'] + "for image " + data['img_name'] + "\n\n\n") message.ack() count = count + 1 # dateTimeObj = datetime.now() # dateStr = dateTimeObj.strftime("%b%d%Y%H:%M:%S.%f") with io.open("receieved_images" + device.get_id() + "/receieved_image" + str(count) + ".jpeg", 'wb') as f: f.write(image_data) bucket_name = 'project2-buck' image_name = device.get_id() + 'image' + str(count) + '.jpg' is_uploaded = upload_to_aws("receieved_images" + device.get_id() + "/receieved_image" + str(count) + ".jpeg",bucket_name, image_name) num_labels = 0 labels = list() if is_uploaded == True: #Call rekognition labels = detect_labels(image_name,bucket_name) payload_json = {'type': 'REKRES', 'img_name':data['img_name'], 'is_success':is_uploaded, 'labels': labels, 'node_id': device.get_id()} payload = json.dumps(payload_json) device_project_id = args.project_id device_registry_id = args.registry_id device_id = data['dev_id'] device_region = args.cloud_region print("Publishing rekognition results to device " + data['dev_id'] + " for image " + data['img_name']) print("The labels in image are : ") for l in labels: print(l) print("\n\n\n\n") # Send the config to the device. device._update_device_config( device_project_id, device_region, device_registry_id, device_id, payload) time.sleep(1) # Signal to the main thread that we can exit. #job_done.set() else: message.ack() except binascii.Error: message.ack() # To move forward if a message can't be processed print('Listening for messages on {}'.format(subscription_path)) subscriber.subscribe(subscription_path, callback=callback) time.sleep(3000) client.disconnect() client.loop_stop() print('Finished loop successfully. Goodbye!')
camera = PiCamera() camera.resolution = (256, 256) def take_picture(): global camera camera.capture('temp.jpg') # message handling callback def on_message(client, userdata, message): print "Callback!" if message.payload == "displayReady": print "ready received. Storing picture" take_picture() print "sending imageDone" client.publish("camera", "imageDone") broker_address = "makerlabPi1" client = mqtt.Client("camera") client.on_message = on_message client.connect(broker_address) client.loop_start() client.subscribe("camera") print "camera running." while True: time.sleep(1) client.loop_stop()
""" if rc == 0: client.connected_flag = True print("mqtt connection ok") else: print("there was an error while connecting: ", rc) import yaml with open('secrets.yaml') as secretsfile: secrets = yaml.load(secretsfile, Loader = yaml.FullLoader) mqtt.Client.connected_flag = False broker_address = secrets['mqtt']['host'] mc = mqtt.Client(client_id = "homeserver") mc.username_pw_set(secrets['mqtt']['username'], secrets['mqtt']['password']) mc.on_connect = on_connect mc.loop_start() print("connecting to broker at (%s) with username (%s)" % (secrets['mqtt']['host'], secrets['mqtt']['username'])) mc.connect(broker_address) while not mc.connected_flag: print("waiting...") time.sleep(1) print("starting mainloop") mc.loop_stop()
try: print("Connecting... ", serialdev) # #connect to serial port # //ser = serial.Serial(serialdev, 9600, timeout=20)///dev/tty.usbserial-143320 ser = serial.Serial(serialdev, 115200, 8, 'N', 1, timeout=120) except: print("Failed to connect serial") #unable to continue with no serial input raise SystemExit try: ser.flushInput() #create an mqtt client mypid = os.getpid() client_uniq = "arduino_pub_" + str(mypid) mqttc = mqtt.Client(client_uniq) #attach MQTT callbacks mqttc.on_connect = on_connect mqttc.on_publish = on_publish #connect to broker mqttc.connect(broker, port, 60) ser.reset_input_buffer() #remain connected to broker #read data from serial and publish while mqttc.loop() == 0: line = ser.readline() line = line.decode("utf-8") #print(output) #f.write(output)
import datetime as dt import uuid from collections import OrderedDict sensor = dht.DHT11 pin = 4 count = 0 try: #uuid generating dev_id = "SYJ" #mqtt publisher broker_address = "210.119.12.52" #ㄱㅏㅇ사님PC client2 = mqtt.Client(dev_id) client2.connect(broker_address) #dh11 init while True: count += 1 currtime = dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') #센서값가져오기 h, t = dht.read_retry(sensor, pin) #groupdata 만들기 raw_data = OrderedDict() raw_data["dev_id"] = dev_id raw_data["time"] = currtime raw_data["temp"] = "{0:0.1f}".format(t) raw_data["humid"] = "{0:0.1f}".format(h) pub_data = json.dumps(raw_data, ensure_ascii=False, indent="\t")
def __init__(self): self.__client = mqtt.Client() self.__client.connect('localhost') self.__client.loop_start()
def __init__(self): self.client = mqtt.Client() self.client.connect("10.42.0.3", 1883, 60)
"m2m:cin": {"cnf":"message", "con":\"""" + qos_string + """\" } }, "m2m:ty": 4}}""" # este payload crea un dato en el contenedor System_Properties # payload_lista.append(payload1) payload_lista.append(payload2) payload_lista.append(payload3) payload_lista.append(payload4) payload_lista.append(payload5) # payload_lista.append(payload6) # payload_lista.append(payload7) payload_lista.append(payload8) payload_lista.append(payload9) payload_lista.append(payload10) client = mqtt.Client("OM2M_MQTT") client.on_message = on_message client.connect("172.24.100.95", 1883) client.loop_start() for payload in payload_lista: client.subscribe("/oneM2M/resp/mn-cse/" + new_app["App Name"] + "/json") print("prueba del MQTT: " + payload) print() client.publish(topic, payload) time.sleep(0.05) client.on_message = on_message client.loop_stop()
def read_authcount(): strdate = datetime.now().strftime("%b %e") # print(strdate) command = "cat /var/log/auth.log | grep \"{}\" | wc -l".format(strdate) # print(command) stdoutdata, stderrdata = subprocess_open(command) strout = "{} : {}".format(strdate, stdoutdata.decode("utf-8").replace("\n", "", 1)) # print(strdate, ":", strout) client.publish("sensors/auth/dev20.gcp", strout) sleep(1) client = mqtt.Client("sensor_pub") # client.connect("dev20.vm", 1883, 60) client.connect("dev20.gcp", 1883, 60) #client.connect("seoamo.wr", 1883, 60) read_authcount() client.disconnect() # try: # while True: # read_time() # except KeyboardInterrupt: # client.disconnect() # sys.exit(0)
trackers = [] trackableObjects = {} # initialize the total number of frames processed thus far, along # with the total number of objects that have moved either up or down totalFrames = 0 totalDown = 0 totalUp = 0 # start the frames per second throughput estimator fps = FPS().start() # connection to broker mqtt broker_address = "iot.eclipse.org" print("creating new instance") client = mqtt.Client() #create new instance print("connecting to broker") client.connect(broker_address, 1883) #connect to broker # loop over frames from the video stream while True: # grab the next frame and handle if we are reading from either # VideoCapture or VideoStream frame = vs.read() frame = frame[1] if args.get("input", False) else frame # if we are viewing a video and we did not grab a frame then we # have reached the end of the video if args["input"] is not None and frame is None: break
print("Bad connection, RC = ", rc) # Pass recieved MQTT data into the processor def on_message(client, userdata, msg): try: #print("MQTT Data Recieved") print("MQTT Topic: " + msg.topic) print("Payload: " + str(msg.payload)) sensorDataHandler(msg.topic, msg.payload) except: print("error") traceback.print_exc() #def on_subscribe(mosq, obj, mid, granted_qos): #print("Subscribed") #pass mqttc = mqtt.Client() # Assign event callbacks mqttc.on_message = on_message mqttc.on_connect = on_connect #mqttc.on_subscribe = on_subscribe # Connect to the MQTT broker mqttc.connect(MQTT_Broker, int(MQTT_Port), int(Keep_Alive_Interval)) # Keep the MQTT connection looping mqttc.loop_forever(timeout=30)
if rc == 0: print("Connected to broker") global Connected Connected = True else: print("Connection failed") Connected = False #state of the connection broker_address = "test.mosquitto.org" port = 1883 user = "******" password = "******" client = mqttClient.Client("sensor1") client.on_connect = on_connect client.connect(broker_address, port=port) client.loop_start() while Connected != True: time.sleep(0.1) try: while True: value = random.randrange(min_temp_value, max_temp_value, least_count_of_temp_value) time.sleep(time_interval) print("publishing value : ", value) client.publish(topic_path, value)