Closing current session due to invalid msg order
See original GitHub issueHi,recently I have some problems with MQTT: I have a Respberry Pi 3.5 and I run python script on it to collect sounds and upload result telemetry to the Thingsboard ,here is the code for the python script :
import paho.mqtt.client as mqtt
import os, time, json,sys,socket,base64
import requests
sys.path.append('/home/pi/paho.mqtt.python/src/')
from mel_code import model_class
from configparser import ConfigParser
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
ENCODING = 'utf-8'
print(sys.path)
cfg = ConfigParser()
cfg.read('/home/pi/paho.mqtt.python/src/voice/device_config.cfg')
cfg.read('device_config.cfg')
host = cfg.get('address', 'host')
port = cfg.getint('address', 'port')
audio_path = cfg.get('checking', 'audio_path')
audio_upload_url = cfg.get('checking', 'audio_upload_url')
whether_send_audio = cfg.getboolean('common', 'whether_send_audio')
voice_status = {"0": "NORMAL", "3": "BELT_MALFUNCTION", "4": "PILLOW_MALFUNCTION", "2": "WHITE_NOISE", "1": "MALFUNCTION"}
keep_alive = 60
access_token = cfg.get('address', 'access_token')
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
def getserial():
# Extract serial from cpuinfo file
cpu_serial = "0000000000000000"
try:
f = open('/proc/cpuinfo', 'r')
for line in f:
if line[0:6] == 'Serial':
cpu_serial = line[10:26]
f.close()
except:
cpu_serial = "ERROR000000000"
return cpu_serial
serial_number = getserial()
def publish_message(tile,payload,qos):
current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
print(payload)
client = mqtt.Client(serial_number+current_time)
client.enable_logger(logger)
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(access_token)
client.connect(host, port, keep_alive)
print(payload)
client.publish(tile, payload=payload, qos=qos)
time.sleep(0.1)
client.loop_start()
client.disconnect()
def send_data_to_server(audio_path, file_name, transfer_file_name):
print("Start to upload audio file ")
f = open(audio_path + file_name, "rb")
audio_data = f.read()
audio_bytes = bytearray(audio_data)
multipart_form_data = {
'file': (str(transfer_file_name), audio_bytes),
'originalFilename': ('', str(transfer_file_name)),
}
response = requests.post(audio_upload_url + '/v1/sensor/audio', files=multipart_form_data)
print(response.status_code)
def record_sound(input_audio_path, audio_name):
##获取当前时间
audio_file_whole_path = input_audio_path + audio_name
# 录制声音
os.system("arecord -d 20 -f cd -c 1 -t wav " + audio_file_whole_path)
return audio_file_whole_path
def publish_audio_file():
current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
audio_name = current_time + '.wav'
audio_ab_path = record_sound(audio_path,audio_name)
f = open(audio_ab_path, "rb")
#f = open("/home/pi/record/test.txt","rb")
audio_data = f.read()
audio_bytes = bytes(audio_data)
#publish_message("voice/audio", audio_bytes, 0)
publish_message("v1/devices/me/telemetry", audio_bytes, 0)
f.close()
def get_host_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
def get_voice_status(status):
if status == 1:
return voice_status['1']
elif status == 0:
return voice_status['0']
elif status == 2:
return voice_status['2']
elif status == 3:
return voice_status['3']
elif status == 4:
return voice_status['4']
else:
return voice_status['1']
def public_warning_message():
ai_engine_module = model_class.AudioModel()
current_time = time.strftime("%Y%m%d%H%M%S", time.localtime())
audio_name = current_time + '.wav'
audio_ab_path = record_sound(audio_path, audio_name)
status = ai_engine_module.predict(audio_ab_path)
print("Ai Response" + str(status))
voice_type = get_voice_status(status)
transfer_file_name = current_time + '_' + voice_type + '_' + serial_number + '.wav'
if whether_send_audio:
send_data_to_server(audio_path, audio_name, transfer_file_name)
ip = get_host_ip()
message = json.dumps({"deviceSerialNo": serial_number, "ip": ip, "status": status, 'file_name': str(transfer_file_name)})
publish_message("v1/devices/me/telemetry", message, 1)
if __name__ == "__main__":
#publish_message("sensor", "Hello Broker ", 0)
#publish_audio_file()
public_warning_message()
I’m sure it can successfully upload the data in the 2.3.9 snapshot version, here is the history data:
now I update to 2.4.1-release version, thingsboard can not recive the telemetry,here is the logs:
I don’t know why he shut down sessions for no reason If anyone has had the same problem as me, please tell me
Issue Analytics
- State:
- Created 4 years ago
- Comments:8 (3 by maintainers)
Top Results From Across the Web
ESP8266 MQTT Thingsboard - No telemetry problem
IOException: An existing connection was forcibly closed by the remote host ... [mqtt414] Closing current session due to invalid publish msg ...
Read more >Resolving Session Time-Out Errors - Support Center
The Session Time-Out message is normally displayed after several hours have elapsed since your last interaction with the server. If this happens, you...
Read more >invalid session id using Selenium with ChromeDriver and ...
invalid session id ; r'C:\Utility\BrowserDrivers\chromedriver.exe') print ; "Current session is {}".format ; # closes current window/tab driver.
Read more >MQTT - AWS IoT Core - AWS Documentation
Persistent sessions expire if the client doesn't reconnect within the timeout period. After a persistent session expires, the client's subscriptions and saved ...
Read more >How to Fix Session Has Expired Error on the Internet
If your Internet connection is unstable, periodically disconnecting and reconnecting, it can cause a website session to expire. When the ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Just add
time.sleep(1)
after yourclient.connect()
👌@piqueza it would be interesting to calculate network traffic consumed by such application with different protocols used. I am quite sure that even HTTP would be more efficient in this case. CoAP - for sure.