Skip to content

Instantly share code, notes, and snippets.

@nikotan
Last active January 4, 2019 10:02
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 nikotan/05634b1f6114f14c93e64e9f3238228a to your computer and use it in GitHub Desktop.
Save nikotan/05634b1f6114f14c93e64e9f3238228a to your computer and use it in GitHub Desktop.
Python script for AWS lambda to forward AWS IoT 1-Click event to IFTTT
import json
import os
import urllib.request
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def lambda_handler(event, context):
logger.info('request event: \n' + json.dumps(event))
key = event['placementInfo']['attributes'].get('key')
if key is None:
logger.error('key is not defined.')
return
event_prefix = event['placementInfo']['attributes'].get('event_prefix')
event_suffix = event['placementInfo']['attributes'].get('event_suffix')
if event_prefix is None or event_suffix is None:
logger.error('event is not defined.')
return
else:
event_prefix = replaceValues(event_prefix, event)
event_suffix = replaceValues(event_suffix, event)
eventName = event_prefix + '_' + event_suffix
values = {}
for idx in range(1, 4):
vkey = 'value{}'.format(idx)
value = event['placementInfo']['attributes'].get(vkey)
if value is None:
value = 'None'
else:
value = replaceValues(value, event)
values[vkey] = value
url = 'https://maker.ifttt.com/trigger/' + eventName + '/with/key/' + key
data = json.dumps(values).encode('utf-8')
method = 'POST'
headers = {'Content-Type' : 'application/json'}
req = urllib.request.Request(url, data = data, method = method, headers = headers)
with urllib.request.urlopen(req) as res:
body = res.read().decode('utf-8')
logger.info('response body: \n' + body)
def replaceValues(str, event):
ret_str = str
ret_str = ret_str.replace('$deviceId', event['deviceInfo']['deviceId'])
ret_str = ret_str.replace('$remainingLife', '{:.1f}'.format(event['deviceInfo']['remainingLife']))
ret_str = ret_str.replace('$clickType', event['deviceEvent']['buttonClicked']['clickType'])
ret_str = ret_str.replace('$placementName', event['placementInfo']['placementName'])
return ret_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment