OK, probably overkill for your needs...
main.py
Code: Select all
#!/usr/bin/env python
from random import randint
from glob import glob
from os.path import join, dirname
from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.properties import StringProperty
from kivy.uix.carousel import Carousel
from kivy.uix.image import AsyncImage
from kivy.uix.scatter import Scatter
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.button import Button
import RPi.GPIO as GPIO
from webtimeout import WebTimeout
# Some of your web stuff is constant so define it here:
headers = {"X-Parse-Application-Id": "${APPLICATION_ID}",
"X-Parse-REST-API-Key": "${REST_API_KEY}",
"Content-Type": "application/json"
}
address = "https://api.parse.com//1/classes/GameScore/Ed1nuqPvcm"
method = "PUT"
data = None
class Screen(FloatLayout):
def __init__(self, **kwargs):
super(Screen, self).__init__(**kwargs)
# # Here's your GPIO stuff
GPIO.setmode(GPIO.BCM)
GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
self.n = 0
# Add a call function
GPIO.add_event_detect(4,
GPIO.RISING,
callback=self.my_callback,
bouncetime=500)
layout = BoxLayout(orientation='horizontal', spacing=3)
#il parametro spacing determina la distanza tra i due box
# Create a template for your text
self.tx ='[b][size=45][color=ff3333]The value of n is {n}[/color][/size][/b]'
self.lbl = Label(text=self.tx.format(n=self.n),
markup=True,
size_hint=(.4, 1),
pos_hint={"center_x":.5, "center_y":.7})
# This is a blank label for handling the response from the web request
self.callback_lbl = Label(text="", size_hint=(None,None),
size=(200,50), pos=(200,100))
carousel = Carousel(direction='right', size_hint=(.6, 1))
carousel.loop = True
curdir = dirname(__file__)
for filename in glob(join(curdir, '/home/pi/mufolder/img', '*')):
picture = Image(source=filename,allow_stretch=True)
carousel.add_widget(picture)
Clock.schedule_interval(carousel.load_next, 5)
layout.add_widget(carousel)
layout.add_widget(self.lbl)
self.add_widget(layout)
self.add_widget(self.callback_lbl)
def my_callback(self, channel):
print "rising detected on GPIO 4"
self.n += 1
# Update our template with the current value of n
tx = self.tx.format(n=self.n)
# Print it
print tx
# Update the text on the label.
self.lbl.text = tx
# This is where the web request is created
# if you need to submit data, prepare that here (assuming it's not
# constant) e.g.
data = {"score": self.n}
# The example below is set up to run a callback method when the web
# requests ends
wt = WebTimeout(address=address, headers=headers, timeout=10,
method=method, data=data,
callback=self.my_web_callback)
wt.start()
def my_web_callback(self, result):
# This is the callback function
# Result is a tuple of:
# sucess: True if web request submitted successfully
# result: The reponse from the web page
success, response = result
# As an example, I'm just showing a label if the request was submitted
# successfully
if success:
txt = "Web request submitted successfully"
else:
txt = "Error submitting web request"
self.callback_lbl.text = txt
class MainApp(App):
def build(self):
#imposto il colore dello sfondo
Window.clearcolor = (255, 255, 255, 1)
#Window.size=(500, 500)
return Screen()
MainApp().run()
webtimeout.py
Code: Select all
#!/usr/bin/env python
from threading import Thread
import socket
import requests
class WebTimeout(Thread):
'''An example class to show how web requests can be submitted in a
background thread.
Takes one mandatory parameter:
address: The web address to request
Takes six optional parameters:
timeout: Number of seconds until request timesour
data: Data to be submitted with request (e.g. via POST)
headers: Headers to be added to the request
queue: Queue object for thread-safe communication
method: GET, POST, DELETE, PUT
callback: Function to be called when request ends
'''
def __init__(self, address, timeout=5, data=None, headers=None, queue=None,
method="GET", callback=None):
Thread.__init__(self)
self.q = queue
self.timeout = timeout
self.address = address
self.data = data
self.headers = headers
self.method = method.lower()
self.callback = callback
def _sendRequest(self):
'''Method to send the request. Returns a tuple
(success, result)
where:
success: (Boolean) True if request submitted successfully
result: Python dict/list if response if valid JSON, else text
of response body.
'''
# Check if the requested method (GET, POST etc) is valid
try:
req = getattr(requests, self.method)
except AttributeError:
return (False, "Invalid method")
# Build the request and submit
try:
r = req(self.address,
data=self.data,
headers=self.headers,
timeout=self.timeout)
# Handle a timeout event
except (socket.timeout, requests.Timeout):
return (False, "Timed out")
# Handle a connection error
except requests.ConnectionError:
return (False, "Connection error")
# Catch anything else that goes wrong
# (it's bad practice to do this!)
except:
return (False, "Unknown error")
# Check if the response is successful
if r.status_code != 200:
return (False, "Response code {}".format(r.status_code))
# See if the response is a JSON object
try:
response = r.json()
# If not, try getting the text
except requests.compat.json.JSONDecodeError:
response = r.text
# Naughty...
except:
response = "Some other error"
finally:
return (True, response)
def run(self):
'''This is the method that's run when the start() method is called.'''
# submit the web request
result = self._sendRequest()
# If we've got a queue object, add the response to the queue
# where it can be read via the get() method in the main thread
if self.q:
self.q.put(result)
# If we've got a callback function, call it.
if self.callback:
self.callback(result)
The webtimeout script has some functionality (Queue) that you may not need. However, if you're going to have lots of background worker threads, Queues can be very useful.
I've put notes on the code to try and explain how it works.
Let me know how you get on.
Edit: you'll need to have the "requests" module installed for this.