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:
- parse out the JSON Data from a Publish event such as sensor data.
- Given Device ID, query a database for device alert settings
- Send a SMS text alert using Twillio if payload from the particle device is outside of alert settings that were in the database.
- 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)