-
Notifications
You must be signed in to change notification settings - Fork 0
/
doorbell.py
executable file
·267 lines (234 loc) · 9.53 KB
/
doorbell.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Purpose
Shows how to use the AWS SDK for Python (Boto3) with Amazon Simple Notification
Service (Amazon SNS) to create notification topics, add subscribers, and publish
messages.
"""
import json
import logging
import time
import boto3
from botocore.exceptions import ClientError
import CHIP_IO.GPIO as GPIO
import subprocess
import time
import urllib
logger = logging.getLogger(__name__)
pin = "XIO-P0"
class SnsWrapper:
"""Encapsulates Amazon SNS topic and subscription functions."""
def __init__(self, sns_resource):
"""
:param sns_resource: A Boto3 Amazon SNS resource.
"""
self.sns_resource = sns_resource
def create_topic(self, name):
"""
Creates a notification topic.
:param name: The name of the topic to create.
:return: The newly created topic.
"""
try:
topic = self.sns_resource.create_topic(Name=name)
logger.info("Created topic %s with ARN %s.", name, topic.arn)
except ClientError:
logger.exception("Couldn't create topic %s.", name)
raise
else:
return topic
def list_topics(self):
"""
Lists topics for the current account.
:return: An iterator that yields the topics.
"""
try:
topics_iter = self.sns_resource.topics.all()
logger.info("Got topics.")
except ClientError:
logger.exception("Couldn't get topics.")
raise
else:
return topics_iter
@staticmethod
def delete_topic(topic):
"""
Deletes a topic. All subscriptions to the topic are also deleted.
"""
try:
topic.delete()
logger.info("Deleted topic %s.", topic.arn)
except ClientError:
logger.exception("Couldn't delete topic %s.", topic.arn)
raise
@staticmethod
def subscribe(topic, protocol, endpoint):
"""
Subscribes an endpoint to the topic. Some endpoint types, such as email,
must be confirmed before their subscriptions are active. When a subscription
is not confirmed, its Amazon Resource Number (ARN) is set to
'PendingConfirmation'.
:param topic: The topic to subscribe to.
:param protocol: The protocol of the endpoint, such as 'sms' or 'email'.
:param endpoint: The endpoint that receives messages, such as a phone number
(in E.164 format) for SMS messages, or an email address for
email messages.
:return: The newly added subscription.
"""
try:
subscription = topic.subscribe(
Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True)
logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn)
except ClientError:
logger.exception(
"Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn)
raise
else:
return subscription
def list_subscriptions(self, topic=None):
"""
Lists subscriptions for the current account, optionally limited to a
specific topic.
:param topic: When specified, only subscriptions to this topic are returned.
:return: An iterator that yields the subscriptions.
"""
try:
if topic is None:
subs_iter = self.sns_resource.subscriptions.all()
else:
subs_iter = topic.subscriptions.all()
logger.info("Got subscriptions.")
except ClientError:
logger.exception("Couldn't get subscriptions.")
raise
else:
return subs_iter
@staticmethod
def add_subscription_filter(subscription, attributes):
"""
Adds a filter policy to a subscription. A filter policy is a key and a
list of values that are allowed. When a message is published, it must have an
attribute that passes the filter or it will not be sent to the subscription.
:param subscription: The subscription the filter policy is attached to.
:param attributes: A dictionary of key-value pairs that define the filter.
"""
try:
att_policy = {key: [value] for key, value in attributes.items()}
subscription.set_attributes(
AttributeName='FilterPolicy', AttributeValue=json.dumps(att_policy))
logger.info("Added filter to subscription %s.", subscription.arn)
except ClientError:
logger.exception(
"Couldn't add filter to subscription %s.", subscription.arn)
raise
@staticmethod
def delete_subscription(subscription):
"""
Unsubscribes and deletes a subscription.
"""
try:
subscription.delete()
logger.info("Deleted subscription %s.", subscription.arn)
except ClientError:
logger.exception("Couldn't delete subscription %s.", subscription.arn)
raise
def publish_text_message(self, phone_number, message):
"""
Publishes a text message directly to a phone number without need for a
subscription.
:param phone_number: The phone number that receives the message. This must be
in E.164 format. For example, a United States phone
number might be +12065550101.
:param message: The message to send.
:return: The ID of the message.
"""
try:
response = self.sns_resource.meta.client.publish(
PhoneNumber=phone_number, Message=message)
message_id = response['MessageId']
logger.info("Published message to %s.", phone_number)
except ClientError:
logger.exception("Couldn't publish message to %s.", phone_number)
raise
else:
return message_id
@staticmethod
def publish_message(topic, message, attributes):
"""
Publishes a message, with attributes, to a topic. Subscriptions can be filtered
based on message attributes so that a subscription receives messages only
when specified attributes are present.
:param topic: The topic to publish to.
:param message: The message to publish.
:param attributes: The key-value attributes to attach to the message. Values
must be either `str` or `bytes`.
:return: The ID of the message.
"""
try:
att_dict = {}
for key, value in attributes.items():
if isinstance(value, str):
att_dict[key] = {'DataType': 'String', 'StringValue': value}
elif isinstance(value, bytes):
att_dict[key] = {'DataType': 'Binary', 'BinaryValue': value}
response = topic.publish(Message=message, MessageAttributes=att_dict)
message_id = response['MessageId']
logger.info(
"Published message with attributes %s to topic %s.", attributes,
topic.arn)
except ClientError:
logger.exception("Couldn't publish message to topic %s.", topic.arn)
raise
else:
return message_id
@staticmethod
def publish_multi_message(
topic, subject, default_message, sms_message, email_message):
"""
Publishes a multi-format message to a topic. A multi-format message takes
different forms based on the protocol of the subscriber. For example,
an SMS subscriber might receive a short, text-only version of the message
while an email subscriber could receive an HTML version of the message.
:param topic: The topic to publish to.
:param subject: The subject of the message.
:param default_message: The default version of the message. This version is
sent to subscribers that have protocols that are not
otherwise specified in the structured message.
:param sms_message: The version of the message sent to SMS subscribers.
:param email_message: The version of the message sent to email subscribers.
:return: The ID of the message.
"""
try:
message = {
'default': default_message,
'sms': sms_message,
'email': email_message
}
response = topic.publish(
Message=json.dumps(message), Subject=subject, MessageStructure='json')
message_id = response['MessageId']
logger.info("Published multi-format message to topic %s.", topic.arn)
except ClientError:
logger.exception("Couldn't publish message to topic %s.", topic.arn)
raise
else:
return message_id
def main():
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
GPIO.cleanup(pin)
GPIO.setup(pin, GPIO.IN)
# Add Callback for Both Edges using the add_event_detect() method
GPIO.add_event_detect(pin, GPIO.FALLING, doorbell_handler)
try:
while (not time.sleep(5)):
print("watching " + pin)
except:
GPIO.cleanup(pin)
def doorbell_handler():
sns_wrapper = SnsWrapper(boto3.resource('sns'))
topic = sns_wrapper.create_topic("doorbell")
sns_wrapper.publish_message(
topic, "Ding Dong", {"mobile_key": "friendly"})
if __name__ == '__main__':
main()