├── README.md ├── flask-web-app ├── flaskapp.py ├── static │ └── js │ │ └── highcharts.js └── templates │ └── index.html ├── lambda-function ├── lambda_function.py ├── requests-2.9.1.dist-info │ ├── DESCRIPTION.rst │ ├── INSTALLER │ ├── METADATA │ ├── RECORD │ ├── WHEEL │ ├── metadata.json │ └── top_level.txt └── requests │ ├── __init__.py │ ├── __init__.pyc │ ├── adapters.py │ ├── adapters.pyc │ ├── api.py │ ├── api.pyc │ ├── auth.py │ ├── auth.pyc │ ├── cacert.pem │ ├── certs.py │ ├── certs.pyc │ ├── compat.py │ ├── compat.pyc │ ├── cookies.py │ ├── cookies.pyc │ ├── exceptions.py │ ├── exceptions.pyc │ ├── hooks.py │ ├── hooks.pyc │ ├── models.py │ ├── models.pyc │ ├── packages │ ├── __init__.py │ ├── __init__.pyc │ ├── chardet │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── big5freq.py │ │ ├── big5freq.pyc │ │ ├── big5prober.py │ │ ├── big5prober.pyc │ │ ├── chardetect.py │ │ ├── chardetect.pyc │ │ ├── chardistribution.py │ │ ├── chardistribution.pyc │ │ ├── charsetgroupprober.py │ │ ├── charsetgroupprober.pyc │ │ ├── charsetprober.py │ │ ├── charsetprober.pyc │ │ ├── codingstatemachine.py │ │ ├── codingstatemachine.pyc │ │ ├── compat.py │ │ ├── compat.pyc │ │ ├── constants.py │ │ ├── constants.pyc │ │ ├── cp949prober.py │ │ ├── cp949prober.pyc │ │ ├── escprober.py │ │ ├── escprober.pyc │ │ ├── escsm.py │ │ ├── escsm.pyc │ │ ├── eucjpprober.py │ │ ├── eucjpprober.pyc │ │ ├── euckrfreq.py │ │ ├── euckrfreq.pyc │ │ ├── euckrprober.py │ │ ├── euckrprober.pyc │ │ ├── euctwfreq.py │ │ ├── euctwfreq.pyc │ │ ├── euctwprober.py │ │ ├── euctwprober.pyc │ │ ├── gb2312freq.py │ │ ├── gb2312freq.pyc │ │ ├── gb2312prober.py │ │ ├── gb2312prober.pyc │ │ ├── hebrewprober.py │ │ ├── hebrewprober.pyc │ │ ├── jisfreq.py │ │ ├── jisfreq.pyc │ │ ├── jpcntx.py │ │ ├── jpcntx.pyc │ │ ├── langbulgarianmodel.py │ │ ├── langbulgarianmodel.pyc │ │ ├── langcyrillicmodel.py │ │ ├── langcyrillicmodel.pyc │ │ ├── langgreekmodel.py │ │ ├── langgreekmodel.pyc │ │ ├── langhebrewmodel.py │ │ ├── langhebrewmodel.pyc │ │ ├── langhungarianmodel.py │ │ ├── langhungarianmodel.pyc │ │ ├── langthaimodel.py │ │ ├── langthaimodel.pyc │ │ ├── latin1prober.py │ │ ├── latin1prober.pyc │ │ ├── mbcharsetprober.py │ │ ├── mbcharsetprober.pyc │ │ ├── mbcsgroupprober.py │ │ ├── mbcsgroupprober.pyc │ │ ├── mbcssm.py │ │ ├── mbcssm.pyc │ │ ├── sbcharsetprober.py │ │ ├── sbcharsetprober.pyc │ │ ├── sbcsgroupprober.py │ │ ├── sbcsgroupprober.pyc │ │ ├── sjisprober.py │ │ ├── sjisprober.pyc │ │ ├── universaldetector.py │ │ ├── universaldetector.pyc │ │ ├── utf8prober.py │ │ └── utf8prober.pyc │ └── urllib3 │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── _collections.py │ │ ├── _collections.pyc │ │ ├── connection.py │ │ ├── connection.pyc │ │ ├── connectionpool.py │ │ ├── connectionpool.pyc │ │ ├── contrib │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── appengine.py │ │ ├── appengine.pyc │ │ ├── ntlmpool.py │ │ ├── ntlmpool.pyc │ │ ├── pyopenssl.py │ │ └── pyopenssl.pyc │ │ ├── exceptions.py │ │ ├── exceptions.pyc │ │ ├── fields.py │ │ ├── fields.pyc │ │ ├── filepost.py │ │ ├── filepost.pyc │ │ ├── packages │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── ordered_dict.py │ │ ├── ordered_dict.pyc │ │ ├── six.py │ │ ├── six.pyc │ │ └── ssl_match_hostname │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── _implementation.py │ │ │ └── _implementation.pyc │ │ ├── poolmanager.py │ │ ├── poolmanager.pyc │ │ ├── request.py │ │ ├── request.pyc │ │ ├── response.py │ │ ├── response.pyc │ │ └── util │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── connection.py │ │ ├── connection.pyc │ │ ├── request.py │ │ ├── request.pyc │ │ ├── response.py │ │ ├── response.pyc │ │ ├── retry.py │ │ ├── retry.pyc │ │ ├── ssl_.py │ │ ├── ssl_.pyc │ │ ├── timeout.py │ │ ├── timeout.pyc │ │ ├── url.py │ │ └── url.pyc │ ├── sessions.py │ ├── sessions.pyc │ ├── status_codes.py │ ├── status_codes.pyc │ ├── structures.py │ ├── structures.pyc │ ├── utils.py │ └── utils.pyc ├── raspberry-pi ├── certs │ └── PLACE KEYS HERE.md ├── fonts │ ├── LCD-N.ttf │ └── Tahoma.ttf ├── images │ ├── aws.bmp │ ├── rfid-logo-0.bmp │ ├── rfid-logo-1.bmp │ └── rfid-logo-2.bmp ├── launcher.sh ├── lib │ ├── comm │ │ ├── __init__.py │ │ ├── communicationServer.py │ │ └── serialCommunicationServer.py │ ├── command │ │ ├── AWSIoTCommand.py │ │ ├── __init__.py │ │ ├── commandConfig.py │ │ ├── commandConnect.py │ │ ├── commandDisconnect.py │ │ ├── commandLockSize.py │ │ ├── commandPublish.py │ │ ├── commandShadowDelete.py │ │ ├── commandShadowGet.py │ │ ├── commandShadowRegisterDeltaCallback.py │ │ ├── commandShadowUnregisterDeltaCallback.py │ │ ├── commandShadowUpdate.py │ │ ├── commandSubscribe.py │ │ ├── commandUnsubscribe.py │ │ └── commandYield.py │ ├── exception │ │ ├── AWSIoTExceptions.py │ │ ├── AWSIoTExceptions.pyc │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── operationError.py │ │ ├── operationError.pyc │ │ ├── operationTimeoutException.py │ │ └── operationTimeoutException.pyc │ ├── protocol │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── mqttCore.py │ │ ├── mqttCore.pyc │ │ └── paho │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── client.py │ │ │ ├── client.pyc │ │ │ └── securedWebsocket │ │ │ ├── __init__.py │ │ │ ├── __init__.pyc │ │ │ ├── securedWebsocketCore.py │ │ │ └── securedWebsocketCore.pyc │ ├── rfid │ │ ├── RFID.py │ │ └── __init__.py │ ├── shadow │ │ ├── __init__.py │ │ ├── deviceShadow.py │ │ └── shadowManager.py │ └── util │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── logManager.py │ │ ├── logManager.pyc │ │ ├── sigV4Core.py │ │ └── sigV4Core.pyc ├── main.py └── runtime │ ├── __init__.py │ ├── run.py │ └── runtimeHub.py └── screenshots ├── flask-website-demo.png ├── hardware-setup.JPG └── materials-used.jpg /flask-web-app/flaskapp.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, jsonify, render_template, make_response, request 2 | from flask_sqlalchemy import SQLAlchemy 3 | from flask_socketio import SocketIO, send, emit 4 | from time import time 5 | from random import random 6 | import json 7 | 8 | # define the flask app 9 | app = Flask(__name__) 10 | 11 | # define the socket.io app 12 | socketio = SocketIO(app) 13 | 14 | # config the database connection 15 | app.config["SQLALCHEMY_DATABASE_URI"] = '' 16 | db = SQLAlchemy(app) 17 | 18 | # define a User model used by sqlalchemy to fetch data from the mysql db 19 | # the database currently holds just one table named 'users'. This table 20 | # has 3 columns - uid, name, and avatar (url to the bmp) 21 | class User(db.Model): 22 | __tablename__ = 'users' 23 | uid = db.Column('uid', db.Integer, primary_key=True) 24 | name = db.Column('name', db.String(50), unique=True) 25 | avatar = db.Column('avatar', db.String(100)) 26 | 27 | def to_json(self): 28 | return { 29 | 'uid' : self.uid, 30 | 'name' : self.name, 31 | 'avatar' : self.avatar 32 | } 33 | 34 | @app.route('/') 35 | def displayLiveChart(): 36 | return render_template('index.html', data='test') 37 | 38 | @app.route('/users/', methods=['GET']) 39 | def fetchAllUsers(): 40 | return jsonify({'users': [s.to_json() for s in User.query.all()]}) 41 | 42 | @app.route('/users/', methods=['GET']) 43 | def fetchUser(uid): 44 | return jsonify({'user': User.query.get(uid).to_json()}) 45 | 46 | @app.route('/racingLogEntry', methods=['POST']) 47 | def postRacingLogEntry(): 48 | socketio.emit('log', request.json, namespace='/chart') 49 | return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 50 | 51 | @app.route('/shutdown', methods=['POST']) 52 | def shutdown(): 53 | shutdown_server() 54 | return 'Server shutting down...' 55 | 56 | def shutdown_server(): 57 | func = request.environ.get('werkzeug.server.shutdown') 58 | if func is None: 59 | raise RuntimeError('Not running with the Werkzeug Server') 60 | func() 61 | 62 | if __name__ == '__main__': 63 | socketio.run(app) 64 | -------------------------------------------------------------------------------- /flask-web-app/static/js/highcharts.js: -------------------------------------------------------------------------------- 1 | var chart; 2 | 3 | $(document).ready(function() { 4 | 5 | // connect to the web socket 6 | var socket = io.connect('http://' + document.domain + ':' + location.port + '/chart', { 7 | 'reconnect': true, 8 | 'reconnection delay': 500, 9 | 'max reconnection attempts': 10 10 | }); 11 | 12 | // event handler for server sent data 13 | // the data is processed and added to the chart series 14 | socket.on('log', function(msg) { 15 | msg = JSON.parse(msg); 16 | var i = 0; 17 | var found = false; 18 | 19 | // convert datetime to local 20 | var utcTime = new Date(Date.parse(msg.createdDateTime)) 21 | var localTime = new Date( utcTime.getTime() - ( utcTime.getTimezoneOffset() * 60000 ) ) 22 | 23 | // search series array to see if it already exists 24 | for (i = 0; i < chart.series.length; i++) { 25 | if (chart.series[i].name == msg.name) { 26 | 27 | // set found to true 28 | found = true; 29 | 30 | // set shift if longer than 20 31 | shift = chart.series[i].data.length > 20; 32 | 33 | // add the point 34 | chart.series[i].addPoint([localTime.getTime(), Number(msg.raceTime.toFixed(4))], true, shift); 35 | } 36 | } 37 | 38 | // add series if it was not previously found 39 | if (found == false) { 40 | chart.addSeries({ 41 | name: msg.name, 42 | data: [[localTime.getTime() , Number(msg.raceTime.toFixed(4))]] 43 | }); 44 | } 45 | 46 | }); 47 | 48 | chart = new Highcharts.Chart({ 49 | chart: { 50 | renderTo: 'data-container', 51 | defaultSeriesType: 'spline' 52 | }, 53 | title: { 54 | text: '100 Meter Dash Records' 55 | }, 56 | xAxis: { 57 | type: 'datetime', 58 | title: { 59 | text: 'Time' 60 | }, 61 | labels: { 62 | formatter: function() { 63 | return Highcharts.dateFormat('%I:%M:%S %p', this.value); 64 | } 65 | } 66 | }, 67 | yAxis: { 68 | title: { 69 | text: 'Completion Time (seconds)' 70 | } 71 | }, 72 | tooltip: { 73 | shared: false, 74 | formatter: function() { 75 | var text = ''; 76 | text = '' + this.series.name + '' + ': ' + Highcharts.numberFormat(this.y, 4) + '(s)' 77 | + '
' + Highcharts.dateFormat('%I:%M:%S %p', this.x) 78 | return text; 79 | } 80 | }, 81 | series: [] 82 | }); 83 | }); -------------------------------------------------------------------------------- /flask-web-app/templates/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Flask Highcharts Live Data Demo 8 | 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 20 | 33 | 34 | 35 |
36 |
37 |
38 |

Live data plotting using Flask, Highcharts and Socket.io

39 |
40 |
41 | 42 |
43 | 44 |
45 | 46 |
47 | 48 |
49 |
50 |
51 | 52 |
53 |

© VJ Ammar 2016

54 |
55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | -------------------------------------------------------------------------------- /lambda-function/lambda_function.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import boto3 3 | import requests 4 | import json 5 | 6 | print('Loading function') 7 | 8 | 9 | def lambda_handler(event, context): 10 | '''Provide an event that contains the following keys: 11 | 12 | - operation: one of the operations in the operations dict below 13 | - tableName: required for operations that interact with DynamoDB 14 | - payload: a parameter to pass to the operation being performed 15 | ''' 16 | print("Received event: " + json.dumps(event, indent=2)) 17 | 18 | # request user data from web api 19 | apiURL = '' 20 | headers = {'Content-Type' : 'application/json'} 21 | r = requests.post(apiURL, json=json.dumps(event), headers=headers, hooks=dict(response=print_response)) 22 | 23 | def print_response(r, *args, **kwargs): 24 | print(r.status_code) 25 | print(r.json()) 26 | -------------------------------------------------------------------------------- /lambda-function/requests-2.9.1.dist-info/INSTALLER: -------------------------------------------------------------------------------- 1 | pip 2 | -------------------------------------------------------------------------------- /lambda-function/requests-2.9.1.dist-info/WHEEL: -------------------------------------------------------------------------------- 1 | Wheel-Version: 1.0 2 | Generator: bdist_wheel (0.26.0) 3 | Root-Is-Purelib: true 4 | Tag: py2-none-any 5 | Tag: py3-none-any 6 | 7 | -------------------------------------------------------------------------------- /lambda-function/requests-2.9.1.dist-info/metadata.json: -------------------------------------------------------------------------------- 1 | {"generator": "bdist_wheel (0.26.0)", "summary": "Python HTTP for Humans.", "classifiers": ["Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5"], "extensions": {"python.details": {"project_urls": {"Home": "http://python-requests.org"}, "contacts": [{"email": "me@kennethreitz.com", "name": "Kenneth Reitz", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}}}, "license": "Apache 2.0", "metadata_version": "2.0", "name": "requests", "extras": ["security"], "run_requires": [{"requires": ["ndg-httpsclient", "pyOpenSSL (>=0.13)", "pyasn1"], "extra": "security"}], "version": "2.9.1"} -------------------------------------------------------------------------------- /lambda-function/requests-2.9.1.dist-info/top_level.txt: -------------------------------------------------------------------------------- 1 | requests 2 | -------------------------------------------------------------------------------- /lambda-function/requests/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # __ 4 | # /__) _ _ _ _ _/ _ 5 | # / ( (- (/ (/ (- _) / _) 6 | # / 7 | 8 | """ 9 | Requests HTTP library 10 | ~~~~~~~~~~~~~~~~~~~~~ 11 | 12 | Requests is an HTTP library, written in Python, for human beings. Basic GET 13 | usage: 14 | 15 | >>> import requests 16 | >>> r = requests.get('https://www.python.org') 17 | >>> r.status_code 18 | 200 19 | >>> 'Python is a programming language' in r.content 20 | True 21 | 22 | ... or POST: 23 | 24 | >>> payload = dict(key1='value1', key2='value2') 25 | >>> r = requests.post('http://httpbin.org/post', data=payload) 26 | >>> print(r.text) 27 | { 28 | ... 29 | "form": { 30 | "key2": "value2", 31 | "key1": "value1" 32 | }, 33 | ... 34 | } 35 | 36 | The other HTTP methods are supported - see `requests.api`. Full documentation 37 | is at . 38 | 39 | :copyright: (c) 2015 by Kenneth Reitz. 40 | :license: Apache 2.0, see LICENSE for more details. 41 | 42 | """ 43 | 44 | __title__ = 'requests' 45 | __version__ = '2.9.1' 46 | __build__ = 0x020901 47 | __author__ = 'Kenneth Reitz' 48 | __license__ = 'Apache 2.0' 49 | __copyright__ = 'Copyright 2015 Kenneth Reitz' 50 | 51 | # Attempt to enable urllib3's SNI support, if possible 52 | try: 53 | from .packages.urllib3.contrib import pyopenssl 54 | pyopenssl.inject_into_urllib3() 55 | except ImportError: 56 | pass 57 | 58 | from . import utils 59 | from .models import Request, Response, PreparedRequest 60 | from .api import request, get, head, post, patch, put, delete, options 61 | from .sessions import session, Session 62 | from .status_codes import codes 63 | from .exceptions import ( 64 | RequestException, Timeout, URLRequired, 65 | TooManyRedirects, HTTPError, ConnectionError, 66 | FileModeWarning, 67 | ) 68 | 69 | # Set default logging handler to avoid "No handler found" warnings. 70 | import logging 71 | try: # Python 2.7+ 72 | from logging import NullHandler 73 | except ImportError: 74 | class NullHandler(logging.Handler): 75 | def emit(self, record): 76 | pass 77 | 78 | logging.getLogger(__name__).addHandler(NullHandler()) 79 | 80 | import warnings 81 | 82 | # FileModeWarnings go off per the default. 83 | warnings.simplefilter('default', FileModeWarning, append=True) 84 | -------------------------------------------------------------------------------- /lambda-function/requests/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/adapters.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/adapters.pyc -------------------------------------------------------------------------------- /lambda-function/requests/api.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.api 5 | ~~~~~~~~~~~~ 6 | 7 | This module implements the Requests API. 8 | 9 | :copyright: (c) 2012 by Kenneth Reitz. 10 | :license: Apache2, see LICENSE for more details. 11 | 12 | """ 13 | 14 | from . import sessions 15 | 16 | 17 | def request(method, url, **kwargs): 18 | """Constructs and sends a :class:`Request `. 19 | 20 | :param method: method for the new :class:`Request` object. 21 | :param url: URL for the new :class:`Request` object. 22 | :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. 23 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 24 | :param json: (optional) json data to send in the body of the :class:`Request`. 25 | :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. 26 | :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. 27 | :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. 28 | :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. 29 | :param timeout: (optional) How long to wait for the server to send data 30 | before giving up, as a float, or a :ref:`(connect timeout, read 31 | timeout) ` tuple. 32 | :type timeout: float or tuple 33 | :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. 34 | :type allow_redirects: bool 35 | :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. 36 | :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. 37 | :param stream: (optional) if ``False``, the response content will be immediately downloaded. 38 | :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. 39 | :return: :class:`Response ` object 40 | :rtype: requests.Response 41 | 42 | Usage:: 43 | 44 | >>> import requests 45 | >>> req = requests.request('GET', 'http://httpbin.org/get') 46 | 47 | """ 48 | 49 | # By using the 'with' statement we are sure the session is closed, thus we 50 | # avoid leaving sockets open which can trigger a ResourceWarning in some 51 | # cases, and look like a memory leak in others. 52 | with sessions.Session() as session: 53 | return session.request(method=method, url=url, **kwargs) 54 | 55 | 56 | def get(url, params=None, **kwargs): 57 | """Sends a GET request. 58 | 59 | :param url: URL for the new :class:`Request` object. 60 | :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. 61 | :param \*\*kwargs: Optional arguments that ``request`` takes. 62 | :return: :class:`Response ` object 63 | :rtype: requests.Response 64 | """ 65 | 66 | kwargs.setdefault('allow_redirects', True) 67 | return request('get', url, params=params, **kwargs) 68 | 69 | 70 | def options(url, **kwargs): 71 | """Sends a OPTIONS request. 72 | 73 | :param url: URL for the new :class:`Request` object. 74 | :param \*\*kwargs: Optional arguments that ``request`` takes. 75 | :return: :class:`Response ` object 76 | :rtype: requests.Response 77 | """ 78 | 79 | kwargs.setdefault('allow_redirects', True) 80 | return request('options', url, **kwargs) 81 | 82 | 83 | def head(url, **kwargs): 84 | """Sends a HEAD request. 85 | 86 | :param url: URL for the new :class:`Request` object. 87 | :param \*\*kwargs: Optional arguments that ``request`` takes. 88 | :return: :class:`Response ` object 89 | :rtype: requests.Response 90 | """ 91 | 92 | kwargs.setdefault('allow_redirects', False) 93 | return request('head', url, **kwargs) 94 | 95 | 96 | def post(url, data=None, json=None, **kwargs): 97 | """Sends a POST request. 98 | 99 | :param url: URL for the new :class:`Request` object. 100 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 101 | :param json: (optional) json data to send in the body of the :class:`Request`. 102 | :param \*\*kwargs: Optional arguments that ``request`` takes. 103 | :return: :class:`Response ` object 104 | :rtype: requests.Response 105 | """ 106 | 107 | return request('post', url, data=data, json=json, **kwargs) 108 | 109 | 110 | def put(url, data=None, **kwargs): 111 | """Sends a PUT request. 112 | 113 | :param url: URL for the new :class:`Request` object. 114 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 115 | :param \*\*kwargs: Optional arguments that ``request`` takes. 116 | :return: :class:`Response ` object 117 | :rtype: requests.Response 118 | """ 119 | 120 | return request('put', url, data=data, **kwargs) 121 | 122 | 123 | def patch(url, data=None, **kwargs): 124 | """Sends a PATCH request. 125 | 126 | :param url: URL for the new :class:`Request` object. 127 | :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. 128 | :param \*\*kwargs: Optional arguments that ``request`` takes. 129 | :return: :class:`Response ` object 130 | :rtype: requests.Response 131 | """ 132 | 133 | return request('patch', url, data=data, **kwargs) 134 | 135 | 136 | def delete(url, **kwargs): 137 | """Sends a DELETE request. 138 | 139 | :param url: URL for the new :class:`Request` object. 140 | :param \*\*kwargs: Optional arguments that ``request`` takes. 141 | :return: :class:`Response ` object 142 | :rtype: requests.Response 143 | """ 144 | 145 | return request('delete', url, **kwargs) 146 | -------------------------------------------------------------------------------- /lambda-function/requests/api.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/api.pyc -------------------------------------------------------------------------------- /lambda-function/requests/auth.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/auth.pyc -------------------------------------------------------------------------------- /lambda-function/requests/certs.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | certs.py 6 | ~~~~~~~~ 7 | 8 | This module returns the preferred default CA certificate bundle. 9 | 10 | If you are packaging Requests, e.g., for a Linux distribution or a managed 11 | environment, you can change the definition of where() to return a separately 12 | packaged CA bundle. 13 | """ 14 | import os.path 15 | 16 | try: 17 | from certifi import where 18 | except ImportError: 19 | def where(): 20 | """Return the preferred certificate bundle.""" 21 | # vendored bundle inside Requests 22 | return os.path.join(os.path.dirname(__file__), 'cacert.pem') 23 | 24 | if __name__ == '__main__': 25 | print(where()) 26 | -------------------------------------------------------------------------------- /lambda-function/requests/certs.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/certs.pyc -------------------------------------------------------------------------------- /lambda-function/requests/compat.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | pythoncompat 5 | """ 6 | 7 | from .packages import chardet 8 | 9 | import sys 10 | 11 | # ------- 12 | # Pythons 13 | # ------- 14 | 15 | # Syntax sugar. 16 | _ver = sys.version_info 17 | 18 | #: Python 2.x? 19 | is_py2 = (_ver[0] == 2) 20 | 21 | #: Python 3.x? 22 | is_py3 = (_ver[0] == 3) 23 | 24 | try: 25 | import simplejson as json 26 | except (ImportError, SyntaxError): 27 | # simplejson does not support Python 3.2, it throws a SyntaxError 28 | # because of u'...' Unicode literals. 29 | import json 30 | 31 | # --------- 32 | # Specifics 33 | # --------- 34 | 35 | if is_py2: 36 | from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass 37 | from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag 38 | from urllib2 import parse_http_list 39 | import cookielib 40 | from Cookie import Morsel 41 | from StringIO import StringIO 42 | from .packages.urllib3.packages.ordered_dict import OrderedDict 43 | 44 | builtin_str = str 45 | bytes = str 46 | str = unicode 47 | basestring = basestring 48 | numeric_types = (int, long, float) 49 | 50 | elif is_py3: 51 | from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag 52 | from urllib.request import parse_http_list, getproxies, proxy_bypass 53 | from http import cookiejar as cookielib 54 | from http.cookies import Morsel 55 | from io import StringIO 56 | from collections import OrderedDict 57 | 58 | builtin_str = str 59 | str = str 60 | bytes = bytes 61 | basestring = (str, bytes) 62 | numeric_types = (int, float) 63 | -------------------------------------------------------------------------------- /lambda-function/requests/compat.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/compat.pyc -------------------------------------------------------------------------------- /lambda-function/requests/cookies.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/cookies.pyc -------------------------------------------------------------------------------- /lambda-function/requests/exceptions.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.exceptions 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | This module contains the set of Requests' exceptions. 8 | 9 | """ 10 | from .packages.urllib3.exceptions import HTTPError as BaseHTTPError 11 | 12 | 13 | class RequestException(IOError): 14 | """There was an ambiguous exception that occurred while handling your 15 | request.""" 16 | 17 | def __init__(self, *args, **kwargs): 18 | """ 19 | Initialize RequestException with `request` and `response` objects. 20 | """ 21 | response = kwargs.pop('response', None) 22 | self.response = response 23 | self.request = kwargs.pop('request', None) 24 | if (response is not None and not self.request and 25 | hasattr(response, 'request')): 26 | self.request = self.response.request 27 | super(RequestException, self).__init__(*args, **kwargs) 28 | 29 | 30 | class HTTPError(RequestException): 31 | """An HTTP error occurred.""" 32 | 33 | 34 | class ConnectionError(RequestException): 35 | """A Connection error occurred.""" 36 | 37 | 38 | class ProxyError(ConnectionError): 39 | """A proxy error occurred.""" 40 | 41 | 42 | class SSLError(ConnectionError): 43 | """An SSL error occurred.""" 44 | 45 | 46 | class Timeout(RequestException): 47 | """The request timed out. 48 | 49 | Catching this error will catch both 50 | :exc:`~requests.exceptions.ConnectTimeout` and 51 | :exc:`~requests.exceptions.ReadTimeout` errors. 52 | """ 53 | 54 | 55 | class ConnectTimeout(ConnectionError, Timeout): 56 | """The request timed out while trying to connect to the remote server. 57 | 58 | Requests that produced this error are safe to retry. 59 | """ 60 | 61 | 62 | class ReadTimeout(Timeout): 63 | """The server did not send any data in the allotted amount of time.""" 64 | 65 | 66 | class URLRequired(RequestException): 67 | """A valid URL is required to make a request.""" 68 | 69 | 70 | class TooManyRedirects(RequestException): 71 | """Too many redirects.""" 72 | 73 | 74 | class MissingSchema(RequestException, ValueError): 75 | """The URL schema (e.g. http or https) is missing.""" 76 | 77 | 78 | class InvalidSchema(RequestException, ValueError): 79 | """See defaults.py for valid schemas.""" 80 | 81 | 82 | class InvalidURL(RequestException, ValueError): 83 | """ The URL provided was somehow invalid. """ 84 | 85 | 86 | class ChunkedEncodingError(RequestException): 87 | """The server declared chunked encoding but sent an invalid chunk.""" 88 | 89 | 90 | class ContentDecodingError(RequestException, BaseHTTPError): 91 | """Failed to decode response content""" 92 | 93 | 94 | class StreamConsumedError(RequestException, TypeError): 95 | """The content for this response was already consumed""" 96 | 97 | 98 | class RetryError(RequestException): 99 | """Custom retries logic failed""" 100 | 101 | 102 | # Warnings 103 | 104 | 105 | class RequestsWarning(Warning): 106 | """Base warning for Requests.""" 107 | pass 108 | 109 | 110 | class FileModeWarning(RequestsWarning, DeprecationWarning): 111 | """ 112 | A file was opened in text mode, but Requests determined its binary length. 113 | """ 114 | pass 115 | -------------------------------------------------------------------------------- /lambda-function/requests/exceptions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/exceptions.pyc -------------------------------------------------------------------------------- /lambda-function/requests/hooks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.hooks 5 | ~~~~~~~~~~~~~~ 6 | 7 | This module provides the capabilities for the Requests hooks system. 8 | 9 | Available hooks: 10 | 11 | ``response``: 12 | The response generated from a Request. 13 | 14 | """ 15 | HOOKS = ['response'] 16 | 17 | def default_hooks(): 18 | return dict((event, []) for event in HOOKS) 19 | 20 | # TODO: response is the only one 21 | 22 | 23 | def dispatch_hook(key, hooks, hook_data, **kwargs): 24 | """Dispatches a hook dictionary on a given piece of data.""" 25 | hooks = hooks or dict() 26 | hooks = hooks.get(key) 27 | if hooks: 28 | if hasattr(hooks, '__call__'): 29 | hooks = [hooks] 30 | for hook in hooks: 31 | _hook_data = hook(hook_data, **kwargs) 32 | if _hook_data is not None: 33 | hook_data = _hook_data 34 | return hook_data 35 | -------------------------------------------------------------------------------- /lambda-function/requests/hooks.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/hooks.pyc -------------------------------------------------------------------------------- /lambda-function/requests/models.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/models.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/__init__.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Debian and other distributions "unbundle" requests' vendored dependencies, and 3 | rewrite all imports to use the global versions of ``urllib3`` and ``chardet``. 4 | The problem with this is that not only requests itself imports those 5 | dependencies, but third-party code outside of the distros' control too. 6 | 7 | In reaction to these problems, the distro maintainers replaced 8 | ``requests.packages`` with a magical "stub module" that imports the correct 9 | modules. The implementations were varying in quality and all had severe 10 | problems. For example, a symlink (or hardlink) that links the correct modules 11 | into place introduces problems regarding object identity, since you now have 12 | two modules in `sys.modules` with the same API, but different identities:: 13 | 14 | requests.packages.urllib3 is not urllib3 15 | 16 | With version ``2.5.2``, requests started to maintain its own stub, so that 17 | distro-specific breakage would be reduced to a minimum, even though the whole 18 | issue is not requests' fault in the first place. See 19 | https://github.com/kennethreitz/requests/pull/2375 for the corresponding pull 20 | request. 21 | ''' 22 | 23 | from __future__ import absolute_import 24 | import sys 25 | 26 | try: 27 | from . import urllib3 28 | except ImportError: 29 | import urllib3 30 | sys.modules['%s.urllib3' % __name__] = urllib3 31 | 32 | try: 33 | from . import chardet 34 | except ImportError: 35 | import chardet 36 | sys.modules['%s.chardet' % __name__] = chardet 37 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/__init__.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # This library is free software; you can redistribute it and/or 3 | # modify it under the terms of the GNU Lesser General Public 4 | # License as published by the Free Software Foundation; either 5 | # version 2.1 of the License, or (at your option) any later version. 6 | # 7 | # This library is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 10 | # Lesser General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU Lesser General Public 13 | # License along with this library; if not, write to the Free Software 14 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 15 | # 02110-1301 USA 16 | ######################### END LICENSE BLOCK ######################### 17 | 18 | __version__ = "2.3.0" 19 | from sys import version_info 20 | 21 | 22 | def detect(aBuf): 23 | if ((version_info < (3, 0) and isinstance(aBuf, unicode)) or 24 | (version_info >= (3, 0) and not isinstance(aBuf, bytes))): 25 | raise ValueError('Expected a bytes object, not a unicode object') 26 | 27 | from . import universaldetector 28 | u = universaldetector.UniversalDetector() 29 | u.reset() 30 | u.feed(aBuf) 31 | u.close() 32 | return u.result 33 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/big5freq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/big5freq.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/big5prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import Big5DistributionAnalysis 31 | from .mbcssm import Big5SMModel 32 | 33 | 34 | class Big5Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(Big5SMModel) 38 | self._mDistributionAnalyzer = Big5DistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "Big5" 43 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/big5prober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/big5prober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/chardetect.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Script which takes one or more file paths and reports on their detected 4 | encodings 5 | 6 | Example:: 7 | 8 | % chardetect somefile someotherfile 9 | somefile: windows-1252 with confidence 0.5 10 | someotherfile: ascii with confidence 1.0 11 | 12 | If no paths are provided, it takes its input from stdin. 13 | 14 | """ 15 | 16 | from __future__ import absolute_import, print_function, unicode_literals 17 | 18 | import argparse 19 | import sys 20 | from io import open 21 | 22 | from chardet import __version__ 23 | from chardet.universaldetector import UniversalDetector 24 | 25 | 26 | def description_of(lines, name='stdin'): 27 | """ 28 | Return a string describing the probable encoding of a file or 29 | list of strings. 30 | 31 | :param lines: The lines to get the encoding of. 32 | :type lines: Iterable of bytes 33 | :param name: Name of file or collection of lines 34 | :type name: str 35 | """ 36 | u = UniversalDetector() 37 | for line in lines: 38 | u.feed(line) 39 | u.close() 40 | result = u.result 41 | if result['encoding']: 42 | return '{0}: {1} with confidence {2}'.format(name, result['encoding'], 43 | result['confidence']) 44 | else: 45 | return '{0}: no result'.format(name) 46 | 47 | 48 | def main(argv=None): 49 | ''' 50 | Handles command line arguments and gets things started. 51 | 52 | :param argv: List of arguments, as if specified on the command-line. 53 | If None, ``sys.argv[1:]`` is used instead. 54 | :type argv: list of str 55 | ''' 56 | # Get command line arguments 57 | parser = argparse.ArgumentParser( 58 | description="Takes one or more file paths and reports their detected \ 59 | encodings", 60 | formatter_class=argparse.ArgumentDefaultsHelpFormatter, 61 | conflict_handler='resolve') 62 | parser.add_argument('input', 63 | help='File whose encoding we would like to determine.', 64 | type=argparse.FileType('rb'), nargs='*', 65 | default=[sys.stdin]) 66 | parser.add_argument('--version', action='version', 67 | version='%(prog)s {0}'.format(__version__)) 68 | args = parser.parse_args(argv) 69 | 70 | for f in args.input: 71 | if f.isatty(): 72 | print("You are running chardetect interactively. Press " + 73 | "CTRL-D twice at the start of a blank line to signal the " + 74 | "end of your input. If you want help, run chardetect " + 75 | "--help\n", file=sys.stderr) 76 | print(description_of(f, f.name)) 77 | 78 | 79 | if __name__ == '__main__': 80 | main() 81 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/chardetect.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/chardetect.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/chardistribution.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/chardistribution.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/charsetgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Communicator client code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | import sys 30 | from .charsetprober import CharSetProber 31 | 32 | 33 | class CharSetGroupProber(CharSetProber): 34 | def __init__(self): 35 | CharSetProber.__init__(self) 36 | self._mActiveNum = 0 37 | self._mProbers = [] 38 | self._mBestGuessProber = None 39 | 40 | def reset(self): 41 | CharSetProber.reset(self) 42 | self._mActiveNum = 0 43 | for prober in self._mProbers: 44 | if prober: 45 | prober.reset() 46 | prober.active = True 47 | self._mActiveNum += 1 48 | self._mBestGuessProber = None 49 | 50 | def get_charset_name(self): 51 | if not self._mBestGuessProber: 52 | self.get_confidence() 53 | if not self._mBestGuessProber: 54 | return None 55 | # self._mBestGuessProber = self._mProbers[0] 56 | return self._mBestGuessProber.get_charset_name() 57 | 58 | def feed(self, aBuf): 59 | for prober in self._mProbers: 60 | if not prober: 61 | continue 62 | if not prober.active: 63 | continue 64 | st = prober.feed(aBuf) 65 | if not st: 66 | continue 67 | if st == constants.eFoundIt: 68 | self._mBestGuessProber = prober 69 | return self.get_state() 70 | elif st == constants.eNotMe: 71 | prober.active = False 72 | self._mActiveNum -= 1 73 | if self._mActiveNum <= 0: 74 | self._mState = constants.eNotMe 75 | return self.get_state() 76 | return self.get_state() 77 | 78 | def get_confidence(self): 79 | st = self.get_state() 80 | if st == constants.eFoundIt: 81 | return 0.99 82 | elif st == constants.eNotMe: 83 | return 0.01 84 | bestConf = 0.0 85 | self._mBestGuessProber = None 86 | for prober in self._mProbers: 87 | if not prober: 88 | continue 89 | if not prober.active: 90 | if constants._debug: 91 | sys.stderr.write(prober.get_charset_name() 92 | + ' not active\n') 93 | continue 94 | cf = prober.get_confidence() 95 | if constants._debug: 96 | sys.stderr.write('%s confidence = %s\n' % 97 | (prober.get_charset_name(), cf)) 98 | if bestConf < cf: 99 | bestConf = cf 100 | self._mBestGuessProber = prober 101 | if not self._mBestGuessProber: 102 | return 0.0 103 | return bestConf 104 | # else: 105 | # self._mBestGuessProber = self._mProbers[0] 106 | # return self._mBestGuessProber.get_confidence() 107 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/charsetgroupprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/charsetgroupprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/charsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from . import constants 30 | import re 31 | 32 | 33 | class CharSetProber: 34 | def __init__(self): 35 | pass 36 | 37 | def reset(self): 38 | self._mState = constants.eDetecting 39 | 40 | def get_charset_name(self): 41 | return None 42 | 43 | def feed(self, aBuf): 44 | pass 45 | 46 | def get_state(self): 47 | return self._mState 48 | 49 | def get_confidence(self): 50 | return 0.0 51 | 52 | def filter_high_bit_only(self, aBuf): 53 | aBuf = re.sub(b'([\x00-\x7F])+', b' ', aBuf) 54 | return aBuf 55 | 56 | def filter_without_english_letters(self, aBuf): 57 | aBuf = re.sub(b'([A-Za-z])+', b' ', aBuf) 58 | return aBuf 59 | 60 | def filter_with_english_letters(self, aBuf): 61 | # TODO 62 | return aBuf 63 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/charsetprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/charsetprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/codingstatemachine.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .constants import eStart 29 | from .compat import wrap_ord 30 | 31 | 32 | class CodingStateMachine: 33 | def __init__(self, sm): 34 | self._mModel = sm 35 | self._mCurrentBytePos = 0 36 | self._mCurrentCharLen = 0 37 | self.reset() 38 | 39 | def reset(self): 40 | self._mCurrentState = eStart 41 | 42 | def next_state(self, c): 43 | # for each byte we get its class 44 | # if it is first byte, we also get byte length 45 | # PY3K: aBuf is a byte stream, so c is an int, not a byte 46 | byteCls = self._mModel['classTable'][wrap_ord(c)] 47 | if self._mCurrentState == eStart: 48 | self._mCurrentBytePos = 0 49 | self._mCurrentCharLen = self._mModel['charLenTable'][byteCls] 50 | # from byte's class and stateTable, we get its next state 51 | curr_state = (self._mCurrentState * self._mModel['classFactor'] 52 | + byteCls) 53 | self._mCurrentState = self._mModel['stateTable'][curr_state] 54 | self._mCurrentBytePos += 1 55 | return self._mCurrentState 56 | 57 | def get_current_charlen(self): 58 | return self._mCurrentCharLen 59 | 60 | def get_coding_state_machine(self): 61 | return self._mModel['name'] 62 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/codingstatemachine.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/codingstatemachine.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/compat.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # Contributor(s): 3 | # Ian Cordasco - port to Python 4 | # 5 | # This library is free software; you can redistribute it and/or 6 | # modify it under the terms of the GNU Lesser General Public 7 | # License as published by the Free Software Foundation; either 8 | # version 2.1 of the License, or (at your option) any later version. 9 | # 10 | # This library is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | # Lesser General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU Lesser General Public 16 | # License along with this library; if not, write to the Free Software 17 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 18 | # 02110-1301 USA 19 | ######################### END LICENSE BLOCK ######################### 20 | 21 | import sys 22 | 23 | 24 | if sys.version_info < (3, 0): 25 | base_str = (str, unicode) 26 | else: 27 | base_str = (bytes, str) 28 | 29 | 30 | def wrap_ord(a): 31 | if sys.version_info < (3, 0) and isinstance(a, base_str): 32 | return ord(a) 33 | else: 34 | return a 35 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/compat.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/compat.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/constants.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | _debug = 0 30 | 31 | eDetecting = 0 32 | eFoundIt = 1 33 | eNotMe = 2 34 | 35 | eStart = 0 36 | eError = 1 37 | eItsMe = 2 38 | 39 | SHORTCUT_THRESHOLD = 0.95 40 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/constants.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/constants.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/cp949prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import CP949SMModel 32 | 33 | 34 | class CP949Prober(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(CP949SMModel) 38 | # NOTE: CP949 is a superset of EUC-KR, so the distribution should be 39 | # not different. 40 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 41 | self.reset() 42 | 43 | def get_charset_name(self): 44 | return "CP949" 45 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/cp949prober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/cp949prober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/escprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | from .escsm import (HZSMModel, ISO2022CNSMModel, ISO2022JPSMModel, 30 | ISO2022KRSMModel) 31 | from .charsetprober import CharSetProber 32 | from .codingstatemachine import CodingStateMachine 33 | from .compat import wrap_ord 34 | 35 | 36 | class EscCharSetProber(CharSetProber): 37 | def __init__(self): 38 | CharSetProber.__init__(self) 39 | self._mCodingSM = [ 40 | CodingStateMachine(HZSMModel), 41 | CodingStateMachine(ISO2022CNSMModel), 42 | CodingStateMachine(ISO2022JPSMModel), 43 | CodingStateMachine(ISO2022KRSMModel) 44 | ] 45 | self.reset() 46 | 47 | def reset(self): 48 | CharSetProber.reset(self) 49 | for codingSM in self._mCodingSM: 50 | if not codingSM: 51 | continue 52 | codingSM.active = True 53 | codingSM.reset() 54 | self._mActiveSM = len(self._mCodingSM) 55 | self._mDetectedCharset = None 56 | 57 | def get_charset_name(self): 58 | return self._mDetectedCharset 59 | 60 | def get_confidence(self): 61 | if self._mDetectedCharset: 62 | return 0.99 63 | else: 64 | return 0.00 65 | 66 | def feed(self, aBuf): 67 | for c in aBuf: 68 | # PY3K: aBuf is a byte array, so c is an int, not a byte 69 | for codingSM in self._mCodingSM: 70 | if not codingSM: 71 | continue 72 | if not codingSM.active: 73 | continue 74 | codingState = codingSM.next_state(wrap_ord(c)) 75 | if codingState == constants.eError: 76 | codingSM.active = False 77 | self._mActiveSM -= 1 78 | if self._mActiveSM <= 0: 79 | self._mState = constants.eNotMe 80 | return self.get_state() 81 | elif codingState == constants.eItsMe: 82 | self._mState = constants.eFoundIt 83 | self._mDetectedCharset = codingSM.get_coding_state_machine() # nopep8 84 | return self.get_state() 85 | 86 | return self.get_state() 87 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/escprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/escprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/escsm.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/escsm.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/eucjpprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from . import constants 30 | from .mbcharsetprober import MultiByteCharSetProber 31 | from .codingstatemachine import CodingStateMachine 32 | from .chardistribution import EUCJPDistributionAnalysis 33 | from .jpcntx import EUCJPContextAnalysis 34 | from .mbcssm import EUCJPSMModel 35 | 36 | 37 | class EUCJPProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(EUCJPSMModel) 41 | self._mDistributionAnalyzer = EUCJPDistributionAnalysis() 42 | self._mContextAnalyzer = EUCJPContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return "EUC-JP" 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mContextAnalyzer.feed(self._mLastChar, charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) 75 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 76 | charLen) 77 | 78 | self._mLastChar[0] = aBuf[aLen - 1] 79 | 80 | if self.get_state() == constants.eDetecting: 81 | if (self._mContextAnalyzer.got_enough_data() and 82 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 83 | self._mState = constants.eFoundIt 84 | 85 | return self.get_state() 86 | 87 | def get_confidence(self): 88 | contxtCf = self._mContextAnalyzer.get_confidence() 89 | distribCf = self._mDistributionAnalyzer.get_confidence() 90 | return max(contxtCf, distribCf) 91 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/eucjpprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/eucjpprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euckrfreq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/euckrfreq.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euckrprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCKRDistributionAnalysis 31 | from .mbcssm import EUCKRSMModel 32 | 33 | 34 | class EUCKRProber(MultiByteCharSetProber): 35 | def __init__(self): 36 | MultiByteCharSetProber.__init__(self) 37 | self._mCodingSM = CodingStateMachine(EUCKRSMModel) 38 | self._mDistributionAnalyzer = EUCKRDistributionAnalysis() 39 | self.reset() 40 | 41 | def get_charset_name(self): 42 | return "EUC-KR" 43 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euckrprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/euckrprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euctwfreq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/euctwfreq.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euctwprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import EUCTWDistributionAnalysis 31 | from .mbcssm import EUCTWSMModel 32 | 33 | class EUCTWProber(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(EUCTWSMModel) 37 | self._mDistributionAnalyzer = EUCTWDistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "EUC-TW" 42 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/euctwprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/euctwprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/gb2312freq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/gb2312freq.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/gb2312prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from .mbcharsetprober import MultiByteCharSetProber 29 | from .codingstatemachine import CodingStateMachine 30 | from .chardistribution import GB2312DistributionAnalysis 31 | from .mbcssm import GB2312SMModel 32 | 33 | class GB2312Prober(MultiByteCharSetProber): 34 | def __init__(self): 35 | MultiByteCharSetProber.__init__(self) 36 | self._mCodingSM = CodingStateMachine(GB2312SMModel) 37 | self._mDistributionAnalyzer = GB2312DistributionAnalysis() 38 | self.reset() 39 | 40 | def get_charset_name(self): 41 | return "GB2312" 42 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/gb2312prober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/gb2312prober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/hebrewprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/hebrewprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/jisfreq.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/jisfreq.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/jpcntx.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/jpcntx.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langbulgarianmodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langbulgarianmodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langcyrillicmodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langcyrillicmodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langgreekmodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langgreekmodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langhebrewmodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langhebrewmodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langhungarianmodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langhungarianmodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/langthaimodel.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/langthaimodel.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/latin1prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from .charsetprober import CharSetProber 30 | from .constants import eNotMe 31 | from .compat import wrap_ord 32 | 33 | FREQ_CAT_NUM = 4 34 | 35 | UDF = 0 # undefined 36 | OTH = 1 # other 37 | ASC = 2 # ascii capital letter 38 | ASS = 3 # ascii small letter 39 | ACV = 4 # accent capital vowel 40 | ACO = 5 # accent capital other 41 | ASV = 6 # accent small vowel 42 | ASO = 7 # accent small other 43 | CLASS_NUM = 8 # total classes 44 | 45 | Latin1_CharToClass = ( 46 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 00 - 07 47 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 08 - 0F 48 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 10 - 17 49 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 18 - 1F 50 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 20 - 27 51 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 28 - 2F 52 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 30 - 37 53 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 38 - 3F 54 | OTH, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 40 - 47 55 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 48 - 4F 56 | ASC, ASC, ASC, ASC, ASC, ASC, ASC, ASC, # 50 - 57 57 | ASC, ASC, ASC, OTH, OTH, OTH, OTH, OTH, # 58 - 5F 58 | OTH, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 60 - 67 59 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 68 - 6F 60 | ASS, ASS, ASS, ASS, ASS, ASS, ASS, ASS, # 70 - 77 61 | ASS, ASS, ASS, OTH, OTH, OTH, OTH, OTH, # 78 - 7F 62 | OTH, UDF, OTH, ASO, OTH, OTH, OTH, OTH, # 80 - 87 63 | OTH, OTH, ACO, OTH, ACO, UDF, ACO, UDF, # 88 - 8F 64 | UDF, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # 90 - 97 65 | OTH, OTH, ASO, OTH, ASO, UDF, ASO, ACO, # 98 - 9F 66 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A0 - A7 67 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # A8 - AF 68 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B0 - B7 69 | OTH, OTH, OTH, OTH, OTH, OTH, OTH, OTH, # B8 - BF 70 | ACV, ACV, ACV, ACV, ACV, ACV, ACO, ACO, # C0 - C7 71 | ACV, ACV, ACV, ACV, ACV, ACV, ACV, ACV, # C8 - CF 72 | ACO, ACO, ACV, ACV, ACV, ACV, ACV, OTH, # D0 - D7 73 | ACV, ACV, ACV, ACV, ACV, ACO, ACO, ACO, # D8 - DF 74 | ASV, ASV, ASV, ASV, ASV, ASV, ASO, ASO, # E0 - E7 75 | ASV, ASV, ASV, ASV, ASV, ASV, ASV, ASV, # E8 - EF 76 | ASO, ASO, ASV, ASV, ASV, ASV, ASV, OTH, # F0 - F7 77 | ASV, ASV, ASV, ASV, ASV, ASO, ASO, ASO, # F8 - FF 78 | ) 79 | 80 | # 0 : illegal 81 | # 1 : very unlikely 82 | # 2 : normal 83 | # 3 : very likely 84 | Latin1ClassModel = ( 85 | # UDF OTH ASC ASS ACV ACO ASV ASO 86 | 0, 0, 0, 0, 0, 0, 0, 0, # UDF 87 | 0, 3, 3, 3, 3, 3, 3, 3, # OTH 88 | 0, 3, 3, 3, 3, 3, 3, 3, # ASC 89 | 0, 3, 3, 3, 1, 1, 3, 3, # ASS 90 | 0, 3, 3, 3, 1, 2, 1, 2, # ACV 91 | 0, 3, 3, 3, 3, 3, 3, 3, # ACO 92 | 0, 3, 1, 3, 1, 1, 1, 3, # ASV 93 | 0, 3, 1, 3, 1, 1, 3, 3, # ASO 94 | ) 95 | 96 | 97 | class Latin1Prober(CharSetProber): 98 | def __init__(self): 99 | CharSetProber.__init__(self) 100 | self.reset() 101 | 102 | def reset(self): 103 | self._mLastCharClass = OTH 104 | self._mFreqCounter = [0] * FREQ_CAT_NUM 105 | CharSetProber.reset(self) 106 | 107 | def get_charset_name(self): 108 | return "windows-1252" 109 | 110 | def feed(self, aBuf): 111 | aBuf = self.filter_with_english_letters(aBuf) 112 | for c in aBuf: 113 | charClass = Latin1_CharToClass[wrap_ord(c)] 114 | freq = Latin1ClassModel[(self._mLastCharClass * CLASS_NUM) 115 | + charClass] 116 | if freq == 0: 117 | self._mState = eNotMe 118 | break 119 | self._mFreqCounter[freq] += 1 120 | self._mLastCharClass = charClass 121 | 122 | return self.get_state() 123 | 124 | def get_confidence(self): 125 | if self.get_state() == eNotMe: 126 | return 0.01 127 | 128 | total = sum(self._mFreqCounter) 129 | if total < 0.01: 130 | confidence = 0.0 131 | else: 132 | confidence = ((self._mFreqCounter[3] - self._mFreqCounter[1] * 20.0) 133 | / total) 134 | if confidence < 0.0: 135 | confidence = 0.0 136 | # lower the confidence of latin1 so that other more accurate 137 | # detector can take priority. 138 | confidence = confidence * 0.73 139 | return confidence 140 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/latin1prober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/latin1prober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/mbcharsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | import sys 31 | from . import constants 32 | from .charsetprober import CharSetProber 33 | 34 | 35 | class MultiByteCharSetProber(CharSetProber): 36 | def __init__(self): 37 | CharSetProber.__init__(self) 38 | self._mDistributionAnalyzer = None 39 | self._mCodingSM = None 40 | self._mLastChar = [0, 0] 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | if self._mCodingSM: 45 | self._mCodingSM.reset() 46 | if self._mDistributionAnalyzer: 47 | self._mDistributionAnalyzer.reset() 48 | self._mLastChar = [0, 0] 49 | 50 | def get_charset_name(self): 51 | pass 52 | 53 | def feed(self, aBuf): 54 | aLen = len(aBuf) 55 | for i in range(0, aLen): 56 | codingState = self._mCodingSM.next_state(aBuf[i]) 57 | if codingState == constants.eError: 58 | if constants._debug: 59 | sys.stderr.write(self.get_charset_name() 60 | + ' prober hit error at byte ' + str(i) 61 | + '\n') 62 | self._mState = constants.eNotMe 63 | break 64 | elif codingState == constants.eItsMe: 65 | self._mState = constants.eFoundIt 66 | break 67 | elif codingState == constants.eStart: 68 | charLen = self._mCodingSM.get_current_charlen() 69 | if i == 0: 70 | self._mLastChar[1] = aBuf[0] 71 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 72 | else: 73 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 74 | charLen) 75 | 76 | self._mLastChar[0] = aBuf[aLen - 1] 77 | 78 | if self.get_state() == constants.eDetecting: 79 | if (self._mDistributionAnalyzer.got_enough_data() and 80 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 81 | self._mState = constants.eFoundIt 82 | 83 | return self.get_state() 84 | 85 | def get_confidence(self): 86 | return self._mDistributionAnalyzer.get_confidence() 87 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/mbcharsetprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/mbcharsetprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/mbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # Proofpoint, Inc. 13 | # 14 | # This library is free software; you can redistribute it and/or 15 | # modify it under the terms of the GNU Lesser General Public 16 | # License as published by the Free Software Foundation; either 17 | # version 2.1 of the License, or (at your option) any later version. 18 | # 19 | # This library is distributed in the hope that it will be useful, 20 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 21 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 22 | # Lesser General Public License for more details. 23 | # 24 | # You should have received a copy of the GNU Lesser General Public 25 | # License along with this library; if not, write to the Free Software 26 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 27 | # 02110-1301 USA 28 | ######################### END LICENSE BLOCK ######################### 29 | 30 | from .charsetgroupprober import CharSetGroupProber 31 | from .utf8prober import UTF8Prober 32 | from .sjisprober import SJISProber 33 | from .eucjpprober import EUCJPProber 34 | from .gb2312prober import GB2312Prober 35 | from .euckrprober import EUCKRProber 36 | from .cp949prober import CP949Prober 37 | from .big5prober import Big5Prober 38 | from .euctwprober import EUCTWProber 39 | 40 | 41 | class MBCSGroupProber(CharSetGroupProber): 42 | def __init__(self): 43 | CharSetGroupProber.__init__(self) 44 | self._mProbers = [ 45 | UTF8Prober(), 46 | SJISProber(), 47 | EUCJPProber(), 48 | GB2312Prober(), 49 | EUCKRProber(), 50 | CP949Prober(), 51 | Big5Prober(), 52 | EUCTWProber() 53 | ] 54 | self.reset() 55 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/mbcsgroupprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/mbcsgroupprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/mbcssm.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/mbcssm.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sbcharsetprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | import sys 30 | from . import constants 31 | from .charsetprober import CharSetProber 32 | from .compat import wrap_ord 33 | 34 | SAMPLE_SIZE = 64 35 | SB_ENOUGH_REL_THRESHOLD = 1024 36 | POSITIVE_SHORTCUT_THRESHOLD = 0.95 37 | NEGATIVE_SHORTCUT_THRESHOLD = 0.05 38 | SYMBOL_CAT_ORDER = 250 39 | NUMBER_OF_SEQ_CAT = 4 40 | POSITIVE_CAT = NUMBER_OF_SEQ_CAT - 1 41 | #NEGATIVE_CAT = 0 42 | 43 | 44 | class SingleByteCharSetProber(CharSetProber): 45 | def __init__(self, model, reversed=False, nameProber=None): 46 | CharSetProber.__init__(self) 47 | self._mModel = model 48 | # TRUE if we need to reverse every pair in the model lookup 49 | self._mReversed = reversed 50 | # Optional auxiliary prober for name decision 51 | self._mNameProber = nameProber 52 | self.reset() 53 | 54 | def reset(self): 55 | CharSetProber.reset(self) 56 | # char order of last character 57 | self._mLastOrder = 255 58 | self._mSeqCounters = [0] * NUMBER_OF_SEQ_CAT 59 | self._mTotalSeqs = 0 60 | self._mTotalChar = 0 61 | # characters that fall in our sampling range 62 | self._mFreqChar = 0 63 | 64 | def get_charset_name(self): 65 | if self._mNameProber: 66 | return self._mNameProber.get_charset_name() 67 | else: 68 | return self._mModel['charsetName'] 69 | 70 | def feed(self, aBuf): 71 | if not self._mModel['keepEnglishLetter']: 72 | aBuf = self.filter_without_english_letters(aBuf) 73 | aLen = len(aBuf) 74 | if not aLen: 75 | return self.get_state() 76 | for c in aBuf: 77 | order = self._mModel['charToOrderMap'][wrap_ord(c)] 78 | if order < SYMBOL_CAT_ORDER: 79 | self._mTotalChar += 1 80 | if order < SAMPLE_SIZE: 81 | self._mFreqChar += 1 82 | if self._mLastOrder < SAMPLE_SIZE: 83 | self._mTotalSeqs += 1 84 | if not self._mReversed: 85 | i = (self._mLastOrder * SAMPLE_SIZE) + order 86 | model = self._mModel['precedenceMatrix'][i] 87 | else: # reverse the order of the letters in the lookup 88 | i = (order * SAMPLE_SIZE) + self._mLastOrder 89 | model = self._mModel['precedenceMatrix'][i] 90 | self._mSeqCounters[model] += 1 91 | self._mLastOrder = order 92 | 93 | if self.get_state() == constants.eDetecting: 94 | if self._mTotalSeqs > SB_ENOUGH_REL_THRESHOLD: 95 | cf = self.get_confidence() 96 | if cf > POSITIVE_SHORTCUT_THRESHOLD: 97 | if constants._debug: 98 | sys.stderr.write('%s confidence = %s, we have a' 99 | 'winner\n' % 100 | (self._mModel['charsetName'], cf)) 101 | self._mState = constants.eFoundIt 102 | elif cf < NEGATIVE_SHORTCUT_THRESHOLD: 103 | if constants._debug: 104 | sys.stderr.write('%s confidence = %s, below negative' 105 | 'shortcut threshhold %s\n' % 106 | (self._mModel['charsetName'], cf, 107 | NEGATIVE_SHORTCUT_THRESHOLD)) 108 | self._mState = constants.eNotMe 109 | 110 | return self.get_state() 111 | 112 | def get_confidence(self): 113 | r = 0.01 114 | if self._mTotalSeqs > 0: 115 | r = ((1.0 * self._mSeqCounters[POSITIVE_CAT]) / self._mTotalSeqs 116 | / self._mModel['mTypicalPositiveRatio']) 117 | r = r * self._mFreqChar / self._mTotalChar 118 | if r >= 1.0: 119 | r = 0.99 120 | return r 121 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sbcharsetprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/sbcharsetprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sbcsgroupprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is Mozilla Universal charset detector code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 2001 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # Shy Shalom - original C code 12 | # 13 | # This library is free software; you can redistribute it and/or 14 | # modify it under the terms of the GNU Lesser General Public 15 | # License as published by the Free Software Foundation; either 16 | # version 2.1 of the License, or (at your option) any later version. 17 | # 18 | # This library is distributed in the hope that it will be useful, 19 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 21 | # Lesser General Public License for more details. 22 | # 23 | # You should have received a copy of the GNU Lesser General Public 24 | # License along with this library; if not, write to the Free Software 25 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 26 | # 02110-1301 USA 27 | ######################### END LICENSE BLOCK ######################### 28 | 29 | from .charsetgroupprober import CharSetGroupProber 30 | from .sbcharsetprober import SingleByteCharSetProber 31 | from .langcyrillicmodel import (Win1251CyrillicModel, Koi8rModel, 32 | Latin5CyrillicModel, MacCyrillicModel, 33 | Ibm866Model, Ibm855Model) 34 | from .langgreekmodel import Latin7GreekModel, Win1253GreekModel 35 | from .langbulgarianmodel import Latin5BulgarianModel, Win1251BulgarianModel 36 | from .langhungarianmodel import Latin2HungarianModel, Win1250HungarianModel 37 | from .langthaimodel import TIS620ThaiModel 38 | from .langhebrewmodel import Win1255HebrewModel 39 | from .hebrewprober import HebrewProber 40 | 41 | 42 | class SBCSGroupProber(CharSetGroupProber): 43 | def __init__(self): 44 | CharSetGroupProber.__init__(self) 45 | self._mProbers = [ 46 | SingleByteCharSetProber(Win1251CyrillicModel), 47 | SingleByteCharSetProber(Koi8rModel), 48 | SingleByteCharSetProber(Latin5CyrillicModel), 49 | SingleByteCharSetProber(MacCyrillicModel), 50 | SingleByteCharSetProber(Ibm866Model), 51 | SingleByteCharSetProber(Ibm855Model), 52 | SingleByteCharSetProber(Latin7GreekModel), 53 | SingleByteCharSetProber(Win1253GreekModel), 54 | SingleByteCharSetProber(Latin5BulgarianModel), 55 | SingleByteCharSetProber(Win1251BulgarianModel), 56 | SingleByteCharSetProber(Latin2HungarianModel), 57 | SingleByteCharSetProber(Win1250HungarianModel), 58 | SingleByteCharSetProber(TIS620ThaiModel), 59 | ] 60 | hebrewProber = HebrewProber() 61 | logicalHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, 62 | False, hebrewProber) 63 | visualHebrewProber = SingleByteCharSetProber(Win1255HebrewModel, True, 64 | hebrewProber) 65 | hebrewProber.set_model_probers(logicalHebrewProber, visualHebrewProber) 66 | self._mProbers.extend([hebrewProber, logicalHebrewProber, 67 | visualHebrewProber]) 68 | 69 | self.reset() 70 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sbcsgroupprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/sbcsgroupprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sjisprober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | import sys 29 | from .mbcharsetprober import MultiByteCharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .chardistribution import SJISDistributionAnalysis 32 | from .jpcntx import SJISContextAnalysis 33 | from .mbcssm import SJISSMModel 34 | from . import constants 35 | 36 | 37 | class SJISProber(MultiByteCharSetProber): 38 | def __init__(self): 39 | MultiByteCharSetProber.__init__(self) 40 | self._mCodingSM = CodingStateMachine(SJISSMModel) 41 | self._mDistributionAnalyzer = SJISDistributionAnalysis() 42 | self._mContextAnalyzer = SJISContextAnalysis() 43 | self.reset() 44 | 45 | def reset(self): 46 | MultiByteCharSetProber.reset(self) 47 | self._mContextAnalyzer.reset() 48 | 49 | def get_charset_name(self): 50 | return self._mContextAnalyzer.get_charset_name() 51 | 52 | def feed(self, aBuf): 53 | aLen = len(aBuf) 54 | for i in range(0, aLen): 55 | codingState = self._mCodingSM.next_state(aBuf[i]) 56 | if codingState == constants.eError: 57 | if constants._debug: 58 | sys.stderr.write(self.get_charset_name() 59 | + ' prober hit error at byte ' + str(i) 60 | + '\n') 61 | self._mState = constants.eNotMe 62 | break 63 | elif codingState == constants.eItsMe: 64 | self._mState = constants.eFoundIt 65 | break 66 | elif codingState == constants.eStart: 67 | charLen = self._mCodingSM.get_current_charlen() 68 | if i == 0: 69 | self._mLastChar[1] = aBuf[0] 70 | self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:], 71 | charLen) 72 | self._mDistributionAnalyzer.feed(self._mLastChar, charLen) 73 | else: 74 | self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3 75 | - charLen], charLen) 76 | self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], 77 | charLen) 78 | 79 | self._mLastChar[0] = aBuf[aLen - 1] 80 | 81 | if self.get_state() == constants.eDetecting: 82 | if (self._mContextAnalyzer.got_enough_data() and 83 | (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): 84 | self._mState = constants.eFoundIt 85 | 86 | return self.get_state() 87 | 88 | def get_confidence(self): 89 | contxtCf = self._mContextAnalyzer.get_confidence() 90 | distribCf = self._mDistributionAnalyzer.get_confidence() 91 | return max(contxtCf, distribCf) 92 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/sjisprober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/sjisprober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/universaldetector.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/universaldetector.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/utf8prober.py: -------------------------------------------------------------------------------- 1 | ######################## BEGIN LICENSE BLOCK ######################## 2 | # The Original Code is mozilla.org code. 3 | # 4 | # The Initial Developer of the Original Code is 5 | # Netscape Communications Corporation. 6 | # Portions created by the Initial Developer are Copyright (C) 1998 7 | # the Initial Developer. All Rights Reserved. 8 | # 9 | # Contributor(s): 10 | # Mark Pilgrim - port to Python 11 | # 12 | # This library is free software; you can redistribute it and/or 13 | # modify it under the terms of the GNU Lesser General Public 14 | # License as published by the Free Software Foundation; either 15 | # version 2.1 of the License, or (at your option) any later version. 16 | # 17 | # This library is distributed in the hope that it will be useful, 18 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 20 | # Lesser General Public License for more details. 21 | # 22 | # You should have received a copy of the GNU Lesser General Public 23 | # License along with this library; if not, write to the Free Software 24 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 25 | # 02110-1301 USA 26 | ######################### END LICENSE BLOCK ######################### 27 | 28 | from . import constants 29 | from .charsetprober import CharSetProber 30 | from .codingstatemachine import CodingStateMachine 31 | from .mbcssm import UTF8SMModel 32 | 33 | ONE_CHAR_PROB = 0.5 34 | 35 | 36 | class UTF8Prober(CharSetProber): 37 | def __init__(self): 38 | CharSetProber.__init__(self) 39 | self._mCodingSM = CodingStateMachine(UTF8SMModel) 40 | self.reset() 41 | 42 | def reset(self): 43 | CharSetProber.reset(self) 44 | self._mCodingSM.reset() 45 | self._mNumOfMBChar = 0 46 | 47 | def get_charset_name(self): 48 | return "utf-8" 49 | 50 | def feed(self, aBuf): 51 | for c in aBuf: 52 | codingState = self._mCodingSM.next_state(c) 53 | if codingState == constants.eError: 54 | self._mState = constants.eNotMe 55 | break 56 | elif codingState == constants.eItsMe: 57 | self._mState = constants.eFoundIt 58 | break 59 | elif codingState == constants.eStart: 60 | if self._mCodingSM.get_current_charlen() >= 2: 61 | self._mNumOfMBChar += 1 62 | 63 | if self.get_state() == constants.eDetecting: 64 | if self.get_confidence() > constants.SHORTCUT_THRESHOLD: 65 | self._mState = constants.eFoundIt 66 | 67 | return self.get_state() 68 | 69 | def get_confidence(self): 70 | unlike = 0.99 71 | if self._mNumOfMBChar < 6: 72 | for i in range(0, self._mNumOfMBChar): 73 | unlike = unlike * ONE_CHAR_PROB 74 | return 1.0 - unlike 75 | else: 76 | return unlike 77 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/chardet/utf8prober.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/chardet/utf8prober.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | urllib3 - Thread-safe connection pooling and re-using. 3 | """ 4 | 5 | from __future__ import absolute_import 6 | import warnings 7 | 8 | from .connectionpool import ( 9 | HTTPConnectionPool, 10 | HTTPSConnectionPool, 11 | connection_from_url 12 | ) 13 | 14 | from . import exceptions 15 | from .filepost import encode_multipart_formdata 16 | from .poolmanager import PoolManager, ProxyManager, proxy_from_url 17 | from .response import HTTPResponse 18 | from .util.request import make_headers 19 | from .util.url import get_host 20 | from .util.timeout import Timeout 21 | from .util.retry import Retry 22 | 23 | 24 | # Set default logging handler to avoid "No handler found" warnings. 25 | import logging 26 | try: # Python 2.7+ 27 | from logging import NullHandler 28 | except ImportError: 29 | class NullHandler(logging.Handler): 30 | def emit(self, record): 31 | pass 32 | 33 | __author__ = 'Andrey Petrov (andrey.petrov@shazow.net)' 34 | __license__ = 'MIT' 35 | __version__ = '1.13.1' 36 | 37 | __all__ = ( 38 | 'HTTPConnectionPool', 39 | 'HTTPSConnectionPool', 40 | 'PoolManager', 41 | 'ProxyManager', 42 | 'HTTPResponse', 43 | 'Retry', 44 | 'Timeout', 45 | 'add_stderr_logger', 46 | 'connection_from_url', 47 | 'disable_warnings', 48 | 'encode_multipart_formdata', 49 | 'get_host', 50 | 'make_headers', 51 | 'proxy_from_url', 52 | ) 53 | 54 | logging.getLogger(__name__).addHandler(NullHandler()) 55 | 56 | 57 | def add_stderr_logger(level=logging.DEBUG): 58 | """ 59 | Helper for quickly adding a StreamHandler to the logger. Useful for 60 | debugging. 61 | 62 | Returns the handler after adding it. 63 | """ 64 | # This method needs to be in this __init__.py to get the __name__ correct 65 | # even if urllib3 is vendored within another package. 66 | logger = logging.getLogger(__name__) 67 | handler = logging.StreamHandler() 68 | handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) 69 | logger.addHandler(handler) 70 | logger.setLevel(level) 71 | logger.debug('Added a stderr logging handler to logger: %s' % __name__) 72 | return handler 73 | 74 | # ... Clean up. 75 | del NullHandler 76 | 77 | 78 | # SecurityWarning's always go off by default. 79 | warnings.simplefilter('always', exceptions.SecurityWarning, append=True) 80 | # SubjectAltNameWarning's should go off once per host 81 | warnings.simplefilter('default', exceptions.SubjectAltNameWarning) 82 | # InsecurePlatformWarning's don't vary between requests, so we keep it default. 83 | warnings.simplefilter('default', exceptions.InsecurePlatformWarning, 84 | append=True) 85 | # SNIMissingWarnings should go off only once. 86 | warnings.simplefilter('default', exceptions.SNIMissingWarning) 87 | 88 | 89 | def disable_warnings(category=exceptions.HTTPWarning): 90 | """ 91 | Helper for quickly disabling all urllib3 warnings. 92 | """ 93 | warnings.simplefilter('ignore', category) 94 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/_collections.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/_collections.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/connection.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/connection.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/connectionpool.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/connectionpool.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/contrib/__init__.py -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/contrib/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/appengine.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/contrib/appengine.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/ntlmpool.py: -------------------------------------------------------------------------------- 1 | """ 2 | NTLM authenticating pool, contributed by erikcederstran 3 | 4 | Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 5 | """ 6 | from __future__ import absolute_import 7 | 8 | try: 9 | from http.client import HTTPSConnection 10 | except ImportError: 11 | from httplib import HTTPSConnection 12 | from logging import getLogger 13 | from ntlm import ntlm 14 | 15 | from urllib3 import HTTPSConnectionPool 16 | 17 | 18 | log = getLogger(__name__) 19 | 20 | 21 | class NTLMConnectionPool(HTTPSConnectionPool): 22 | """ 23 | Implements an NTLM authentication version of an urllib3 connection pool 24 | """ 25 | 26 | scheme = 'https' 27 | 28 | def __init__(self, user, pw, authurl, *args, **kwargs): 29 | """ 30 | authurl is a random URL on the server that is protected by NTLM. 31 | user is the Windows user, probably in the DOMAIN\\username format. 32 | pw is the password for the user. 33 | """ 34 | super(NTLMConnectionPool, self).__init__(*args, **kwargs) 35 | self.authurl = authurl 36 | self.rawuser = user 37 | user_parts = user.split('\\', 1) 38 | self.domain = user_parts[0].upper() 39 | self.user = user_parts[1] 40 | self.pw = pw 41 | 42 | def _new_conn(self): 43 | # Performs the NTLM handshake that secures the connection. The socket 44 | # must be kept open while requests are performed. 45 | self.num_connections += 1 46 | log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' % 47 | (self.num_connections, self.host, self.authurl)) 48 | 49 | headers = {} 50 | headers['Connection'] = 'Keep-Alive' 51 | req_header = 'Authorization' 52 | resp_header = 'www-authenticate' 53 | 54 | conn = HTTPSConnection(host=self.host, port=self.port) 55 | 56 | # Send negotiation message 57 | headers[req_header] = ( 58 | 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) 59 | log.debug('Request headers: %s' % headers) 60 | conn.request('GET', self.authurl, None, headers) 61 | res = conn.getresponse() 62 | reshdr = dict(res.getheaders()) 63 | log.debug('Response status: %s %s' % (res.status, res.reason)) 64 | log.debug('Response headers: %s' % reshdr) 65 | log.debug('Response data: %s [...]' % res.read(100)) 66 | 67 | # Remove the reference to the socket, so that it can not be closed by 68 | # the response object (we want to keep the socket open) 69 | res.fp = None 70 | 71 | # Server should respond with a challenge message 72 | auth_header_values = reshdr[resp_header].split(', ') 73 | auth_header_value = None 74 | for s in auth_header_values: 75 | if s[:5] == 'NTLM ': 76 | auth_header_value = s[5:] 77 | if auth_header_value is None: 78 | raise Exception('Unexpected %s response header: %s' % 79 | (resp_header, reshdr[resp_header])) 80 | 81 | # Send authentication message 82 | ServerChallenge, NegotiateFlags = \ 83 | ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) 84 | auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, 85 | self.user, 86 | self.domain, 87 | self.pw, 88 | NegotiateFlags) 89 | headers[req_header] = 'NTLM %s' % auth_msg 90 | log.debug('Request headers: %s' % headers) 91 | conn.request('GET', self.authurl, None, headers) 92 | res = conn.getresponse() 93 | log.debug('Response status: %s %s' % (res.status, res.reason)) 94 | log.debug('Response headers: %s' % dict(res.getheaders())) 95 | log.debug('Response data: %s [...]' % res.read()[:100]) 96 | if res.status != 200: 97 | if res.status == 401: 98 | raise Exception('Server rejected request: wrong ' 99 | 'username or password') 100 | raise Exception('Wrong server response: %s %s' % 101 | (res.status, res.reason)) 102 | 103 | res.fp = None 104 | log.debug('Connection established') 105 | return conn 106 | 107 | def urlopen(self, method, url, body=None, headers=None, retries=3, 108 | redirect=True, assert_same_host=True): 109 | if headers is None: 110 | headers = {} 111 | headers['Connection'] = 'Keep-Alive' 112 | return super(NTLMConnectionPool, self).urlopen(method, url, body, 113 | headers, retries, 114 | redirect, 115 | assert_same_host) 116 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/ntlmpool.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/contrib/ntlmpool.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/contrib/pyopenssl.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/contrib/pyopenssl.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/exceptions.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | # Base Exceptions 3 | 4 | 5 | class HTTPError(Exception): 6 | "Base exception used by this module." 7 | pass 8 | 9 | 10 | class HTTPWarning(Warning): 11 | "Base warning used by this module." 12 | pass 13 | 14 | 15 | class PoolError(HTTPError): 16 | "Base exception for errors caused within a pool." 17 | def __init__(self, pool, message): 18 | self.pool = pool 19 | HTTPError.__init__(self, "%s: %s" % (pool, message)) 20 | 21 | def __reduce__(self): 22 | # For pickling purposes. 23 | return self.__class__, (None, None) 24 | 25 | 26 | class RequestError(PoolError): 27 | "Base exception for PoolErrors that have associated URLs." 28 | def __init__(self, pool, url, message): 29 | self.url = url 30 | PoolError.__init__(self, pool, message) 31 | 32 | def __reduce__(self): 33 | # For pickling purposes. 34 | return self.__class__, (None, self.url, None) 35 | 36 | 37 | class SSLError(HTTPError): 38 | "Raised when SSL certificate fails in an HTTPS connection." 39 | pass 40 | 41 | 42 | class ProxyError(HTTPError): 43 | "Raised when the connection to a proxy fails." 44 | pass 45 | 46 | 47 | class DecodeError(HTTPError): 48 | "Raised when automatic decoding based on Content-Type fails." 49 | pass 50 | 51 | 52 | class ProtocolError(HTTPError): 53 | "Raised when something unexpected happens mid-request/response." 54 | pass 55 | 56 | 57 | #: Renamed to ProtocolError but aliased for backwards compatibility. 58 | ConnectionError = ProtocolError 59 | 60 | 61 | # Leaf Exceptions 62 | 63 | class MaxRetryError(RequestError): 64 | """Raised when the maximum number of retries is exceeded. 65 | 66 | :param pool: The connection pool 67 | :type pool: :class:`~urllib3.connectionpool.HTTPConnectionPool` 68 | :param string url: The requested Url 69 | :param exceptions.Exception reason: The underlying error 70 | 71 | """ 72 | 73 | def __init__(self, pool, url, reason=None): 74 | self.reason = reason 75 | 76 | message = "Max retries exceeded with url: %s (Caused by %r)" % ( 77 | url, reason) 78 | 79 | RequestError.__init__(self, pool, url, message) 80 | 81 | 82 | class HostChangedError(RequestError): 83 | "Raised when an existing pool gets a request for a foreign host." 84 | 85 | def __init__(self, pool, url, retries=3): 86 | message = "Tried to open a foreign host with url: %s" % url 87 | RequestError.__init__(self, pool, url, message) 88 | self.retries = retries 89 | 90 | 91 | class TimeoutStateError(HTTPError): 92 | """ Raised when passing an invalid state to a timeout """ 93 | pass 94 | 95 | 96 | class TimeoutError(HTTPError): 97 | """ Raised when a socket timeout error occurs. 98 | 99 | Catching this error will catch both :exc:`ReadTimeoutErrors 100 | ` and :exc:`ConnectTimeoutErrors `. 101 | """ 102 | pass 103 | 104 | 105 | class ReadTimeoutError(TimeoutError, RequestError): 106 | "Raised when a socket timeout occurs while receiving data from a server" 107 | pass 108 | 109 | 110 | # This timeout error does not have a URL attached and needs to inherit from the 111 | # base HTTPError 112 | class ConnectTimeoutError(TimeoutError): 113 | "Raised when a socket timeout occurs while connecting to a server" 114 | pass 115 | 116 | 117 | class NewConnectionError(ConnectTimeoutError, PoolError): 118 | "Raised when we fail to establish a new connection. Usually ECONNREFUSED." 119 | pass 120 | 121 | 122 | class EmptyPoolError(PoolError): 123 | "Raised when a pool runs out of connections and no more are allowed." 124 | pass 125 | 126 | 127 | class ClosedPoolError(PoolError): 128 | "Raised when a request enters a pool after the pool has been closed." 129 | pass 130 | 131 | 132 | class LocationValueError(ValueError, HTTPError): 133 | "Raised when there is something wrong with a given URL input." 134 | pass 135 | 136 | 137 | class LocationParseError(LocationValueError): 138 | "Raised when get_host or similar fails to parse the URL input." 139 | 140 | def __init__(self, location): 141 | message = "Failed to parse: %s" % location 142 | HTTPError.__init__(self, message) 143 | 144 | self.location = location 145 | 146 | 147 | class ResponseError(HTTPError): 148 | "Used as a container for an error reason supplied in a MaxRetryError." 149 | GENERIC_ERROR = 'too many error responses' 150 | SPECIFIC_ERROR = 'too many {status_code} error responses' 151 | 152 | 153 | class SecurityWarning(HTTPWarning): 154 | "Warned when perfoming security reducing actions" 155 | pass 156 | 157 | 158 | class SubjectAltNameWarning(SecurityWarning): 159 | "Warned when connecting to a host with a certificate missing a SAN." 160 | pass 161 | 162 | 163 | class InsecureRequestWarning(SecurityWarning): 164 | "Warned when making an unverified HTTPS request." 165 | pass 166 | 167 | 168 | class SystemTimeWarning(SecurityWarning): 169 | "Warned when system time is suspected to be wrong" 170 | pass 171 | 172 | 173 | class InsecurePlatformWarning(SecurityWarning): 174 | "Warned when certain SSL configuration is not available on a platform." 175 | pass 176 | 177 | 178 | class SNIMissingWarning(HTTPWarning): 179 | "Warned when making a HTTPS request without SNI available." 180 | pass 181 | 182 | 183 | class ResponseNotChunked(ProtocolError, ValueError): 184 | "Response needs to be chunked in order to read it as chunks." 185 | pass 186 | 187 | 188 | class ProxySchemeUnknown(AssertionError, ValueError): 189 | "ProxyManager does not support the supplied scheme" 190 | # TODO(t-8ch): Stop inheriting from AssertionError in v2.0. 191 | 192 | def __init__(self, scheme): 193 | message = "Not supported proxy scheme %s" % scheme 194 | super(ProxySchemeUnknown, self).__init__(message) 195 | 196 | 197 | class HeaderParsingError(HTTPError): 198 | "Raised by assert_header_parsing, but we convert it to a log.warning statement." 199 | def __init__(self, defects, unparsed_data): 200 | message = '%s, unparsed data: %r' % (defects or 'Unknown', unparsed_data) 201 | super(HeaderParsingError, self).__init__(message) 202 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/exceptions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/exceptions.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/fields.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/fields.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/filepost.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import codecs 3 | 4 | from uuid import uuid4 5 | from io import BytesIO 6 | 7 | from .packages import six 8 | from .packages.six import b 9 | from .fields import RequestField 10 | 11 | writer = codecs.lookup('utf-8')[3] 12 | 13 | 14 | def choose_boundary(): 15 | """ 16 | Our embarassingly-simple replacement for mimetools.choose_boundary. 17 | """ 18 | return uuid4().hex 19 | 20 | 21 | def iter_field_objects(fields): 22 | """ 23 | Iterate over fields. 24 | 25 | Supports list of (k, v) tuples and dicts, and lists of 26 | :class:`~urllib3.fields.RequestField`. 27 | 28 | """ 29 | if isinstance(fields, dict): 30 | i = six.iteritems(fields) 31 | else: 32 | i = iter(fields) 33 | 34 | for field in i: 35 | if isinstance(field, RequestField): 36 | yield field 37 | else: 38 | yield RequestField.from_tuples(*field) 39 | 40 | 41 | def iter_fields(fields): 42 | """ 43 | .. deprecated:: 1.6 44 | 45 | Iterate over fields. 46 | 47 | The addition of :class:`~urllib3.fields.RequestField` makes this function 48 | obsolete. Instead, use :func:`iter_field_objects`, which returns 49 | :class:`~urllib3.fields.RequestField` objects. 50 | 51 | Supports list of (k, v) tuples and dicts. 52 | """ 53 | if isinstance(fields, dict): 54 | return ((k, v) for k, v in six.iteritems(fields)) 55 | 56 | return ((k, v) for k, v in fields) 57 | 58 | 59 | def encode_multipart_formdata(fields, boundary=None): 60 | """ 61 | Encode a dictionary of ``fields`` using the multipart/form-data MIME format. 62 | 63 | :param fields: 64 | Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). 65 | 66 | :param boundary: 67 | If not specified, then a random boundary will be generated using 68 | :func:`mimetools.choose_boundary`. 69 | """ 70 | body = BytesIO() 71 | if boundary is None: 72 | boundary = choose_boundary() 73 | 74 | for field in iter_field_objects(fields): 75 | body.write(b('--%s\r\n' % (boundary))) 76 | 77 | writer(body).write(field.render_headers()) 78 | data = field.data 79 | 80 | if isinstance(data, int): 81 | data = str(data) # Backwards compatibility 82 | 83 | if isinstance(data, six.text_type): 84 | writer(body).write(data) 85 | else: 86 | body.write(data) 87 | 88 | body.write(b'\r\n') 89 | 90 | body.write(b('--%s--\r\n' % (boundary))) 91 | 92 | content_type = str('multipart/form-data; boundary=%s' % boundary) 93 | 94 | return body.getvalue(), content_type 95 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/filepost.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/filepost.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from . import ssl_match_hostname 4 | 5 | __all__ = ('ssl_match_hostname', ) 6 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/packages/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/ordered_dict.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/packages/ordered_dict.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/six.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/packages/six.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/__init__.py: -------------------------------------------------------------------------------- 1 | try: 2 | # Python 3.2+ 3 | from ssl import CertificateError, match_hostname 4 | except ImportError: 5 | try: 6 | # Backport of the function from a pypi module 7 | from backports.ssl_match_hostname import CertificateError, match_hostname 8 | except ImportError: 9 | # Our vendored copy 10 | from ._implementation import CertificateError, match_hostname 11 | 12 | # Not needed, but documenting what we provide. 13 | __all__ = ('CertificateError', 'match_hostname') 14 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.py: -------------------------------------------------------------------------------- 1 | """The match_hostname() function from Python 3.3.3, essential when using SSL.""" 2 | 3 | # Note: This file is under the PSF license as the code comes from the python 4 | # stdlib. http://docs.python.org/3/license.html 5 | 6 | import re 7 | 8 | __version__ = '3.4.0.2' 9 | 10 | class CertificateError(ValueError): 11 | pass 12 | 13 | 14 | def _dnsname_match(dn, hostname, max_wildcards=1): 15 | """Matching according to RFC 6125, section 6.4.3 16 | 17 | http://tools.ietf.org/html/rfc6125#section-6.4.3 18 | """ 19 | pats = [] 20 | if not dn: 21 | return False 22 | 23 | # Ported from python3-syntax: 24 | # leftmost, *remainder = dn.split(r'.') 25 | parts = dn.split(r'.') 26 | leftmost = parts[0] 27 | remainder = parts[1:] 28 | 29 | wildcards = leftmost.count('*') 30 | if wildcards > max_wildcards: 31 | # Issue #17980: avoid denials of service by refusing more 32 | # than one wildcard per fragment. A survey of established 33 | # policy among SSL implementations showed it to be a 34 | # reasonable choice. 35 | raise CertificateError( 36 | "too many wildcards in certificate DNS name: " + repr(dn)) 37 | 38 | # speed up common case w/o wildcards 39 | if not wildcards: 40 | return dn.lower() == hostname.lower() 41 | 42 | # RFC 6125, section 6.4.3, subitem 1. 43 | # The client SHOULD NOT attempt to match a presented identifier in which 44 | # the wildcard character comprises a label other than the left-most label. 45 | if leftmost == '*': 46 | # When '*' is a fragment by itself, it matches a non-empty dotless 47 | # fragment. 48 | pats.append('[^.]+') 49 | elif leftmost.startswith('xn--') or hostname.startswith('xn--'): 50 | # RFC 6125, section 6.4.3, subitem 3. 51 | # The client SHOULD NOT attempt to match a presented identifier 52 | # where the wildcard character is embedded within an A-label or 53 | # U-label of an internationalized domain name. 54 | pats.append(re.escape(leftmost)) 55 | else: 56 | # Otherwise, '*' matches any dotless string, e.g. www* 57 | pats.append(re.escape(leftmost).replace(r'\*', '[^.]*')) 58 | 59 | # add the remaining fragments, ignore any wildcards 60 | for frag in remainder: 61 | pats.append(re.escape(frag)) 62 | 63 | pat = re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) 64 | return pat.match(hostname) 65 | 66 | 67 | def match_hostname(cert, hostname): 68 | """Verify that *cert* (in decoded format as returned by 69 | SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 70 | rules are followed, but IP addresses are not accepted for *hostname*. 71 | 72 | CertificateError is raised on failure. On success, the function 73 | returns nothing. 74 | """ 75 | if not cert: 76 | raise ValueError("empty or no certificate") 77 | dnsnames = [] 78 | san = cert.get('subjectAltName', ()) 79 | for key, value in san: 80 | if key == 'DNS': 81 | if _dnsname_match(value, hostname): 82 | return 83 | dnsnames.append(value) 84 | if not dnsnames: 85 | # The subject is only checked when there is no dNSName entry 86 | # in subjectAltName 87 | for sub in cert.get('subject', ()): 88 | for key, value in sub: 89 | # XXX according to RFC 2818, the most specific Common Name 90 | # must be used. 91 | if key == 'commonName': 92 | if _dnsname_match(value, hostname): 93 | return 94 | dnsnames.append(value) 95 | if len(dnsnames) > 1: 96 | raise CertificateError("hostname %r " 97 | "doesn't match either of %s" 98 | % (hostname, ', '.join(map(repr, dnsnames)))) 99 | elif len(dnsnames) == 1: 100 | raise CertificateError("hostname %r " 101 | "doesn't match %r" 102 | % (hostname, dnsnames[0])) 103 | else: 104 | raise CertificateError("no appropriate commonName or " 105 | "subjectAltName fields were found") 106 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/packages/ssl_match_hostname/_implementation.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/poolmanager.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/poolmanager.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/request.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/request.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/response.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/response.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | # For backwards compatibility, provide imports that used to be here. 3 | from .connection import is_connection_dropped 4 | from .request import make_headers 5 | from .response import is_fp_closed 6 | from .ssl_ import ( 7 | SSLContext, 8 | HAS_SNI, 9 | assert_fingerprint, 10 | resolve_cert_reqs, 11 | resolve_ssl_version, 12 | ssl_wrap_socket, 13 | ) 14 | from .timeout import ( 15 | current_time, 16 | Timeout, 17 | ) 18 | 19 | from .retry import Retry 20 | from .url import ( 21 | get_host, 22 | parse_url, 23 | split_first, 24 | Url, 25 | ) 26 | 27 | __all__ = ( 28 | 'HAS_SNI', 29 | 'SSLContext', 30 | 'Retry', 31 | 'Timeout', 32 | 'Url', 33 | 'assert_fingerprint', 34 | 'current_time', 35 | 'is_connection_dropped', 36 | 'is_fp_closed', 37 | 'get_host', 38 | 'parse_url', 39 | 'make_headers', 40 | 'resolve_cert_reqs', 41 | 'resolve_ssl_version', 42 | 'split_first', 43 | 'ssl_wrap_socket', 44 | ) 45 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/__init__.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/connection.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import socket 3 | try: 4 | from select import poll, POLLIN 5 | except ImportError: # `poll` doesn't exist on OSX and other platforms 6 | poll = False 7 | try: 8 | from select import select 9 | except ImportError: # `select` doesn't exist on AppEngine. 10 | select = False 11 | 12 | 13 | def is_connection_dropped(conn): # Platform-specific 14 | """ 15 | Returns True if the connection is dropped and should be closed. 16 | 17 | :param conn: 18 | :class:`httplib.HTTPConnection` object. 19 | 20 | Note: For platforms like AppEngine, this will always return ``False`` to 21 | let the platform handle connection recycling transparently for us. 22 | """ 23 | sock = getattr(conn, 'sock', False) 24 | if sock is False: # Platform-specific: AppEngine 25 | return False 26 | if sock is None: # Connection already closed (such as by httplib). 27 | return True 28 | 29 | if not poll: 30 | if not select: # Platform-specific: AppEngine 31 | return False 32 | 33 | try: 34 | return select([sock], [], [], 0.0)[0] 35 | except socket.error: 36 | return True 37 | 38 | # This version is better on platforms that support it. 39 | p = poll() 40 | p.register(sock, POLLIN) 41 | for (fno, ev) in p.poll(0.0): 42 | if fno == sock.fileno(): 43 | # Either data is buffered (bad), or the connection is dropped. 44 | return True 45 | 46 | 47 | # This function is copied from socket.py in the Python 2.7 standard 48 | # library test suite. Added to its signature is only `socket_options`. 49 | def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, 50 | source_address=None, socket_options=None): 51 | """Connect to *address* and return the socket object. 52 | 53 | Convenience function. Connect to *address* (a 2-tuple ``(host, 54 | port)``) and return the socket object. Passing the optional 55 | *timeout* parameter will set the timeout on the socket instance 56 | before attempting to connect. If no *timeout* is supplied, the 57 | global default timeout setting returned by :func:`getdefaulttimeout` 58 | is used. If *source_address* is set it must be a tuple of (host, port) 59 | for the socket to bind as a source address before making the connection. 60 | An host of '' or port 0 tells the OS to use the default. 61 | """ 62 | 63 | host, port = address 64 | if host.startswith('['): 65 | host = host.strip('[]') 66 | err = None 67 | for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): 68 | af, socktype, proto, canonname, sa = res 69 | sock = None 70 | try: 71 | sock = socket.socket(af, socktype, proto) 72 | 73 | # If provided, set socket level options before connecting. 74 | # This is the only addition urllib3 makes to this function. 75 | _set_socket_options(sock, socket_options) 76 | 77 | if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT: 78 | sock.settimeout(timeout) 79 | if source_address: 80 | sock.bind(source_address) 81 | sock.connect(sa) 82 | return sock 83 | 84 | except socket.error as e: 85 | err = e 86 | if sock is not None: 87 | sock.close() 88 | sock = None 89 | 90 | if err is not None: 91 | raise err 92 | 93 | raise socket.error("getaddrinfo returns an empty list") 94 | 95 | 96 | def _set_socket_options(sock, options): 97 | if options is None: 98 | return 99 | 100 | for opt in options: 101 | sock.setsockopt(*opt) 102 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/connection.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/connection.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/request.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from base64 import b64encode 3 | 4 | from ..packages.six import b 5 | 6 | ACCEPT_ENCODING = 'gzip,deflate' 7 | 8 | 9 | def make_headers(keep_alive=None, accept_encoding=None, user_agent=None, 10 | basic_auth=None, proxy_basic_auth=None, disable_cache=None): 11 | """ 12 | Shortcuts for generating request headers. 13 | 14 | :param keep_alive: 15 | If ``True``, adds 'connection: keep-alive' header. 16 | 17 | :param accept_encoding: 18 | Can be a boolean, list, or string. 19 | ``True`` translates to 'gzip,deflate'. 20 | List will get joined by comma. 21 | String will be used as provided. 22 | 23 | :param user_agent: 24 | String representing the user-agent you want, such as 25 | "python-urllib3/0.6" 26 | 27 | :param basic_auth: 28 | Colon-separated username:password string for 'authorization: basic ...' 29 | auth header. 30 | 31 | :param proxy_basic_auth: 32 | Colon-separated username:password string for 'proxy-authorization: basic ...' 33 | auth header. 34 | 35 | :param disable_cache: 36 | If ``True``, adds 'cache-control: no-cache' header. 37 | 38 | Example:: 39 | 40 | >>> make_headers(keep_alive=True, user_agent="Batman/1.0") 41 | {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} 42 | >>> make_headers(accept_encoding=True) 43 | {'accept-encoding': 'gzip,deflate'} 44 | """ 45 | headers = {} 46 | if accept_encoding: 47 | if isinstance(accept_encoding, str): 48 | pass 49 | elif isinstance(accept_encoding, list): 50 | accept_encoding = ','.join(accept_encoding) 51 | else: 52 | accept_encoding = ACCEPT_ENCODING 53 | headers['accept-encoding'] = accept_encoding 54 | 55 | if user_agent: 56 | headers['user-agent'] = user_agent 57 | 58 | if keep_alive: 59 | headers['connection'] = 'keep-alive' 60 | 61 | if basic_auth: 62 | headers['authorization'] = 'Basic ' + \ 63 | b64encode(b(basic_auth)).decode('utf-8') 64 | 65 | if proxy_basic_auth: 66 | headers['proxy-authorization'] = 'Basic ' + \ 67 | b64encode(b(proxy_basic_auth)).decode('utf-8') 68 | 69 | if disable_cache: 70 | headers['cache-control'] = 'no-cache' 71 | 72 | return headers 73 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/request.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/request.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/response.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | from ..packages.six.moves import http_client as httplib 3 | 4 | from ..exceptions import HeaderParsingError 5 | 6 | 7 | def is_fp_closed(obj): 8 | """ 9 | Checks whether a given file-like object is closed. 10 | 11 | :param obj: 12 | The file-like object to check. 13 | """ 14 | 15 | try: 16 | # Check via the official file-like-object way. 17 | return obj.closed 18 | except AttributeError: 19 | pass 20 | 21 | try: 22 | # Check if the object is a container for another file-like object that 23 | # gets released on exhaustion (e.g. HTTPResponse). 24 | return obj.fp is None 25 | except AttributeError: 26 | pass 27 | 28 | raise ValueError("Unable to determine whether fp is closed.") 29 | 30 | 31 | def assert_header_parsing(headers): 32 | """ 33 | Asserts whether all headers have been successfully parsed. 34 | Extracts encountered errors from the result of parsing headers. 35 | 36 | Only works on Python 3. 37 | 38 | :param headers: Headers to verify. 39 | :type headers: `httplib.HTTPMessage`. 40 | 41 | :raises urllib3.exceptions.HeaderParsingError: 42 | If parsing errors are found. 43 | """ 44 | 45 | # This will fail silently if we pass in the wrong kind of parameter. 46 | # To make debugging easier add an explicit check. 47 | if not isinstance(headers, httplib.HTTPMessage): 48 | raise TypeError('expected httplib.Message, got {0}.'.format( 49 | type(headers))) 50 | 51 | defects = getattr(headers, 'defects', None) 52 | get_payload = getattr(headers, 'get_payload', None) 53 | 54 | unparsed_data = None 55 | if get_payload: # Platform-specific: Python 3. 56 | unparsed_data = get_payload() 57 | 58 | if defects or unparsed_data: 59 | raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data) 60 | 61 | 62 | def is_response_to_head(response): 63 | """ 64 | Checks, wether a the request of a response has been a HEAD-request. 65 | Handles the quirks of AppEngine. 66 | 67 | :param conn: 68 | :type conn: :class:`httplib.HTTPResponse` 69 | """ 70 | # FIXME: Can we do this somehow without accessing private httplib _method? 71 | method = response._method 72 | if isinstance(method, int): # Platform-specific: Appengine 73 | return method == 3 74 | return method.upper() == 'HEAD' 75 | -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/response.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/response.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/retry.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/retry.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/ssl_.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/ssl_.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/timeout.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/timeout.pyc -------------------------------------------------------------------------------- /lambda-function/requests/packages/urllib3/util/url.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/packages/urllib3/util/url.pyc -------------------------------------------------------------------------------- /lambda-function/requests/sessions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/sessions.pyc -------------------------------------------------------------------------------- /lambda-function/requests/status_codes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .structures import LookupDict 4 | 5 | _codes = { 6 | 7 | # Informational. 8 | 100: ('continue',), 9 | 101: ('switching_protocols',), 10 | 102: ('processing',), 11 | 103: ('checkpoint',), 12 | 122: ('uri_too_long', 'request_uri_too_long'), 13 | 200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'), 14 | 201: ('created',), 15 | 202: ('accepted',), 16 | 203: ('non_authoritative_info', 'non_authoritative_information'), 17 | 204: ('no_content',), 18 | 205: ('reset_content', 'reset'), 19 | 206: ('partial_content', 'partial'), 20 | 207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'), 21 | 208: ('already_reported',), 22 | 226: ('im_used',), 23 | 24 | # Redirection. 25 | 300: ('multiple_choices',), 26 | 301: ('moved_permanently', 'moved', '\\o-'), 27 | 302: ('found',), 28 | 303: ('see_other', 'other'), 29 | 304: ('not_modified',), 30 | 305: ('use_proxy',), 31 | 306: ('switch_proxy',), 32 | 307: ('temporary_redirect', 'temporary_moved', 'temporary'), 33 | 308: ('permanent_redirect', 34 | 'resume_incomplete', 'resume',), # These 2 to be removed in 3.0 35 | 36 | # Client Error. 37 | 400: ('bad_request', 'bad'), 38 | 401: ('unauthorized',), 39 | 402: ('payment_required', 'payment'), 40 | 403: ('forbidden',), 41 | 404: ('not_found', '-o-'), 42 | 405: ('method_not_allowed', 'not_allowed'), 43 | 406: ('not_acceptable',), 44 | 407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'), 45 | 408: ('request_timeout', 'timeout'), 46 | 409: ('conflict',), 47 | 410: ('gone',), 48 | 411: ('length_required',), 49 | 412: ('precondition_failed', 'precondition'), 50 | 413: ('request_entity_too_large',), 51 | 414: ('request_uri_too_large',), 52 | 415: ('unsupported_media_type', 'unsupported_media', 'media_type'), 53 | 416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'), 54 | 417: ('expectation_failed',), 55 | 418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'), 56 | 422: ('unprocessable_entity', 'unprocessable'), 57 | 423: ('locked',), 58 | 424: ('failed_dependency', 'dependency'), 59 | 425: ('unordered_collection', 'unordered'), 60 | 426: ('upgrade_required', 'upgrade'), 61 | 428: ('precondition_required', 'precondition'), 62 | 429: ('too_many_requests', 'too_many'), 63 | 431: ('header_fields_too_large', 'fields_too_large'), 64 | 444: ('no_response', 'none'), 65 | 449: ('retry_with', 'retry'), 66 | 450: ('blocked_by_windows_parental_controls', 'parental_controls'), 67 | 451: ('unavailable_for_legal_reasons', 'legal_reasons'), 68 | 499: ('client_closed_request',), 69 | 70 | # Server Error. 71 | 500: ('internal_server_error', 'server_error', '/o\\', '✗'), 72 | 501: ('not_implemented',), 73 | 502: ('bad_gateway',), 74 | 503: ('service_unavailable', 'unavailable'), 75 | 504: ('gateway_timeout',), 76 | 505: ('http_version_not_supported', 'http_version'), 77 | 506: ('variant_also_negotiates',), 78 | 507: ('insufficient_storage',), 79 | 509: ('bandwidth_limit_exceeded', 'bandwidth'), 80 | 510: ('not_extended',), 81 | 511: ('network_authentication_required', 'network_auth', 'network_authentication'), 82 | } 83 | 84 | codes = LookupDict(name='status_codes') 85 | 86 | for code, titles in _codes.items(): 87 | for title in titles: 88 | setattr(codes, title, code) 89 | if not title.startswith('\\'): 90 | setattr(codes, title.upper(), code) 91 | -------------------------------------------------------------------------------- /lambda-function/requests/status_codes.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/status_codes.pyc -------------------------------------------------------------------------------- /lambda-function/requests/structures.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | requests.structures 5 | ~~~~~~~~~~~~~~~~~~~ 6 | 7 | Data structures that power Requests. 8 | 9 | """ 10 | 11 | import collections 12 | 13 | 14 | class CaseInsensitiveDict(collections.MutableMapping): 15 | """ 16 | A case-insensitive ``dict``-like object. 17 | 18 | Implements all methods and operations of 19 | ``collections.MutableMapping`` as well as dict's ``copy``. Also 20 | provides ``lower_items``. 21 | 22 | All keys are expected to be strings. The structure remembers the 23 | case of the last key to be set, and ``iter(instance)``, 24 | ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()`` 25 | will contain case-sensitive keys. However, querying and contains 26 | testing is case insensitive:: 27 | 28 | cid = CaseInsensitiveDict() 29 | cid['Accept'] = 'application/json' 30 | cid['aCCEPT'] == 'application/json' # True 31 | list(cid) == ['Accept'] # True 32 | 33 | For example, ``headers['content-encoding']`` will return the 34 | value of a ``'Content-Encoding'`` response header, regardless 35 | of how the header name was originally stored. 36 | 37 | If the constructor, ``.update``, or equality comparison 38 | operations are given keys that have equal ``.lower()``s, the 39 | behavior is undefined. 40 | 41 | """ 42 | def __init__(self, data=None, **kwargs): 43 | self._store = dict() 44 | if data is None: 45 | data = {} 46 | self.update(data, **kwargs) 47 | 48 | def __setitem__(self, key, value): 49 | # Use the lowercased key for lookups, but store the actual 50 | # key alongside the value. 51 | self._store[key.lower()] = (key, value) 52 | 53 | def __getitem__(self, key): 54 | return self._store[key.lower()][1] 55 | 56 | def __delitem__(self, key): 57 | del self._store[key.lower()] 58 | 59 | def __iter__(self): 60 | return (casedkey for casedkey, mappedvalue in self._store.values()) 61 | 62 | def __len__(self): 63 | return len(self._store) 64 | 65 | def lower_items(self): 66 | """Like iteritems(), but with all lowercase keys.""" 67 | return ( 68 | (lowerkey, keyval[1]) 69 | for (lowerkey, keyval) 70 | in self._store.items() 71 | ) 72 | 73 | def __eq__(self, other): 74 | if isinstance(other, collections.Mapping): 75 | other = CaseInsensitiveDict(other) 76 | else: 77 | return NotImplemented 78 | # Compare insensitively 79 | return dict(self.lower_items()) == dict(other.lower_items()) 80 | 81 | # Copy is required 82 | def copy(self): 83 | return CaseInsensitiveDict(self._store.values()) 84 | 85 | def __repr__(self): 86 | return str(dict(self.items())) 87 | 88 | class LookupDict(dict): 89 | """Dictionary lookup object.""" 90 | 91 | def __init__(self, name=None): 92 | self.name = name 93 | super(LookupDict, self).__init__() 94 | 95 | def __repr__(self): 96 | return '' % (self.name) 97 | 98 | def __getitem__(self, key): 99 | # We allow fall-through here, so values default to None 100 | 101 | return self.__dict__.get(key, None) 102 | 103 | def get(self, key, default=None): 104 | return self.__dict__.get(key, default) 105 | -------------------------------------------------------------------------------- /lambda-function/requests/structures.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/structures.pyc -------------------------------------------------------------------------------- /lambda-function/requests/utils.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/lambda-function/requests/utils.pyc -------------------------------------------------------------------------------- /raspberry-pi/certs/PLACE KEYS HERE.md: -------------------------------------------------------------------------------- 1 | #Place your device, private and root keys here!!! -------------------------------------------------------------------------------- /raspberry-pi/fonts/LCD-N.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/fonts/LCD-N.ttf -------------------------------------------------------------------------------- /raspberry-pi/fonts/Tahoma.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/fonts/Tahoma.ttf -------------------------------------------------------------------------------- /raspberry-pi/images/aws.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/images/aws.bmp -------------------------------------------------------------------------------- /raspberry-pi/images/rfid-logo-0.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/images/rfid-logo-0.bmp -------------------------------------------------------------------------------- /raspberry-pi/images/rfid-logo-1.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/images/rfid-logo-1.bmp -------------------------------------------------------------------------------- /raspberry-pi/images/rfid-logo-2.bmp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/images/rfid-logo-2.bmp -------------------------------------------------------------------------------- /raspberry-pi/launcher.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # launcher.sh 3 | # navigate to home directory, then to this direcotry, then execute program 4 | 5 | STATE="error"; 6 | 7 | while [ $STATE = "error" ] 8 | do 9 | #do a ping and check that its not a default message or change to grep for something else 10 | STATE=$(ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error) 11 | 12 | #sleep for 2 seconds and try again 13 | sleep 2 14 | done 15 | 16 | cd / 17 | cd home/pi/aws-iot-python 18 | sudo python main.py -------------------------------------------------------------------------------- /raspberry-pi/lib/comm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/comm/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/comm/communicationServer.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | 19 | # Base class of communicationServer that handles message traffic across a certain type of tunnel (Socket/Serial bridge) 20 | class communicationServer: 21 | def __init__(self): 22 | pass 23 | 24 | # Accept a message from the other side of the tunnel 25 | def accept(self): 26 | pass 27 | 28 | # Other server object writes to the internal buffer of communicationServer 29 | def writeToInternal(self, srcContent): 30 | pass 31 | 32 | # Upon a remote request, communicationServer write whatever is in the internal buffer to the remote client 33 | def writeToExternal(self): 34 | pass 35 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/AWSIoTCommand.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | 19 | class AWSIoTCommand: 20 | _commandProtocolName = None 21 | _parameterList = None 22 | _serialCommServerHandler = None 23 | _desiredNumberOfParameters = 0 24 | _initSuccess = True 25 | 26 | def __init__(self, srcCommandProtocolName="x"): 27 | self._commandProtocolName = srcCommandProtocolName 28 | self._parameterList = [] 29 | 30 | def _validateCommand(self): 31 | if self._parameterList is None: 32 | return False 33 | else: 34 | return len(self._parameterList) == self._desiredNumberOfParameters 35 | 36 | def getCommandProtocolName(self): 37 | return self._commandProtocolName 38 | 39 | def setInitSuccess(self, src): 40 | self._initSuccess = src 41 | 42 | def getInitSuccess(self): 43 | return self._initSuccess 44 | 45 | def execute(self): 46 | pass 47 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/command/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandConfig.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import AWSIoTCommand 19 | 20 | 21 | class commandConfig(AWSIoTCommand.AWSIoTCommand): 22 | # Target API: mqttCore.config(srcHost, srcPort, srcCAFile, srcKey, srcCert) 23 | _mqttCoreHandler = None 24 | 25 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore): 26 | self._commandProtocolName = "g" 27 | self._parameterList = srcParameterList 28 | self._serialCommServerHandler = srcSerialCommuteServer 29 | self._mqttCoreHandler = srcMQTTCore 30 | self._desiredNumberOfParameters = 5 31 | 32 | def _validateCommand(self): 33 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 34 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 35 | 36 | def execute(self): 37 | returnMessage = "G T" 38 | if not self._validateCommand(): 39 | returnMessage = "G1F: " + "No setup." 40 | else: 41 | try: 42 | self._mqttCoreHandler.config(self._parameterList[0], int(self._parameterList[1]), self._parameterList[2], self._parameterList[3], self._parameterList[4]) 43 | except TypeError as e: 44 | returnMessage = "G2F: " + str(e.message) 45 | except Exception as e: 46 | returnMessage = "GFF: " + "Unknown error." 47 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 48 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandConnect.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from ssl import SSLError 22 | from AWSIoTExceptions import connectError 23 | from AWSIoTExceptions import connectTimeoutException 24 | 25 | 26 | class commandConnect(AWSIoTCommand.AWSIoTCommand): 27 | # Target API: mqttCore.connect(keepAliveInterval) 28 | _mqttCoreHandler = None 29 | 30 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore): 31 | self._commandProtocolName = "c" 32 | self._parameterList = srcParameterList 33 | self._serialCommServerHandler = srcSerialCommuteServer 34 | self._mqttCoreHandler = srcMQTTCore 35 | self._desiredNumberOfParameters = 1 36 | 37 | def _validateCommand(self): 38 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 39 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 40 | 41 | def execute(self): 42 | returnMessage = "C T" 43 | if not self._validateCommand(): 44 | returnMessage = "C1F: " + "No setup." 45 | else: 46 | try: 47 | self._mqttCoreHandler.connect(int(self._parameterList[0])) 48 | except TypeError as e: 49 | returnMessage = "C2F: " + str(e.message) 50 | except SSLError as e: 51 | returnMessage = "C3F: " + "Mutual Auth issues." 52 | except connectError as e: 53 | returnMessage = "C4F: " + str(e.message) 54 | except connectTimeoutException as e: 55 | returnMessage = "C5F: " + str(e.message) 56 | except IOError as e: 57 | returnMessage = "C6F: " + "Credentials not found." 58 | except ValueError as e: 59 | returnMessage = "C7F: " + "Key/KeyID not in $ENV." 60 | except Exception as e: 61 | returnMessage = "CFF: " + "Unknown error." 62 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 63 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandDisconnect.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import disconnectError 22 | from AWSIoTExceptions import disconnectTimeoutException 23 | 24 | 25 | class commandDisconnect(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: mqttCore.disconnect() 27 | _mqttCoreHandler = None 28 | 29 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore): 30 | self._commandProtocolName = "d" 31 | self._parameterList = srcParameterList 32 | self._serialCommServerHandler = srcSerialCommuteServer 33 | self._mqttCoreHandler = srcMQTTCore 34 | self._desiredNumberOfParameters = 0 35 | 36 | def _validateCommand(self): 37 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 38 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 39 | 40 | def execute(self): 41 | returnMessage = "D T" 42 | if not self._validateCommand(): 43 | returnMessage = "D1F: " + "No setup." 44 | else: 45 | try: 46 | self._mqttCoreHandler.disconnect() 47 | except disconnectError as e: 48 | returnMessage = "D2F: " + str(e.message) 49 | except disconnectTimeoutException as e: 50 | returnMessage = "D3F: " + str(e.message) 51 | except Exception as e: 52 | returnMessage = "DFF: " + "Unknown error." 53 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 54 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandLockSize.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | 22 | 23 | class commandLockSize(AWSIoTCommand.AWSIoTCommand): 24 | # Target API: None 25 | 26 | def __init__(self, srcParameterList, srcSerialCommuteServer): 27 | self._commandProtocolName = "z" 28 | self._parameterList = srcParameterList 29 | self._serialCommServerHandler = srcSerialCommuteServer 30 | self._desiredNumberOfParameters = 0 31 | 32 | def _validateCommand(self): 33 | ret = self._serialCommServerHandler is not None 34 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 35 | 36 | def execute(self): 37 | returnMessage = "Z T" 38 | if not self._validateCommand(): 39 | returnMessage = "Z F: " + "Invalid information." 40 | else: 41 | try: 42 | self._serialCommServerHandler.updateLockedQueueSize() 43 | except Exception as e: 44 | returnMessage = "Z F: " + "Unknown Error " + str(type(e)) 45 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 46 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandPublish.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import publishError 22 | from AWSIoTExceptions import publishTimeoutException 23 | 24 | 25 | class commandPublish(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: mqttCore.publish(topic, payload, qos, retain) 27 | _mqttCoreHandler = None 28 | 29 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore): 30 | self._commandProtocolName = "p" 31 | self._parameterList = srcParameterList 32 | self._serialCommServerHandler = srcSerialCommuteServer 33 | self._mqttCoreHandler = srcMQTTCore 34 | self._desiredNumberOfParameters = 4 35 | 36 | def _validateCommand(self): 37 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 38 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 39 | 40 | def execute(self): 41 | returnMessage = "P T" 42 | if not self._validateCommand(): 43 | returnMessage = "P1F: " + "No setup." 44 | else: 45 | try: 46 | self._mqttCoreHandler.publish(self._parameterList[0], self._parameterList[1], int(self._parameterList[2]), self._parameterList[3] == '1') 47 | except TypeError as e: 48 | returnMessage = "P2F: " + str(e.message) 49 | except publishError as e: 50 | returnMessage = "P3F: " + str(e.message) 51 | except publishTimeoutException as e: 52 | returnMessage = "P4F: " + str(e.message) 53 | except Exception as e: 54 | returnMessage = "PFF: " + "Unknown error." 55 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 56 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandShadowDelete.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import subscribeError 22 | from AWSIoTExceptions import subscribeTimeoutException 23 | from AWSIoTExceptions import publishError 24 | from AWSIoTExceptions import publishTimeoutException 25 | 26 | 27 | class commandShadowDelete(AWSIoTCommand.AWSIoTCommand): 28 | # Target API: deviceShadow.shadowDelete(srcCallback, srcTimeout) 29 | # Parameters: deviceShadowName, sketchSubscribeSlot, srcTimeout, callback 30 | _shadowRegistrationTable = None 31 | _shadowSubscribeRecord = None 32 | 33 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcShadowRegistrationTable, srcShadowSubscribeRecord): 34 | self._commandProtocolName = "sd" 35 | self._parameterList = srcParameterList 36 | self._serialCommServerHandler = srcSerialCommuteServer 37 | # To get the corresponding registered deviceShadow instance 38 | self._shadowRegistrationTable = srcShadowRegistrationTable 39 | # To get update the sketch slot information 40 | self._shadowSubscribeRecord = srcShadowSubscribeRecord 41 | self._desiredNumberOfParameters = 4 42 | 43 | def _validateCommand(self): 44 | isNumberOfParameterMatched = AWSIoTCommand.AWSIoTCommand._validateCommand(self) 45 | isDataStructureExist = self._shadowRegistrationTable is not None and self._serialCommServerHandler is not None 46 | isDeviceShadowNameRegistered = False 47 | if isNumberOfParameterMatched and isDataStructureExist: 48 | isDeviceShadowNameRegistered = self._shadowRegistrationTable.get(self._parameterList[0]) is not None 49 | return isNumberOfParameterMatched and isDataStructureExist and isDeviceShadowNameRegistered 50 | 51 | def execute(self): 52 | returnMessage = "SD T" 53 | if not self._validateCommand(): 54 | returnMessage = "SD1F: " + "No shadow init." 55 | else: 56 | try: 57 | currentDeviceShadow = self._shadowRegistrationTable.get(self._parameterList[0]) # By this time, currentDeviceShadow should never be None 58 | # Real shadow delete 59 | tokenForThisRequest = currentDeviceShadow.shadowDelete(self._parameterList[3], int(self._parameterList[2])) 60 | # Update sketch subscribe slot number 61 | self._shadowSubscribeRecord[tokenForThisRequest] = int(self._parameterList[1]) 62 | # A waiting will be performed in the callback to wait until the data structure is ready for device shadow name registration 63 | except TypeError as e: 64 | returnMessage = "SD2F: " + str(e.message) 65 | # 2 subscriptions and 1 publish 66 | except subscribeError as e: 67 | returnMessage = "SD3F: " + str(e.message) 68 | except subscribeTimeoutException as e: 69 | returnMessage = "SD4F: " + str(e.message) 70 | except publishError as e: 71 | returnMessage = "SD5F: " + str(e.message) 72 | except publishTimeoutException as e: 73 | returnMessage = "SD6F: " + str(e.message) 74 | except Exception as e: 75 | returnMessage = "SDFF: " + "Unknown error." 76 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 77 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandShadowGet.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import subscribeError 22 | from AWSIoTExceptions import subscribeTimeoutException 23 | from AWSIoTExceptions import publishError 24 | from AWSIoTExceptions import publishTimeoutException 25 | 26 | 27 | class commandShadowGet(AWSIoTCommand.AWSIoTCommand): 28 | # Target API: deviceShadow.shadowGet(srcCallback, srcTimeout) 29 | # Parameters: deviceShadowName, sketchSubscribeSlot, srcTimeout, callback 30 | _shadowRegistrationTable = None 31 | _shadowSubscribeRecord = None 32 | 33 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcShadowRegistrationTable, srcShadowSubscribeRecord): 34 | self._commandProtocolName = "sg" 35 | self._parameterList = srcParameterList 36 | self._serialCommServerHandler = srcSerialCommuteServer 37 | # To get the corresponding registered deviceShadow instance 38 | self._shadowRegistrationTable = srcShadowRegistrationTable 39 | # To get update the sketch slot information 40 | self._shadowSubscribeRecord = srcShadowSubscribeRecord 41 | self._desiredNumberOfParameters = 4 42 | 43 | def _validateCommand(self): 44 | isNumberOfParameterMatched = AWSIoTCommand.AWSIoTCommand._validateCommand(self) 45 | isDataStructureExist = self._shadowRegistrationTable is not None and self._serialCommServerHandler is not None 46 | isDeviceShadowNameRegistered = False 47 | if isNumberOfParameterMatched and isDataStructureExist: 48 | isDeviceShadowNameRegistered = self._shadowRegistrationTable.get(self._parameterList[0]) is not None 49 | return isNumberOfParameterMatched and isDataStructureExist and isDeviceShadowNameRegistered 50 | 51 | def execute(self): 52 | returnMessage = "SG T" 53 | if not self._validateCommand(): 54 | returnMessage = "SG1F: " + "No shadow init." 55 | else: 56 | try: 57 | currentDeviceShadow = self._shadowRegistrationTable.get(self._parameterList[0]) # By this time, currentDeviceShadow should never be None 58 | # Real shadow get 59 | tokenForThisRequest = currentDeviceShadow.shadowGet(self._parameterList[3], int(self._parameterList[2])) 60 | # Update sketch subscribe slot number 61 | self._shadowSubscribeRecord[tokenForThisRequest] = int(self._parameterList[1]) 62 | # A waiting will be performed in the callback to wait until the data structure is ready for device shadow name registration 63 | except TypeError as e: 64 | returnMessage = "SG2F: " + str(e.message) 65 | # 2 subscriptions and 1 publish 66 | except subscribeError as e: 67 | returnMessage = "SG3F: " + str(e.message) 68 | except subscribeTimeoutException as e: 69 | returnMessage = "SG4F: " + str(e.message) 70 | except publishError as e: 71 | returnMessage = "SG5F: " + str(e.message) 72 | except publishTimeoutException as e: 73 | returnMessage = "SG6F: " + str(e.message) 74 | except Exception as e: 75 | returnMessage = "SGFF: " + "Unknown error." 76 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 77 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandShadowRegisterDeltaCallback.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import subscribeError 22 | from AWSIoTExceptions import subscribeTimeoutException 23 | 24 | 25 | class commandShadowRegisterDeltaCallback(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: deviceShadow.shadowRegisterDeltaCallback(srcCallback) 27 | # Parameters: deviceShadowName, sketchSubscribeSlot, callback 28 | _shadowRegistrationTable = None 29 | _shadowSubscribeRecord = None 30 | 31 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcShadowRegistrationTable, srcShadowSubscribeRecord): 32 | self._commandProtocolName = "s_rd" 33 | self._parameterList = srcParameterList 34 | self._serialCommServerHandler = srcSerialCommuteServer 35 | # To get the corresponding registered deviceShadow instance 36 | self._shadowRegistrationTable = srcShadowRegistrationTable 37 | # To get update the sketch slot information 38 | self._shadowSubscribeRecord = srcShadowSubscribeRecord 39 | self._desiredNumberOfParameters = 3 40 | 41 | def _validateCommand(self): 42 | isNumberOfParameterMatched = AWSIoTCommand.AWSIoTCommand._validateCommand(self) 43 | isDataStructureExist = self._shadowRegistrationTable is not None and self._serialCommServerHandler is not None 44 | isDeviceShadowNameRegistered = False 45 | if isNumberOfParameterMatched and isDataStructureExist: 46 | isDeviceShadowNameRegistered = self._shadowRegistrationTable.get(self._parameterList[0]) is not None 47 | return isNumberOfParameterMatched and isDataStructureExist and isDeviceShadowNameRegistered 48 | 49 | def execute(self): 50 | returnMessage = "S_RD T" 51 | if not self._validateCommand(): 52 | returnMessage = "S_RD1F: " + "No shadow init." 53 | else: 54 | try: 55 | currentDeviceShadow = self._shadowRegistrationTable.get(self._parameterList[0]) # By this time, currentDeviceShadow should never be None 56 | # Real shadow register delta callback 57 | currentDeviceShadow.shadowRegisterDeltaCallback(self._parameterList[2]) 58 | # Update sketch subscribe slot number, using deviceShadow name 59 | self._shadowSubscribeRecord[self._parameterList[0]] = int(self._parameterList[1]) 60 | except TypeError as e: 61 | returnMessage = "S_RD2F: " + str(e.message) 62 | # One subscription 63 | except subscribeError as e: 64 | returnMessage = "S_RD3F: " + str(e.message) 65 | except subscribeTimeoutException as e: 66 | returnMessage = "S_RD4F: " + str(e.message) 67 | except Exception as e: 68 | returnMessage = "S_RDFF: " + "Unknown error." 69 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 70 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandShadowUnregisterDeltaCallback.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import unsubscribeError 22 | from AWSIoTExceptions import unsubscribeTimeoutException 23 | 24 | 25 | class commandShadowUnregisterDeltaCallback(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: deviceShadow.shadowUnregisterDeltaCallback() 27 | # Parameters: deviceShadowName 28 | _shadowRegistrationTable = None 29 | _shadowSubscribeRecord = None 30 | 31 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcShadowRegistrationTable, srcShadowSubscribeRecord): 32 | self._commandProtocolName = "s_ud" 33 | self._parameterList = srcParameterList 34 | self._serialCommServerHandler = srcSerialCommuteServer 35 | # To get the corresponding registered deviceShadow instance 36 | self._shadowRegistrationTable = srcShadowRegistrationTable 37 | # To get update the sketch slot information 38 | self._shadowSubscribeRecord = srcShadowSubscribeRecord 39 | self._desiredNumberOfParameters = 1 40 | 41 | def _validateCommand(self): 42 | isNumberOfParameterMatched = AWSIoTCommand.AWSIoTCommand._validateCommand(self) 43 | isDataStructureExist = self._shadowRegistrationTable is not None and self._serialCommServerHandler is not None 44 | isDeviceShadowNameRegistered = False 45 | if isNumberOfParameterMatched and isDataStructureExist: 46 | isDeviceShadowNameRegistered = self._shadowRegistrationTable.get(self._parameterList[0]) is not None 47 | return isNumberOfParameterMatched and isDataStructureExist and isDeviceShadowNameRegistered 48 | 49 | def execute(self): 50 | returnMessage = "S_UD T" 51 | if not self._validateCommand(): 52 | returnMessage = "S_UD1F: " + "No shadow init." 53 | else: 54 | try: 55 | returnMessage = "S_UD " + str(self._shadowSubscribeRecord[self._parameterList[0]]) 56 | currentDeviceShadow = self._shadowRegistrationTable.get(self._parameterList[0]) # By this time, currentDeviceShadow should never be None 57 | # Real shadow unregister delta callback 58 | currentDeviceShadow.shadowUnregisterDeltaCallback() 59 | # Update sketch subscribe slot number, using deviceShadow name 60 | del self._shadowSubscribeRecord[self._parameterList[0]] 61 | except TypeError as e: 62 | returnMessage = "S_UD2F: " + str(e.message) 63 | # One unsubscription 64 | except unsubscribeError as e: 65 | returnMessage = "S_UD3F: " + str(e.message) 66 | except unsubscribeTimeoutException as e: 67 | returnMessage = "S_UD4F: " + str(e.message) 68 | except Exception as e: 69 | returnMessage = "S_UDFF: " + "Unknown error." 70 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 71 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandShadowUpdate.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import subscribeError 22 | from AWSIoTExceptions import subscribeTimeoutException 23 | from AWSIoTExceptions import publishError 24 | from AWSIoTExceptions import publishTimeoutException 25 | 26 | 27 | class commandShadowUpdate(AWSIoTCommand.AWSIoTCommand): 28 | # Target API: deviceShadow.shadowUpdate(srcJSONPayload, srcCallback, srcTimeout) 29 | # Parameters: deviceShadowName, JSONPayload, sketchSubscribeSlot, srcTimeout, callback 30 | _shadowRegistrationTable = None 31 | _shadowSubscribeRecord = None 32 | 33 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcShadowRegistrationTable, srcShadowSubscribeRecord): 34 | self._commandProtocolName = "su" 35 | self._parameterList = srcParameterList 36 | self._serialCommServerHandler = srcSerialCommuteServer 37 | # To get the corresponding registered deviceShadow instance 38 | self._shadowRegistrationTable = srcShadowRegistrationTable 39 | # To get update the sketch slot information 40 | self._shadowSubscribeRecord = srcShadowSubscribeRecord 41 | self._desiredNumberOfParameters = 5 42 | 43 | def _validateCommand(self): 44 | isNumberOfParameterMatched = AWSIoTCommand.AWSIoTCommand._validateCommand(self) 45 | isDataStructureExist = self._shadowRegistrationTable is not None and self._serialCommServerHandler is not None 46 | isDeviceShadowNameRegistered = False 47 | if isNumberOfParameterMatched and isDataStructureExist: 48 | isDeviceShadowNameRegistered = self._shadowRegistrationTable.get(self._parameterList[0]) is not None 49 | return isNumberOfParameterMatched and isDataStructureExist and isDeviceShadowNameRegistered 50 | 51 | def execute(self): 52 | returnMessage = "SU T" 53 | if not self._validateCommand(): 54 | returnMessage = "SU1F: " + "No shadow init." 55 | else: 56 | try: 57 | currentDeviceShadow = self._shadowRegistrationTable.get(self._parameterList[0]) # By this time, currentDeviceShadow should never be None 58 | # Real shadow update 59 | tokenForThisRequest = currentDeviceShadow.shadowUpdate(self._parameterList[1], self._parameterList[4], int(self._parameterList[3])) 60 | # Update sketch subscribe slot number 61 | self._shadowSubscribeRecord[tokenForThisRequest] = int(self._parameterList[2]) 62 | # A waiting will be performed in the callback to wait until the data structure is ready for device shadow name registration 63 | except TypeError as e: 64 | returnMessage = "SU2F: " + str(e.message) 65 | except ValueError as e: 66 | returnMessage = "SU3F: " + "Invalid JSON payload." 67 | # 2 subscriptions and 1 publish 68 | except subscribeError as e: 69 | returnMessage = "SU4F: " + str(e.message) 70 | except subscribeTimeoutException as e: 71 | returnMessage = "SU5F: " + str(e.message) 72 | except publishError as e: 73 | returnMessage = "SU6F: " + str(e.message) 74 | except publishTimeoutException as e: 75 | returnMessage = "SU7F: " + str(e.message) 76 | except Exception as e: 77 | returnMessage = "SUFF: " + "Unknown error." 78 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 79 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandSubscribe.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import subscribeError 22 | from AWSIoTExceptions import subscribeTimeoutException 23 | 24 | 25 | class commandSubscribe(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: mqttCore.subscribe(topic, qos, callback) 27 | # Parameter list: 28 | _mqttCoreHandler = None 29 | _mqttSubscribeUnit = None 30 | _mqttSubscribeTable = None 31 | 32 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore, srcMQTTSubscribeTable): 33 | self._commandProtocolName = "s" 34 | self._parameterList = srcParameterList 35 | self._serialCommServerHandler = srcSerialCommuteServer 36 | self._mqttCoreHandler = srcMQTTCore 37 | self._mqttSubscribeTable = srcMQTTSubscribeTable 38 | self._desiredNumberOfParameters = 4 39 | 40 | def _validateCommand(self): 41 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 42 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 43 | 44 | def execute(self): 45 | returnMessage = "S T" 46 | if not self._validateCommand(): 47 | returnMessage = "S1F: " + "No setup." 48 | else: 49 | try: 50 | # Init the mqttSubscribeUnit 51 | self._mqttSubscribeUnit = self._parameterList[3] 52 | self._mqttSubscribeUnit.setTopicName(self._parameterList[0]) 53 | self._mqttSubscribeUnit.setSketchSlotNumber(int(self._parameterList[2])) 54 | self._mqttSubscribeUnit.setSerialCommunicationServerHub(self._serialCommServerHandler) 55 | # Real subscription 56 | self._mqttCoreHandler.subscribe(self._parameterList[0], int(self._parameterList[1]), self._mqttSubscribeUnit.individualCallback) 57 | # Update mqttSubscribeTable 58 | self._mqttSubscribeTable[self._parameterList[0]] = self._mqttSubscribeUnit 59 | except TypeError as e: 60 | returnMessage = "S2F: " + str(e.message) 61 | except subscribeError as e: 62 | returnMessage = "S3F: " + str(e.message) 63 | except subscribeTimeoutException as e: 64 | returnMessage = "S4F: " + str(e.message) 65 | except Exception as e: 66 | returnMessage = "SFF: " + "Unknown error." 67 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 68 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandUnsubscribe.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | from AWSIoTExceptions import unsubscribeError 22 | from AWSIoTExceptions import unsubscribeTimeoutException 23 | 24 | 25 | class commandUnsubscribe(AWSIoTCommand.AWSIoTCommand): 26 | # Target API: mqttCore.unsubscribe(topic) 27 | _mqttCoreHandler = None 28 | _mqttSubscribeTable = None 29 | 30 | def __init__(self, srcParameterList, srcSerialCommuteServer, srcMQTTCore, srcMQTTSubscribeTable): 31 | self._commandProtocolName = "u" 32 | self._parameterList = srcParameterList 33 | self._serialCommServerHandler = srcSerialCommuteServer 34 | self._mqttCoreHandler = srcMQTTCore 35 | self._mqttSubscribeTable = srcMQTTSubscribeTable 36 | self._desiredNumberOfParameters = 1 37 | 38 | def _validateCommand(self): 39 | ret = self._mqttCoreHandler is not None and self._serialCommServerHandler is not None 40 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 41 | 42 | def execute(self): 43 | returnMessage = "U T" 44 | if not self._validateCommand(): 45 | returnMessage = "U1F: " + "No setup." 46 | else: 47 | try: 48 | thisSubscribeUnit = self._mqttSubscribeTable.get(self._parameterList[0]) 49 | if thisSubscribeUnit is not None: 50 | returnMessage = "U " + str(thisSubscribeUnit.getSketchSlotNumber()) 51 | # Real unsubscription 52 | self._mqttCoreHandler.unsubscribe(self._parameterList[0]) 53 | # Update mqttSubscribeTable 54 | del self._mqttSubscribeTable[self._parameterList[0]] 55 | except KeyError as e: 56 | pass # Ignore unsubscribe to a topic that never been subscribed 57 | except TypeError as e: 58 | returnMessage = "U2F: " + str(e.message) 59 | except unsubscribeError as e: 60 | returnMessage = "U3F: " + str(e.message) 61 | except unsubscribeTimeoutException as e: 62 | returnMessage = "U4F: " + str(e.message) 63 | except Exception as e: 64 | returnMessage = "UFF: " + "Unknown error." 65 | self._serialCommServerHandler.writeToInternalProtocol(returnMessage) 66 | -------------------------------------------------------------------------------- /raspberry-pi/lib/command/commandYield.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import sys 19 | sys.path.append("../lib/exception/") 20 | import AWSIoTCommand 21 | 22 | 23 | class commandYield(AWSIoTCommand.AWSIoTCommand): 24 | # Target API: None 25 | 26 | def __init__(self, srcParameterList, srcSerialCommuteServer): 27 | self._commandProtocolName = "y" 28 | self._parameterList = srcParameterList 29 | self._serialCommServerHandler = srcSerialCommuteServer 30 | self._desiredNumberOfParameters = 0 31 | 32 | def _validateCommand(self): 33 | ret = self._serialCommServerHandler is not None 34 | return ret and AWSIoTCommand.AWSIoTCommand._validateCommand(self) 35 | 36 | # No execute, pass and directly go to writeToExternalYield 37 | -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/AWSIoTExceptions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import operationTimeoutException 19 | import operationError 20 | 21 | 22 | # Serial Exception 23 | class acceptTimeoutException(Exception): 24 | def __init__(self, msg="Accept Timeout"): 25 | self.message = msg 26 | 27 | 28 | # MQTT Operation Timeout Exception 29 | class connectTimeoutException(operationTimeoutException.operationTimeoutException): 30 | def __init__(self, msg="Connect Timeout"): 31 | self.message = msg 32 | 33 | 34 | class disconnectTimeoutException(operationTimeoutException.operationTimeoutException): 35 | def __init__(self, msg="Disconnect Timeout"): 36 | self.message = msg 37 | 38 | 39 | class publishTimeoutException(operationTimeoutException.operationTimeoutException): 40 | def __init__(self, msg="Publish Timeout"): 41 | self.message = msg 42 | 43 | 44 | class subscribeTimeoutException(operationTimeoutException.operationTimeoutException): 45 | def __init__(self, msg="Subscribe Timeout"): 46 | self.message = msg 47 | 48 | 49 | class unsubscribeTimeoutException(operationTimeoutException.operationTimeoutException): 50 | def __init__(self, msg="Unsubscribe Timeout"): 51 | self.message = msg 52 | 53 | 54 | # MQTT Operation Error 55 | class connectError(operationError.operationError): 56 | def __init__(self, errorCode): 57 | self.message = "Connect Error: " + str(errorCode) 58 | 59 | 60 | class disconnectError(operationError.operationError): 61 | def __init__(self, errorCode): 62 | self.message = "Disconnect Error: " + str(errorCode) 63 | 64 | 65 | class publishError(operationError.operationError): 66 | def __init__(self, errorCode): 67 | self.message = "Publish Error: " + str(errorCode) 68 | 69 | 70 | class subscribeError(operationError.operationError): 71 | def __init__(self, errorCode): 72 | self.message = "Subscribe Error: " + str(errorCode) 73 | 74 | 75 | class unsubscribeError(operationError.operationError): 76 | def __init__(self, errorCode): 77 | self.message = "Unsubscribe Error: " + str(errorCode) 78 | 79 | 80 | # Websocket Error 81 | class wssNoKeyInEnvironmentError(operationError.operationError): 82 | def __init__(self): 83 | self.message = "No AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY detected in $ENV." 84 | 85 | 86 | class wssHandShakeError(operationError.operationError): 87 | def __init__(self): 88 | self.message = "Error in WSS handshake." 89 | -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/AWSIoTExceptions.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/exception/AWSIoTExceptions.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/exception/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/exception/__init__.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/operationError.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | 19 | class operationError(Exception): 20 | def __init__(self, msg="Operation Error"): 21 | self.message = msg 22 | -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/operationError.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/exception/operationError.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/operationTimeoutException.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | 19 | class operationTimeoutException(Exception): 20 | def __init__(self, msg="Operation Timeout"): 21 | self.message = msg 22 | -------------------------------------------------------------------------------- /raspberry-pi/lib/exception/operationTimeoutException.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/exception/operationTimeoutException.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/__init__.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/mqttCore.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/mqttCore.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/__init__.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/client.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/client.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/securedWebsocket/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/securedWebsocket/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/securedWebsocket/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/securedWebsocket/__init__.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/protocol/paho/securedWebsocket/securedWebsocketCore.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/protocol/paho/securedWebsocket/securedWebsocketCore.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/rfid/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/rfid/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/shadow/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/shadow/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/shadow/shadowManager.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | 19 | class _shadowAction: 20 | _shadowName = None 21 | _actionName = None 22 | _topicGeneral = None 23 | _topicAccept = None 24 | _topicReject = None 25 | _topicDelta = None 26 | isDelta = False 27 | _actionType = ["get", "update", "delete", "delta"] 28 | 29 | def __init__(self, srcShadowName, srcActionName): 30 | if srcActionName is None or srcActionName not in self._actionType: 31 | raise TypeError("Unsupported shadow action.") 32 | self._shadowName = srcShadowName 33 | self._actionName = srcActionName 34 | self.isDelta = srcActionName == "delta" 35 | if self.isDelta: 36 | self._topicDelta = "$aws/things/" + str(self._shadowName) + "/shadow/update/delta" 37 | else: 38 | self._topicGeneral = "$aws/things/" + str(self._shadowName) + "/shadow/" + str(self._actionName) 39 | self._topicAccept = "$aws/things/" + str(self._shadowName) + "/shadow/" + str(self._actionName) + "/accepted" 40 | self._topicReject = "$aws/things/" + str(self._shadowName) + "/shadow/" + str(self._actionName) + "/rejected" 41 | 42 | def getTopicGeneral(self): 43 | return self._topicGeneral 44 | 45 | def getTopicAccept(self): 46 | return self._topicAccept 47 | 48 | def getTopicReject(self): 49 | return self._topicReject 50 | 51 | def getTopicDelta(self): 52 | return self._topicDelta 53 | 54 | 55 | class shadowManager: 56 | # Tool handler 57 | _mqttCoreHandler = None 58 | # Tool data structure 59 | 60 | def __init__(self, srcMQTTCore): 61 | # Load in mqttCore 62 | if srcMQTTCore is None: 63 | raise TypeError("None type inputs detected.") 64 | self._mqttCoreHandler = srcMQTTCore 65 | 66 | def getClientID(self): 67 | return self._mqttCoreHandler.getClientID() 68 | 69 | def basicShadowPublish(self, srcShadowName, srcShadowAction, srcPayload): 70 | currentShadowAction = _shadowAction(srcShadowName, srcShadowAction) 71 | self._mqttCoreHandler.publish(currentShadowAction.getTopicGeneral(), srcPayload, 0, False) 72 | 73 | def basicShadowSubscribe(self, srcShadowName, srcShadowAction, srcCallback): 74 | currentShadowAction = _shadowAction(srcShadowName, srcShadowAction) 75 | if currentShadowAction.isDelta: 76 | self._mqttCoreHandler.subscribe(currentShadowAction.getTopicDelta(), 0, srcCallback) 77 | else: 78 | self._mqttCoreHandler.subscribe(currentShadowAction.getTopicAccept(), 0, srcCallback) 79 | self._mqttCoreHandler.subscribe(currentShadowAction.getTopicReject(), 0, srcCallback) 80 | 81 | def basicShadowUnsubscribe(self, srcShadowName, srcShadowAction): 82 | currentShadowAction = _shadowAction(srcShadowName, srcShadowAction) 83 | if currentShadowAction.isDelta: 84 | self._mqttCoreHandler.unsubscribe(currentShadowAction.getTopicDelta()) 85 | else: 86 | self._mqttCoreHandler.unsubscribe(currentShadowAction.getTopicAccept()) 87 | self._mqttCoreHandler.unsubscribe(currentShadowAction.getTopicReject()) 88 | -------------------------------------------------------------------------------- /raspberry-pi/lib/util/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/util/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/lib/util/__init__.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/util/__init__.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/util/logManager.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | import threading 19 | import datetime 20 | 21 | 22 | class logManager: 23 | _mutex = threading.Lock() 24 | _directory = None 25 | _fileHandler = None 26 | _fileName = None 27 | _enable = True 28 | _lastTimeStamp = None 29 | _consolePrint = True 30 | _fileOutput = False 31 | 32 | def __init__(self, srcFileName, srcDirectory): 33 | if srcFileName is None or srcDirectory is None: 34 | raise TypeError("None type inputs detected.") 35 | self._fileName = srcFileName + "_" + str(datetime.datetime.now()) + ".log" 36 | self._directory = srcDirectory 37 | 38 | def getFileName(self): 39 | return self._fileName 40 | 41 | def getDirectory(self): 42 | return self._directory 43 | 44 | def getLastTimeStamp(self): 45 | return self._lastTimeStamp 46 | 47 | def enable(self): 48 | self._enable = True 49 | 50 | def disable(self): 51 | self._enable = False 52 | 53 | def enableConsolePrint(self): 54 | self._consolePrint = True 55 | 56 | def disableConsolePrint(self): 57 | self._consolePrint = False 58 | 59 | def enableFileOutput(self): 60 | self._fileOutput = True 61 | 62 | def disableFileOutput(self): 63 | self._fileOutput = False 64 | 65 | def writeLog(self, log): 66 | if(self._enable): 67 | self._mutex.acquire() 68 | self._lastTimeStamp = str(datetime.datetime.now()) 69 | newLog = "[" + self._lastTimeStamp + "] " + log 70 | if(self._fileOutput): 71 | self._fileHandler = open(self._directory + self._fileName, "a+") 72 | self._fileHandler.write(newLog + "\n") 73 | self._fileHandler.close() 74 | if(self._consolePrint): 75 | print newLog 76 | self._mutex.release() 77 | else: 78 | pass 79 | -------------------------------------------------------------------------------- /raspberry-pi/lib/util/logManager.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/util/logManager.pyc -------------------------------------------------------------------------------- /raspberry-pi/lib/util/sigV4Core.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | # This class implements the sigV4 signing process and return the signed URL for connection 19 | 20 | import os 21 | import datetime 22 | import hashlib 23 | import hmac 24 | 25 | 26 | class sigV4Core: 27 | 28 | def _createAmazonDate(self): 29 | amazonDate = [] 30 | currentTime = datetime.datetime.utcnow() 31 | YMDHMS = currentTime.strftime('%Y%m%dT%H%M%SZ') 32 | YMD = YMDHMS[0:YMDHMS.index('T')] 33 | amazonDate.append(YMD) 34 | amazonDate.append(YMDHMS) 35 | return amazonDate 36 | 37 | def _sign(self, key, message): 38 | return hmac.new(key, message.encode('utf-8'), hashlib.sha256).digest() 39 | 40 | def _getSignatureKey(self, key, dateStamp, regionName, serviceName): 41 | kDate = self._sign(('AWS4' + key).encode('utf-8'), dateStamp) 42 | kRegion = self._sign(kDate, regionName) 43 | kService = self._sign(kRegion, serviceName) 44 | kSigning = self._sign(kService, 'aws4_request') 45 | return kSigning 46 | 47 | def _checkKeyInEnv(self): 48 | ret = [] 49 | aws_access_key_id = os.environ.get('AWS_ACCESS_KEY_ID') 50 | aws_secret_access_key = os.environ.get('AWS_SECRET_ACCESS_KEY') 51 | if aws_access_key_id is not None and aws_secret_access_key is not None: 52 | ret.append(aws_access_key_id) 53 | ret.append(aws_secret_access_key) 54 | return ret 55 | 56 | def createWebsocketEndpoint(self, host, port, region, method, awsServiceName, path): 57 | # Gather all the facts 58 | amazonDate = self._createAmazonDate() 59 | amazonDateSimple = amazonDate[0] 60 | amazonDateComplex = amazonDate[1] 61 | idKeyPair = self._checkKeyInEnv() 62 | if idKeyPair == []: 63 | return "" 64 | else: 65 | keyID = idKeyPair[0] 66 | secretKey = idKeyPair[1] 67 | queryParameters = "X-Amz-Algorithm=AWS4-HMAC-SHA256" + \ 68 | "&X-Amz-Credential=" + keyID + "%2F" + amazonDateSimple + "%2F" + region + "%2F" + awsServiceName + "%2Faws4_request" + \ 69 | "&X-Amz-Date=" + amazonDateComplex + \ 70 | "&X-Amz-Expires=86400" + \ 71 | "&X-Amz-SignedHeaders=host" 72 | hashedPayload = hashlib.sha256("").hexdigest() 73 | # Create the string to sign 74 | signedHeaders = "host" 75 | canonicalHeaders = "host:" + host + "\n" 76 | canonicalRequest = method + "\n" + path + "\n" + queryParameters + "\n" + canonicalHeaders + "\n" + signedHeaders + "\n" + hashedPayload 77 | hashedCanonicalRequest = hashlib.sha256(canonicalRequest).hexdigest() 78 | stringToSign = "AWS4-HMAC-SHA256\n" + amazonDateComplex + "\n" + amazonDateSimple + "/" + region + "/" + awsServiceName + "/aws4_request\n" + hashedCanonicalRequest 79 | # Sign it 80 | signingKey = self._getSignatureKey(secretKey, amazonDateSimple, region, awsServiceName) 81 | signature = hmac.new(signingKey, (stringToSign).encode("utf-8"), hashlib.sha256).hexdigest() 82 | # generate url 83 | url = "wss://" + host + ":" + str(port) + path + '?' + queryParameters + "&X-Amz-Signature=" + signature 84 | return url 85 | -------------------------------------------------------------------------------- /raspberry-pi/lib/util/sigV4Core.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/lib/util/sigV4Core.pyc -------------------------------------------------------------------------------- /raspberry-pi/runtime/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/raspberry-pi/runtime/__init__.py -------------------------------------------------------------------------------- /raspberry-pi/runtime/run.py: -------------------------------------------------------------------------------- 1 | ''' 2 | /* 3 | * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"). 6 | * You may not use this file except in compliance with the License. 7 | * A copy of the License is located at 8 | * 9 | * http://aws.amazon.com/apache2.0 10 | * 11 | * or in the "license" file accompanying this file. This file is distributed 12 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 13 | * express or implied. See the License for the specific language governing 14 | * permissions and limitations under the License. 15 | */ 16 | ''' 17 | 18 | from runtimeHub import * 19 | 20 | AWSIoTMQTTArduinoPyHub = runtimeHub("AWSIoTMQTTArduinoHub", "../log/") 21 | AWSIoTMQTTArduinoPyHub.run() 22 | -------------------------------------------------------------------------------- /screenshots/flask-website-demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/screenshots/flask-website-demo.png -------------------------------------------------------------------------------- /screenshots/hardware-setup.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/screenshots/hardware-setup.JPG -------------------------------------------------------------------------------- /screenshots/materials-used.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vjammar/aws-iot-python/c4b2e2dc8d1be8a5ff43d40f09b4f8b6cb2d2786/screenshots/materials-used.jpg --------------------------------------------------------------------------------