Skip to content

Instantly share code, notes, and snippets.

@grambas
Created February 15, 2019 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grambas/e55c77cfca289f3906fae9b112aed91b to your computer and use it in GitHub Desktop.
Save grambas/e55c77cfca289f3906fae9b112aed91b to your computer and use it in GitHub Desktop.
Embedded #python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" This Module reads data from serial port
then converts to JSON and sends to Amazon Firebase
"""
import serial
from time import sleep
from firebase import firebase
import json
arduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=65)
sleep(2)
arduino.flushInput()
firebase = firebase.FirebaseApplication('https://garden-c4dc3.firebaseio.com/')
def closeAndOpen(ser):
ser.close()
sleep(5)
try:
ser.open()
except serial.SerialException as e:
print("Trying recursice to open connection")
print(e)
sleep(5)
closeAndOpen(ser)
ser.flushInput()
print("Connection closed and opend")
return
def processInput(input):
if(isValidJson(input) is True):
data = json.loads(input)
postToFirebase(data['type'], data)
else:
print("input is not valid json or desnt have type key:")
print(input)
postToFirebase('debug', data)
return
def isValidJson(myjson):
try:
data = json.loads(myjson)
except ValueError:
return False
if 'type' in data:
return True
return False
def postToFirebase(path, data):
try:
firebase.post(path, data)
print('data successfuly posted')
print(data)
except Exception as e:
print('error by upoading to firebase')
print(e)
return
while True:
print("Waiting for input...")
try:
dataIn = arduino.readline()[:-1]
except serial.SerialException as e:
print("There is no new data from serial port")
print(e)
closeAndOpen(arduino)
except TypeError as e:
# Disconnect of USB->UART occured
print("Disconnect of USB->UART occured")
closeAndOpen(arduino)
else:
# Some data was received
processInput(dataIn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment