1# Copyright 2018 Espressif Systems (Shanghai) PTE LTD 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# 15 16from __future__ import print_function 17 18import socket 19 20from future.utils import tobytes 21 22try: 23 from http.client import HTTPConnection, HTTPSConnection 24except ImportError: 25 # Python 2 fallback 26 from httplib import HTTPConnection, HTTPSConnection 27 28from .transport import Transport 29 30 31class Transport_HTTP(Transport): 32 def __init__(self, hostname, ssl_context=None): 33 try: 34 socket.gethostbyname(hostname.split(':')[0]) 35 except socket.gaierror: 36 raise RuntimeError('Unable to resolve hostname :' + hostname) 37 38 if ssl_context is None: 39 self.conn = HTTPConnection(hostname, timeout=60) 40 else: 41 self.conn = HTTPSConnection(hostname, context=ssl_context, timeout=60) 42 try: 43 print('Connecting to ' + hostname) 44 self.conn.connect() 45 except Exception as err: 46 raise RuntimeError('Connection Failure : ' + str(err)) 47 self.headers = {'Content-type': 'application/x-www-form-urlencoded','Accept': 'text/plain'} 48 49 def _send_post_request(self, path, data): 50 try: 51 self.conn.request('POST', path, tobytes(data), self.headers) 52 response = self.conn.getresponse() 53 if response.status == 200: 54 return response.read().decode('latin-1') 55 except Exception as err: 56 raise RuntimeError('Connection Failure : ' + str(err)) 57 raise RuntimeError('Server responded with error code ' + str(response.status)) 58 59 def send_data(self, ep_name, data): 60 return self._send_post_request('/' + ep_name, data) 61