提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
通过MQTT发送图片
提示:以下是本篇文章正文内容,下面案例可供参考
一、发送:Send_Pic.py
使用字节流读取图片文件,切片发送
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 2 15:12:19 2022
@author: 嗯哒
"""
import time
import paho.mqtt.client as mqtt
import os
import struct
import pandas as pd
def on_connect(client, userdata, flags, rc):
print("Connect with result "+str(rc))
def on_message(client, userdata, msg):
print("接收到的消息为:"+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_messafe = on_message
client.connect('192.168.137.1', 1883, 600)
client.loop_start()
path = ***** #图片路径
if os.path.exists(path):
#图片存在,发送图片
filepath = path
if os.path.isfile(filepath):
# 定义定义文件信息。128s表示文件名为128bytes长,l表示一个int或log文件类型,在此为文件大小
fileinfo_size = struct.calcsize('128sl')
# 定义文件头信息,包含文件名和文件大小
fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode('utf-8')),os.stat(filepath).st_size)
print(os.stat(filepath).st_size)
client.publish('Pi-1', payload = fhead, qos =0)
time.sleep(3)
filesize=os.stat(filepath).st_size
print ('client filepath: {0}'.format(filepath))
fp = open(filepath, 'rb')
re_size=0
while 1:
if filesize - re_size >= 1024: #文件切片,大小可自定义,视情况而定
data = fp.read(1024)
re_size += 1024
else:
data = fp.read(filesize - re_size)
print(len(data))
if not data:
print ('{0} file send over...'.format(filepath))
print('')
break
client.publish('Pi-1', payload = data, qos =0)
time.sleep(1)
else:
break
client.loop_stop()
print('Photos send end.')
print('Server is receiving, wait patiently please !')**
二、接收:Rece_All.py
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 5 15:45:42 2022
@author: 嗯哒
"""
import paho.mqtt.client as mqtt
import numpy as np
import pandas as pd
import time
import threading
import sys
import os
import struct
import csv
count = 0
Tag = 0
Tag_2 = 0
new_filename = 0
filesize = 0
fp = 0
writer = 0
def on_connect(client, userdata, flags, rc):
print("Connect with result: "+str(rc))
def on_message(client, userdata, msg):
global new_filename,filesize,fp,writer,Tag
#Tag==0 时接收文件名和文件大小
if Tag == 0:
if buf:
filename, filesize = struct.unpack('128sl', buf)
fn = filename.strip(str.encode('\00'))
print(fn)
new_filename = os.path.join('./', str(fn)[2:-1])
print ('file new name is {0}, filesize is {1}'.format(new_filename, filesize))
fp = open(new_filename, 'wb')
print('receiving...')
Tag = 1
#Tag == 1时接收文件内容
elif Tag == 1:
fp.write(msg.payload)
if fp.tell() >= filesize:
Tag = 0
print('1 Round over.')
fp.close()
time.sleep(1)
#接收完成,Tag置为2
Tag = 2
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect('127.0.0.1', 1883, 600)
client.subscribe('Pi-1', qos=0)
client.loop_start()
print('start')
while True:
if (Tag == 2):
client.publish('Rece', payload = bytes(('OK').encode('UTF-8')), qos =0)
#print('end')
#break
else:
pass
client.loop_stop()