[QuecPython] MQTT protocol Tencent Cloud data reporting for EC800M IoT development board

[QuecPython] MQTT protocol Tencent Cloud data reporting for EC800M IoT development board

Import library

from TenCentYun import TXyun
import ujson as json

The json library here is for reporting data.

initialization

TXyun(productID, devicename, devicePsk, ProductSecret)

Configure the product information and device information of the Tencent IoT platform IoT suite.

Parameter Description:

productID - product identification (unique ID), type string
devicename - device name, type string
devicePsk - device key (one When using the one-password authentication scheme, this parameter is passed to None), string type, optional parameter, the default is None
ProductSecret - product key, string type, when using the one-machine-one-password authentication scheme , this parameter is passed into None
When using the one-type-one-password authentication scheme, this parameter is passed into the real product key
Return value description:

Returns the TXyun connection object.

Set up MQTT

TXyun.setMqtt(clean_session, keepAlive=300,reconn=True)

Set the parameters of the MQTT data channel

Parameter Description:

clean_session - Product identification (unique ID), boolean type, if True,
then the agent will delete all information about this client when it disconnects. If False, the client is a durable client and subscription information and queued messages will be retained when the client disconnects. The default is False
keepAlive - the maximum time period allowed between communications (in seconds), integer type, default is 300, range (60-1000), more than 300 is recommended Return value description:
reconn - (optional) Flag that controls whether to use internal reconnection, Boolean type, enabled by default to True

An integer value of 0 is returned on success, and an integer value of -1 is returned on failure.

Register callback

TXyun.setCallback(callback)

Register callback function.

Parameter Description:

callback - Set the message callback function, function type, this method is triggered when the server responds
Callback function parameters

topic - mqtt topic topic, string type
msg - the data to be sent, string type

like:

def sub_callback(topic, msg):   # IoT 平台消息响应回调函数
    print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(), msg.decode()))

Subscription publishing function

TXyun.subscribe(topic,qos)

Subscribe to the mqtt topic.

Parameter Description:

topic - mqtt topic topic, string type
qos - MQTT message quality of service (default 0, 0 or 1 can be selected), integer type
0: The sender only sends the message once and does not retry 1: The sender sends the message at least once to ensure that the message reaches the Broker
Return value description:

An integer value of 0 is returned on success, and an integer value of -1 is returned on failure.

Start service

TXyun.start()

Send a message

TXyun.publish(topic,msg, qos=0)

make an announcement.

Parameter Description:

topic - mqtt topic topic, string type
msg - data to be sent, string type
qos - MQTT message quality of service (default 0, you can choose 0 or 1), integer type
0: The sender only sends the message once and does not retry 1: The sender sends the message at least once to ensure that the message reaches the Broker
Return value description:

An integer value of 0 is returned on success, and an integer value of -1 is returned on failure.

Note that you need to use thejson.dumps function to convert it to json format:

def TX_Cloud_Send(handle,topic,msg_dir):
    msg_json=json.dumps(str(msg_dir))
    handle.publish(topic, msg_json)   # 发布消息

Function packaging

from TenCentYun import TXyun
import ujson as json

def TX_Cloud_Send(handle,topic,msg_dir):
    msg_json=json.dumps(str(msg_dir))
    handle.publish(topic, msg_json)   # 发布消息

def TX_Cloud_Init(productID,devicename,devicePsk,ProductSecret,topic,callback): 
    try:
        handle=TXyun(productID, devicename, devicePsk, ProductSecret)  # 创建连接对象
        handle.setMqtt()  # 设置mqtt
        handle.setCallback(callback)   # 设置消息回调函数
        
        handle.subscribe(topic)   # 订阅Topic
        handle.start()
        #tenxun.publish(topic, "hello world mqtt")   # 发布消息
        msg_dir = {
    
    "test0":"","test1":1}
        TX_Cloud_Send(handle,topic,msg_dir)     
        return handle     
    except Exception as e:
        print("TX_Cloud Error",e)
        return None

transfer

    TX_Cloud_Handle = TX_Cloud.TX_Cloud_Init(productID_my,devicename_my,devicePsk_my,ProductSecret_my,topic_my,sub_callback)
    if TX_Cloud_Handle:
        r=1
    else:
        r=0
    print("TX_Cloud Init",r)

Test effect

Insert image description here

Appendix: List assignment types and py packaging

list assignment

BUG recurrence

I wrote a small program when I had nothing to do. The code is as follows:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

I made a 16-time for loop in the program and added "_" and the loop serial number after each value of list a.
For example, the xth time of looping is Add _x to the , '1_1', '2_2', '3_3', '4_4', '5_5', '6_6', '7_7', '8_8', '9_9', '10_10', '11_11', '12_12', ' 13_13', '14_14', '15_15'] This is also correct

At the same time, I write the value of list a into the empty list c during each cycle. For example, the xth cycle is to write the changed value of list a into the xth position of list c
The value of c[0] after the 0th loop should be ['0_0', '1', '2', '3', '4', '5', '6', '7' , '8', '9', '10', '11', '12', '13', '14', '15'] This is also correct
But in the 1st After this cycle, the value of c[0] has been changing into the value of c[x]
, which is equivalent to changing c_list[0] into c_list[1]...and so on. The value of the resulting list c is exactly the same for every item
I don’t understand what’s going on
My c[0] is only at the 0th time It is assigned a value during the loop but its value changes later

As shown in the figure:
Insert image description here
The first time a bug occurred. After the assignment, the value of c[0] was changed every time it was looped. It took a long time and it didn’t work out
No matter whether it is added with the append function or defined with a two-dimensional array or a third empty array is added for transition, it cannot be solved

Code improvements

Later, under the guidance of my Huake classmates, I suddenly thought that the assignment can be assigned to an address. The value in the address keeps changing, causing the assignment to keep changing. So I used the loop within loop deep copy in the second picture to implement it.

code show as below:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        for i in range(16):
            c_list[j].append(a_list[i])
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
print(c_list,'\n')    

solved the problem

Insert image description here

optimization

The third time I asked the teacher to use the copy function to assign a true value.

code show as below:

# -*- coding: utf-8 -*-
"""
Created on Fri Nov 19 19:47:01 2021

@author: 16016
"""

a_list = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15']
#print(len(a_list))
#b_list = ['','','','','','','','','','','','','','','','']
c_list = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
#for i in range(16):
if len(a_list):
    for j in range(16):
        a_list[j]=str(a_list[j])+'_'+str(j)
        print("序号:",j)
        print('a_list:\n',a_list)
        
        
        c_list[j]=a_list.copy()
        print('c_list[0]:\n',c_list[0])
        print('\n')
#        b_list[j]=a_list[7],a_list[8]
#        print(b_list[j])
        # 写入到Excel:
#print(c_list,'\n')    

The problem can also be solved
Insert image description here
Finally, the problem is concluded that the pointer is to blame!

a_list points to an address, not a value. a_list[i] points to a single value. The copy() function also copies a value, not an address.

If this is written in C language, it will be more intuitive. No wonder C language is the basis. If you don’t learn C in optical Python, you will not be able to solve such a problem.

C language yyds What kind of rubbish retarded language is Python?

Summarize

Since Python cannot define a value as a pointer or an independent value, it can only be transferred using a list
As long as the assignment points to a list as a whole, it is a pointer memory address. There is only one solution, which is to deeply copy and assign each value (extract the elements in the sublist and reconnect them in sequence) or use the copy function to assign values ​​individually

Test as shown:
Insert image description here
Insert image description here
Insert image description here
Insert image description here
Insert image description here
Part of the code:

# -*- coding: utf-8 -*-
"""
Created on Sat Nov 20 16:45:48 2021

@author: 16016
"""

def text1():
    A=[1,2,3]
    B=[[],[],[]]
    for i in range(len(A)):
        A[i]=A[i]+i
        B[i]=A
        print(B)

def text2():
    A=[1,2,3]
    B=[[],[],[]]
    
    A[0]=A[0]+0
    B[0]=A
    print(B)
    A[1]=A[1]+1
    B[1]=A
    print(B)
    A[2]=A[2]+2
    B[2]=A
    print(B)
    
if __name__ == '__main__':
    text1()
    print('\n')
    text2()

py package

Pyinstaller packages exe (including packaging resource files, never error version)

Dependent packages and their corresponding version numbers

PyQt5 5.10.1
PyQt5-Qt5 5.15.2
PyQt5-sip 12.9.0

pyinstaller 4.5.1
pyinstaller-hooks-contrib 2021.3

Pyinstaller -F setup.py package exe

Pyinstaller -F -w setup.py packaging without console

Pyinstaller -F -i xx.ico setup.py packages the specified exe icon package

Package exe parameter description:

-F: Only a single exe format file is generated after packaging;

-D: Default option, creates a directory containing exe files and a large number of dependent files;

-c: Default option, use the console (a black box similar to cmd);

-w: Do not use the console;

-p: Add a search path to find the corresponding library;

-i: Change the icon of the generated program.

If you want to package resource files
you need to convert the path in the code
Also note that if you want to package resource files py The path in the program needs to be changed from ./xxx/yy to xxx/yy and the path conversion is performed
But if the resource file is not packaged, it is best to use the path as ./xxx/yy and not perform the path conversion. Path conversion

def get_resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)

Then add the directory in the datas part of the spec file
For example:

a = Analysis(['cxk.py'],
             pathex=['D:\\Python Test\\cxk'],
             binaries=[],
             datas=[('root','root')],
             hiddenimports=[],
             hookspath=[],
             hooksconfig={
    
    },
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

Then directly Pyinstaller -F setup.spec

If the packaged file is too large, just change the excludes in the spec file and include the libraries you don’t need (but have already been installed in the environment).

These unnecessary libraries are output in the shell during the last compilation
For example:
Insert image description here

Insert image description here
Then use pyinstaller --clean -F XX.spec

Guess you like

Origin blog.csdn.net/weixin_53403301/article/details/134398609