Server Sent Events (SSE Client) intermittently stops working? Suggestions appreciated!

I wrote a python script that establishes a Server Sent Events (SSE) Client connection to the particle cloud. This Python script is running a hardwired network connected raspberry Pi. This SSE Client then process all the data coming from my product including:

  1. parse out the JSON Data from a Publish event such as sensor data.
  2. Given Device ID, query a database for device alert settings
  3. Send a SMS text alert using Twillio if payload from the particle device is outside of alert settings that were in the database.
  4. Store the remainder of the payload into a database.

This generally works very well once I got ride of some errors that were occurring. However, occasionally it just stops processing events all together almost like it lost connection to the Particle Cloud. However, there is no error message of any kind. Only way to give it a kick start is to stop/start the python script. Is there any timeout period or re-authentication needed once an SSE Connection is established to the particle cloud? Any advice on where to start to fix this? Here are the important snippets of code:

Function to obtain SSE Client Credentials:

def oauthGetToken():
    data = {
    'grant_type': 'password',
    'username': Config.PARTICLE_USER,
    'password': Config.PARTICLE_PW
    }

    response = requests.post('https://api.particle.io/oauth/token', data=data, auth=( Config.PARTICLE_CLIENTID, Config.PARTICLE_CLIENTSECRET))
    dictFromServer = response.json()
    access_token = dictFromServer.get('access_token')
    print("Access Token Recieved from Particle")
    return access_token

Then this is the particle related part of my Run.py script:

access_token=oauthGetToken()
messages = SSEClient('https://api.particle.io/v1/products/xxxxx/events/?access_token=' + access_token)
print('SSE Session Estbalished')

#Loop through each message recieved from Particle
for msg in messages:
    
    #Get the message event type. This is the Publish Event name. 
    event = str(msg.event)

    #Only add events to SQL that have the event name of "Stat"
    if event == 'Stat':
    (Rest of my script is here)

bump

The SSE client must:

Gracefully handle disconnection (TCP RESET and TCP CLOSE) from the host by reconnecting, preferably with a backoff timeout.

It should also handle timeout. The server will sent a ping (empty command) every 60 seconds. If this is not received, the SSE client should disconnect and reconnect, however this should be done with care due to rate limiting on making SSE connections.

It is possible for the SSE server to request disconnecting at any time, and the client must be able to handle reconnecting. This can also happen due to disruptions on the Internet.

1 Like