Demo entry 6722428

Subscriber

   

Submitted by Pengzhan Xu on Mar 23, 2018 at 01:36
Language: Python. Code size: 8.7 kB.

import paho.mqtt.client as mqtt
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from matplotlib import style
from mpl_toolkits.mplot3d import Axes3D
import time
import sys
import json


broker_address = "172.23.135.147"   
port = 1883
topic= ["temp","hum","acceleration","orientation","control"]
host="pc"

print("creating new instance")
client = mqtt.Client(host)


xs=[]
ys=[]
zs=[]
ylab=0
xlab=0
zlab=0
num=0
gflag = False


mqtt.Client.connected_flag = False
mqtt.Client.bad_connection_flag=False



def on_connect(client,userdata,flags,rc):
    if rc == 0:
        client.connected_flag= True
        print("Connected with result code ="+str(rc)+" Connected OK")     
    else:
        print("Bad connection reurned code =",str(rc))
        client.bad_connection_flag= True
      
def on_disconnect(client,userdata,flags,rc=0):
    print("disconnecting reason "+str(rc)+"client_id ")
    client.connected_flag=False
def on_message(client,userdata,message):
    print("received message:"+str(message.payload.decode("utf-8"))+" on topic:"+message.topic+" with QoS "+str(message.qos))
    global ylab,xlab,zlab,gflag,num
    topic = message.topic
    if topic == 'temp':
        data0 = json.loads(message.payload.decode("utf-8"))
        ylab = data0['temp']
        num=num+1
        xlab = num #data0['time']
        gflag = False
    elif topic == 'hum':
        data1 = json.loads(message.payload.decode("utf-8"))
        ylab = data1['hum']
        num=num+1
        xlab = num  #data1['time']
        gflag = False
    elif topic == 'acceleration':
        data2 = json.loads(message.payload.decode("utf-8"))
        xlab = data2['x']
        ylab = data2['y']
        zlab = data2['z']
        gflag = True
    elif topic == 'orientation':
        data3 = json.loads(message.payload.decode("utf-8"))
        xlab = data3['pitch']
        ylab = data3['roll']
        zlab = data3['yaw']
        gflag = True
    else:
        gflag = False
        print("other message ")
def on_unsubscribe(client,userdata,mid):
    print("unsubscribe to current topic")

def animate(i):
    ys.append(ylab)
    xs.append(xlab)
    zs.append(zlab)
    if gflag == True:
        m=len(xs)
        if m<=20:
           ax1.clear()
           ax1.scatter(xs,ys,zs,c='red')
        else:
           ax1.clear()
           ax1.scatter(xs[m-20:m],ys[m-20:m],zs[m-20:m],c='red')
    else:
        n=len(xs)
        if n<=10:
                    ax1.clear()
                    ax1.plot(xs,ys)
        else :
                    ax1.clear()
                    ax1.plot(xs[n-10:n],ys[n-10:n])

client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.on_unsubscribe = on_unsubscribe


print("Connecting to broker",broker_address)
try:
    client.connect(broker_address ,port ,60)
except:
    print("Connection failed")
    sys.exit("quitting")
    
client.loop_start()

while not client.connected_flag and not client.bad_connection_flag:
        print("In wait loop")
        time.sleep(2)
while client.bad_connection_flag:
         client.loop_stop()
         sys.exit()
         
try:
    while client.connected_flag:
        print("please choose a topic \n 0 is temp \n 1 is hum \n 2 is acceleration \n 3 is orientation \n 4 is control\n")
        opt=int(input())
        if opt == 0:
            try:
                    client.subscribe(topic[0])
                    print("subscribing to "+topic[0])
                    print("input 1 to show graphic")
                    num=0
                    fig = plt.figure(dpi=60,figsize=(10,6))
                    ax1 = fig.add_subplot(1,1,1)
                    while True:
                            ani = animation.FuncAnimation(fig,animate,interval=200)
                            plt.show()
                            #time.sleep(1)
                            if int(input())==1:
                                fig = plt.figure(dpi=60,figsize=(10,6))
                                ax1 = fig.add_subplot(1,1,1)
            except KeyboardInterrupt:
                ax1.clear()
                plt.close()
                client.unsubscribe(topic[0])
                print("interrupted by keyboard, please chooose again ")
        elif opt ==1:
            try:
                    client.subscribe(topic[1])
                    print("subscribing to "+topic[1])
                    print("input 1 to show graphic")
                    num=0
                    fig = plt.figure(dpi=60,figsize=(10,6))
                    ax1 = fig.add_subplot(1,1,1)
                    while True:
                            ani = animation.FuncAnimation(fig,animate,interval=200)
                            plt.show()
                            #time.sleep(1)
                            if int(input())==1:
                                fig = plt.figure(dpi=128,figsize=(10,6))
                                ax1 = fig.add_subplot(1,1,1)                            
            except KeyboardInterrupt:
                ax1.clear()
                plt.close()
                client.unsubscribe(topic[1])
                print("interrupted by keyboard, please chooose again ")
        elif opt ==2:
            try:
                    client.subscribe(topic[2])
                    print("subscribing to "+topic[2])
                    print("input 1 to show graphic")
                    fig = plt.figure(dpi=128,figsize=(10,6))
                    ax1 =Axes3D(fig)
                    ax1.set_zlabel('Z')
                    ax1.set_ylabel('Y')
                    ax1.set_xlabel('X')
                    while True:
                            ani = animation.FuncAnimation(fig,animate,interval=200)
                            plt.show()
                            #time.sleep(1)
                            if int(input())==1:
                                fig = plt.figure(dpi=128,figsize=(10,6))
                                ax1 =Axes3D(fig)
                                ax1.set_zlabel('Z')
                                ax1.set_ylabel('Y')
                                ax1.set_xlabel('X')
            except KeyboardInterrupt:
                ax1.clear()
                plt.close()
                client.unsubscribe(topic[2])
                print("interrupted by keyboard, please chooose again ")
        elif opt == 3:
            try:
                    client.subscribe(topic[3])
                    print("subscribing to "+topic[3])
                    print("input 1 to show graphic")
                    fig = plt.figure(dpi=128,figsize=(10,6))
                    ax1 =Axes3D(fig)
                    ax1 = plt.subplot(111,projection='3d')
                    ax1.set_zlabel('Z')
                    ax1.set_ylabel('Y')
                    ax1.set_xlabel('X')
                    while True:
                            ani = animation.FuncAnimation(fig,animate,interval=200)
                            plt.show()
                            #time.sleep(1)
                            if int(input())==1:
                                fig = plt.figure(dpi=128,figsize=(10,6))
                                ax1 =Axes3D(fig)
                                ax1 = plt.subplot(111,projection='3d')
                                ax1.set_zlabel('Z')
                                ax1.set_ylabel('Y')
                                ax1.set_xlabel('X')
            except KeyboardInterrupt:
                ax1.clear()
                plt.close()
                client.unsubscribe(topic[3])
                print("interrupted by keyboard, please chooose again ")
        elif opt ==4:
            runflag = True
            try:
                while runflag == True:
                    print("please send ")
                    msg=input()
                    data4 = {
                        'com':msg
                        }
                    data4 = json.dumps(data4)
                    ret=client.publish(topic[4],data4,0)
                    print("publish to "+topic[4])
                    time.sleep(3)
            except KeyboardInterrupt:
                runflag = False
                client.unsubscribe(topic[4])
                print("interrupted by keyboard, please chooose again")
        else:
            print("invalied input")
        
except KeyboardInterrupt:
            print("interrrupted by keyboard")
            client.disconnect()
            client.loop_stop()
            sys.exit()
        

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).