Skip to content

Commit

Permalink
Merge pull request #4 from Jbithell/pusher
Browse files Browse the repository at this point in the history
Move to Pusher.com based solution - instead of AJAX polling
  • Loading branch information
Jbithell authored Mar 24, 2018
2 parents dc928f7 + 1e08b16 commit cb50144
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 28 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,6 @@ atlassian-ide-plugin.xml
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
fabric.properties

.idea
13 changes: 9 additions & 4 deletions Dockerfile.template
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@ FROM resin/%%RESIN_MACHINE_NAME%%-debian
python3-dev \
python3-pip \
python3-tk \
python3-setuptools \
python3-pip \
python3-cffi \
libssl-dev \
libffi-dev \
libfreetype6-dev \
rpl \
git \
nano

RUN sudo easy_install3 pip
RUN pip install pyserial
RUN pip3 install -U setuptools
RUN pip3 install cffi
RUN pip3 install cairocffi
RUN pip3 install pyserial pusher
#pip also install - git+https://github.com/resin-io/resin-sdk-python.git

# Set our working directory
Expand All @@ -35,4 +40,4 @@ COPY . ./
RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# main.py will run when container starts up on the device
CMD ["bash","/usr/src/app/start.sh"]
CMD ["python3","/usr/src/app/main.py"]
48 changes: 29 additions & 19 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import urllib.request #For internet
import json #To parse response
import sqlite3 #Database
import pusher #Pusher.com

os.environ['TZ'] = 'Europe/London' #SetTimezone
def log(message):
Expand All @@ -27,8 +28,6 @@ def reboot():
time.sleep(60) # Just in case that api call fails AGAIN as it sometimes does
sys.exit() #This forces a container restart anyway

sqliteconn = sqlite3.connect("/data/weatherdatabase.sqlite3")

serialport = os.environ.get('serialPort', '/dev/ttyUSB0')
baudrate = os.environ.get('baudRate', 19200) #Set the Baudrate to 19200 which is a nice default for the davis logger
try:
Expand Down Expand Up @@ -61,6 +60,17 @@ def reboot():
log("[INFO] Quitting")
ser.readline() #Read the /r character that follows but ignore it

log("[INFO] Connecting to Pusher")
pusher_client = pusher.Pusher(
app_id=os.environ.get('PUSHERappid'),
key=os.environ.get('PUSHERkey'),
secret=os.environ.get('PUSHERsecret'),
cluster='eu',
ssl=True
)
log("[INFO] Connected to Pusher")


log("[INFO] Ready to start getting data")
previousworkingresponse = "" #Global var
errorcount = 0
Expand Down Expand Up @@ -116,31 +126,31 @@ def looprequest():
errorcount = errorcount + 1
previousworkingresponse = thisresponse
return data
def storefailedrequest(data): #Cache all the requests that didn't work
global sqliteconn
cursor = sqliteconn.cursor()
cursor.execute('INSERT INTO `weatherData`(`id`,`timestamp`,`windSpeedMPH`,`windSpeed10MinAverageMPH`,`windDirection`,`temperatureC`,`humidity`,`barometer`) VALUES (NULL,' + str(data["timestamp"]) + ',' + str(data["windSpeed"]) + ',' + str(data["wind10MinAverage"]) + ',' + str(data["windDirection"]) + ',' + str(data["temperatureC"]) + ',' + str(data["humidity"]) + ',' + str(data["barometer"]) + ');')
cursor.commit()
cursor.close()
lastSentToServerTime = time.time()

while True:
data = looprequest()
if data:
if time.time()-lastSentToServerTime > os.environ.get('serverSendFrequency', 60): #Send the server a reading every minute
try:
requestPayload = urllib.parse.urlencode(data).encode("utf-8")
requestResponse = urllib.request.urlopen(os.environ.get('uploadUrl', ''), requestPayload)
response = requestResponse.read().decode('utf-8')
requestParsedResponse = json.loads(response)
if requestParsedResponse["success"] != True:
print(response)
log("[ERROR] Couldn't upload the data online - server rejected with " + str(requestParsedResponse["message"]))
except Exception as e:
log("[ERROR] Couldn't upload data online " + str(e))
try:
requestPayload = urllib.parse.urlencode(data).encode("utf-8")
requestResponse = urllib.request.urlopen(os.environ.get('uploadUrl', ''), requestPayload)
response = requestResponse.read().decode('utf-8')
requestParsedResponse = json.loads(response)
if requestParsedResponse["success"] != True:
print(response)
log("[ERROR] Couldn't upload the data online - server rejected with " + str(requestParsedResponse["message"]))
#storefailedrequest(data)
pusher_client.trigger('PSCWeatherDataLive', 'PSCWeatherDataLiveNEWReading', {'message': {'reading': data}})
log("[SUCCESS] Sent Data to Pusher.com")
except Exception as e:
log("[ERROR] Couldn't upload data online " + str(e))
#storefailedrequest(data)
log("[ERROR] Couldn't upload data to Pusher " + str(e))

if errorcount > 5: #If it's hit an error more than 5 times just reboot it
reboot()

time.sleep(2)
time.sleep(1) #Only take a reading every second

log("[INFO] End of Program")
4 changes: 0 additions & 4 deletions start.sh

This file was deleted.

Binary file removed weatherdatabase.sqlite3
Binary file not shown.

0 comments on commit cb50144

Please sign in to comment.