Advertisement
cymplecy

pyssl.py

Jan 29th, 2019
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.37 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # 2nd approach using redirection from David Fergusson chrome extension
  3. # 29Jan19
  4.  
  5.  
  6. #import BaseHTTPServer, SimpleHTTPServer
  7. import ssl
  8. import socket
  9.  
  10. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  11. import SocketServer
  12. import json
  13. import urlparse
  14. import subprocess
  15. import time
  16.  
  17. import array
  18. #import itertools
  19. import struct
  20.  
  21. import Queue
  22. import threading
  23. sensorDict = {}
  24.  
  25. def rcv_from_sgh():
  26.     global s,c,server,sensorDict
  27.     dataPrevious = ""
  28.     while True:
  29.         #print "listening for data from sgh"
  30.         # time.sleep(1)
  31.         data = dataPrevious + c.recv(8192)
  32.         if data != "":
  33.             #print "Data received from sgh", data
  34.             #print ("datalen: %s", len(data))
  35.  
  36.             if len(data) > 0:  # Connection still valid so process the data received
  37.  
  38.                 dataIn = data
  39.  
  40.                 datawithCAPS = data
  41.                 # dataOut = ""
  42.                 dataList = []  # used to hold series of broadcasts or sensor updates
  43.                 dataPrefix = ""  # data to be re-added onto front of incoming data
  44.                 while len(dataIn) > 0:  # loop thru data
  45.                     if len(dataIn) < 4:  # If whole length not received then break out of loop
  46.                         # print "<4 chrs received"
  47.                         dataPrevious = dataIn  # store data and tag it onto next data read
  48.                         break
  49.                     sizeInfo = dataIn[0:4]
  50.                     size = struct.unpack(">L", sizeInfo)[0]  # get size of Scratch msg
  51.                     # print "size:", size
  52.                     if size > 0:
  53.                         # print dataIn[4:size + 4]
  54.                         dataMsg = dataIn[4:size + 4].lower()  # turn msg into lower case
  55.  
  56.                         if len(dataMsg) < size:  # if msg recieved is too small
  57.                             # print "half msg found"
  58.                             # print size, len(dataMsg)
  59.                             dataPrevious = dataIn  # store data and tag it onto next data read
  60.                             break
  61.                         #print "msg:",dataMsg
  62.                         dataList.append(dataMsg)
  63.                         dataIn = dataIn[size + 4:]  # cut data down that's been processed
  64.  
  65.                         # print "previous:", dataPrevious
  66.             #print "datalist:",dataList
  67.             for msg in dataList:
  68.                 #print "msg:",msg
  69.                 if msg[0:13] == 'sensor-update':
  70.                     msgsplit = msg[14:].replace('"','').split(' ')
  71.                     #print "split",msgsplit
  72.                     print "SENSORDICT:" + str(sensorDict)
  73.                     for loop in range(int(len(msgsplit) / 2)):
  74.                         sensorDict[msgsplit[loop * 2]] = msgsplit[(loop * 2) + 1]
  75.         else:
  76.             time.sleep(0.1)
  77.  
  78. class S(BaseHTTPRequestHandler):
  79.  
  80.  
  81.     def _set_headers(self):
  82.         self.send_response(200)
  83.         self.send_header('Access-Control-Allow-Origin', '*')    
  84.         self.send_header('Access-Control-Allow-Headers', 'Authorization, Content-Type')
  85.         self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
  86.         self.end_headers()
  87.  
  88.     def do_GET(self):
  89.         self._set_headers()
  90.         parsed_path = urlparse.urlparse(self.path)
  91.         request_id = parsed_path.path
  92.         print "GET: ", self.path
  93.         if self.path == "/favicon.ico":
  94.             return
  95.         splitData = self.path.replace("%3D","=").replace("%20","").replace("%2C",",").replace("%3A",":").lower().split("=")
  96.         #print "split: " , splitData
  97.         if len(splitData) < 2:
  98.             return
  99.         message = splitData[2]
  100.         if message[0] == "[":
  101.             message = message[1:]
  102.         if message[-1] == "]":
  103.             message = message[:-1]
  104.        
  105.         print "MESSAGE: ", message
  106.         dataOut = 'broadcast "'  + message + '"'
  107.         #print "len:", len(splitData)
  108.         # Deal with equivalent of Scratch 1.4 variable changing for AddOn and Motors etc
  109.         if message[0:4] == "set:":
  110.             message = message[4:]
  111.             sMessage = message.split(':')
  112.             dataOut = 'sensor-update "' + sMessage[0] +'" "' + sMessage[1] + '"'
  113.         n = len(dataOut)
  114.         b = (chr((n >> 24) & 0xFF)) + (chr((n >> 16) & 0xFF)) + (chr((n >> 8) & 0xFF)) + (chr(n & 0xFF))
  115.         c.send(b + dataOut)
  116.         print "Data sent to sgh", dataOut
  117.         #print "SENSORDICT:" + str(sensorDict)
  118.         #Deal with equivalent of Scratch 1.4 sensor updates
  119.         if message[0:5] == "read:":
  120.             message = message[5:]
  121.             if message in sensorDict:
  122.                 response = '{"result":"' + sensorDict[message] +'"}'
  123.                 print "Response to Scratch:" + response
  124.                 self.wfile.write(response)
  125.             #else:
  126.             #    response = '{"result":"' + 'NOT FOUND' +'"}'
  127.             #    print "Response to Scratch:" + response
  128.             #    self.wfile.write(response)
  129.         else:
  130.             response = {"result":"Eureka"}
  131.  
  132.             self.wfile.write(json.dumps(response))
  133.  
  134.  
  135.     def do_POST(self):
  136.         #print "POST RCVD"
  137.         self._set_headers()
  138.         parsed_path = urlparse.urlparse(self.path)
  139.         request_id = parsed_path.path
  140.         #response = subprocess.check_output(["python", request_id])
  141.         #self.wfile.write(json.dumps(response))
  142.  
  143.     def do_HEAD(self):
  144.         self._set_headers()
  145.        
  146.     def do_OPTIONS(self):
  147.         self.sendResponse(200)
  148.         self.processRequest()
  149.  
  150. def run(server_class=HTTPServer, handler_class=S, port=443):
  151.     server_address = ('', port)
  152.     httpd = server_class(server_address, handler_class)
  153.     httpd.socket = ssl.wrap_socket (httpd.socket, certfile='/home/pi/ca.pem', server_side=True)
  154.     print 'Starting httpd...'
  155.     httpd.serve_forever()
  156.  
  157. s = socket.socket() #Create a socket object
  158. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  159. #host = socket.gethostname() #Get the local machine name
  160. port = 42001 # Reserve a port for your service
  161. s.bind(('127.0.0.1',port)) #Bind to the port
  162. s.listen(5) #Wait for the client connection
  163. print "trying to listen to scratchGPIO_handler"
  164. c,addr = s.accept() #Establish a connection with the client
  165. print "Got connection from ScratchGPIOHandler", addr
  166.  
  167. d = threading.Thread(name='rcv_from_sgh', target=rcv_from_sgh)
  168. d.setDaemon(True)
  169. d.start()
  170.  
  171. run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement