1
+ """
2
+ File: chapter02/dweet_button.py
3
+
4
+ A Python program to control an LED using the public dweet.io service
5
+ by using a Button to post a dweet.
6
+
7
+ Dependencies:
8
+ pip3 install gpiozero pigpio requests
9
+
10
+ Built and tested with Python 3.7 on Raspberry Pi 4 Model B
11
+ """
12
+ import signal
13
+ import requests
14
+ import logging
15
+ from gpiozero import Device , Button
16
+ from gpiozero .pins .pigpio import PiGPIOFactory
17
+
18
+ # Initialize Logging
19
+ logging .basicConfig (level = logging .WARNING )
20
+ logger = logging .getLogger ('main' )
21
+ logger .setLevel (logging .INFO )
22
+
23
+ # Initialise GPIOZero
24
+ Device .pin_factory = PiGPIOFactory ()
25
+
26
+ BUTTON_GPIO_PIN = 23
27
+ button = None
28
+ LED_STATES = ['off' , 'on' , 'blink' ]
29
+ current_led_state = 0 # off
30
+
31
+ # Make sure thing_name matches the "dweet_led thing" you want to control.
32
+ thing_name = '**** ADD YOUR THING NAME HERE ****'
33
+ URL = 'https://dweet.io'
34
+
35
+
36
+ def init_button ():
37
+ """Setup button"""
38
+ global button
39
+ button = Button (BUTTON_GPIO_PIN , pull_up = True , bounce_time = 0.1 )
40
+ button .when_pressed = button_pressed
41
+
42
+
43
+ def button_pressed ():
44
+ """Button pressed handler"""
45
+ cycle_led_state ()
46
+
47
+
48
+ def cycle_led_state ():
49
+ """Send revolving dweet to change LED from off -> on -> blink -> off -> ..."""
50
+ global current_led_state
51
+ current_led_state += 1
52
+
53
+ if current_led_state >= len (LED_STATES ):
54
+ current_led_state = 0
55
+
56
+ state = LED_STATES [current_led_state ]
57
+
58
+ logger .info ('Setting LED state %s' , state )
59
+ send_dweet (thing_name , {'state' : state })
60
+
61
+
62
+ def send_dweet (thing_name , values ):
63
+ """Send a dweet to a thing."""
64
+
65
+ resource = URL + '/dweet/for/' + thing_name
66
+ logger .debug ('Dweeting to url %s with values %s' , resource , values )
67
+
68
+ r = requests .get (resource , params = values )
69
+
70
+ if r .status_code == 200 :
71
+ dweet_response = r .json ()
72
+ logger .debug ('Dweet response was %s' , dweet_response )
73
+ return dweet_response
74
+
75
+ else :
76
+ logger .error ('Dweeting dweet failed with http status %s' , r .status_code )
77
+ return {}
78
+
79
+
80
+ # Initialise Module
81
+ init_button ()
82
+
83
+
84
+ # Main entry point
85
+ if __name__ == '__main__' :
86
+ # You could adopt the get_last_dweet() / process_dweet() from dweet_listner.py
87
+ # to initialise the led state in this file. For simplicity we're just
88
+ # starting with 'Off' (current_led_state = 0)
89
+
90
+ print ("Press button to send a dweet to turn LED on, blink or off." )
91
+
92
+ # Stop Python from exiting.
93
+ signal .pause ()
0 commit comments