dead socket connection

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
patvdleer
Posts: 46
Joined: Mon Jun 13, 2016 11:52 am
Location: Maastricht, NL, Europe
Contact:

dead socket connection

Post by patvdleer » Wed Jun 15, 2016 11:01 am

After a few minutes my socket connection seems dead... I have had the same issue with SSH on my laptop, somehow I think my router drops idle connections. Is there any way I can detect this since there isn't an exception raised. The main while True loop keeps running and outputting the temp but the values don't show up in my MQTT server after a few minutes.

Code: Select all

def boot():
    global mcp, mqtt
    # 5 : D1 : SDL
    # 4 : D2 : SDA
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000)
    mcp = mcp9808.MCP9808(i2c=i2c)
    mcp.set_resolution(mcp9808.T_RES_AVG)

    mqtt = MQTT(config.MQTT_ADDR)
    mqtt.connect()


def run():
    global mcp, mqtt
    while True:
        temp = mcp.get_temp()
        print(temp)
        mqtt.publish("/temperature", temp)
        for _ in range(1, 55):
            # for cntrl C to work via tty
            time.sleep(1)

Code: Select all

import socket
import time
try:
    import binascii
except ImportError:
    import ubinascii as binascii

import config


class MQTT(object):
    s = None
    addr = None
    prefix = ""

    def __init__(self, host, port=1883, prefix=config.MQTT_PREF):
        self.addr = socket.getaddrinfo(host, port)[0][4]
        self.prefix = prefix
        self.reset_socket()

    def reset_socket(self):
        self.s = socket.socket()

    def connect(self):
        address = self.addr
        self.s.connect(address)
        self.s.send(self.mtpConnect(config.DEVICE_NAME))

    def disconnect(self):
        self.s.send(self.mtpDisconnect())
        self.s.close()

    def publish(self, topic, data, sleep=1):
        self.s.send(self.mtpPub(self.prefix+topic, bytes(str(data), 'ascii')))
        if sleep:
            time.sleep(sleep)

    def recv(self, length=4096):
        return binascii.hexlify(self.s.recv(length))

    @staticmethod
    def mtStr(s):
        return bytes([len(s) >> 8, len(s) & 255]) + s.encode('utf-8')

    @staticmethod
    def mtPacket(cmd, variable, payload):
        return bytes([cmd, len(variable) + len(payload)]) + variable + payload

    def mtpConnect(self, name):
        return self.mtPacket(
            0b00010000,
            self.mtStr("MQTT") +  # protocol name
            b'\x04' +  # protocol level
            b'\x00' +  # connect flag
            b'\xFF\xFF',  # keepalive
            self.mtStr(name)
        )

    @staticmethod
    def mtpDisconnect():
        return bytes([0b11100000, 0b00000000])

    def mtpPub(self, topic, data):
        return self.mtPacket(0b00110001, self.mtStr(topic), data)

TTY output

Code: Select all

connected with 0x43, channel 6
dhcp client start...
STAT_CONNECTING
STAT_CONNECTING
STAT_CONNECTING
ip:192.168.178.12,mask:255.255.255.0,gw:192.168.178.1
23.0
23.0
23.0
23.0
NodeMCU v0.9 / V1 / V2 / V3
WeMos D1 Mini
WeMos Lolin32 v1.0.0
WeMos Lolin D32 Pro V2

Post Reply