Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # 2nd approach using redirection from David Fergusson chrome extension
- # 29Jan19
- #import BaseHTTPServer, SimpleHTTPServer
- import ssl
- import socket
- from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
- import SocketServer
- import json
- import urlparse
- import subprocess
- import time
- import array
- #import itertools
- import struct
- import Queue
- import threading
- sensorDict = {}
- def rcv_from_sgh():
- global s,c,server,sensorDict
- dataPrevious = ""
- while True:
- #print "listening for data from sgh"
- # time.sleep(1)
- data = dataPrevious + c.recv(8192)
- if data != "":
- #print "Data received from sgh", data
- #print ("datalen: %s", len(data))
- if len(data) > 0: # Connection still valid so process the data received
- dataIn = data
- datawithCAPS = data
- # dataOut = ""
- dataList = [] # used to hold series of broadcasts or sensor updates
- dataPrefix = "" # data to be re-added onto front of incoming data
- while len(dataIn) > 0: # loop thru data
- if len(dataIn) < 4: # If whole length not received then break out of loop
- # print "<4 chrs received"
- dataPrevious = dataIn # store data and tag it onto next data read
- break
- sizeInfo = dataIn[0:4]
- size = struct.unpack(">L", sizeInfo)[0] # get size of Scratch msg
- # print "size:", size
- if size > 0:
- # print dataIn[4:size + 4]
- dataMsg = dataIn[4:size + 4].lower() # turn msg into lower case
- if len(dataMsg) < size: # if msg recieved is too small
- # print "half msg found"
- # print size, len(dataMsg)
- dataPrevious = dataIn # store data and tag it onto next data read
- break
- #print "msg:",dataMsg
- dataList.append(dataMsg)
- dataIn = dataIn[size + 4:] # cut data down that's been processed
- # print "previous:", dataPrevious
- #print "datalist:",dataList
- for msg in dataList:
- #print "msg:",msg
- if msg[0:13] == 'sensor-update':
- msgsplit = msg[14:].replace('"','').split(' ')
- #print "split",msgsplit
- print "SENSORDICT:" + str(sensorDict)
- for loop in range(int(len(msgsplit) / 2)):
- sensorDict[msgsplit[loop * 2]] = msgsplit[(loop * 2) + 1]
- else:
- time.sleep(0.1)
- class S(BaseHTTPRequestHandler):
- def _set_headers(self):
- self.send_response(200)
- self.send_header('Access-Control-Allow-Origin', '*')
- self.send_header('Access-Control-Allow-Headers', 'Authorization, Content-Type')
- self.send_header('Access-Control-Allow-Methods', 'GET, POST, PUT')
- self.end_headers()
- def do_GET(self):
- self._set_headers()
- parsed_path = urlparse.urlparse(self.path)
- request_id = parsed_path.path
- print "GET: ", self.path
- if self.path == "/favicon.ico":
- return
- splitData = self.path.replace("%3D","=").replace("%20","").replace("%2C",",").replace("%3A",":").lower().split("=")
- #print "split: " , splitData
- if len(splitData) < 2:
- return
- message = splitData[2]
- if message[0] == "[":
- message = message[1:]
- if message[-1] == "]":
- message = message[:-1]
- print "MESSAGE: ", message
- dataOut = 'broadcast "' + message + '"'
- #print "len:", len(splitData)
- # Deal with equivalent of Scratch 1.4 variable changing for AddOn and Motors etc
- if message[0:4] == "set:":
- message = message[4:]
- sMessage = message.split(':')
- dataOut = 'sensor-update "' + sMessage[0] +'" "' + sMessage[1] + '"'
- n = len(dataOut)
- b = (chr((n >> 24) & 0xFF)) + (chr((n >> 16) & 0xFF)) + (chr((n >> 8) & 0xFF)) + (chr(n & 0xFF))
- c.send(b + dataOut)
- print "Data sent to sgh", dataOut
- #print "SENSORDICT:" + str(sensorDict)
- #Deal with equivalent of Scratch 1.4 sensor updates
- if message[0:5] == "read:":
- message = message[5:]
- if message in sensorDict:
- response = '{"result":"' + sensorDict[message] +'"}'
- print "Response to Scratch:" + response
- self.wfile.write(response)
- #else:
- # response = '{"result":"' + 'NOT FOUND' +'"}'
- # print "Response to Scratch:" + response
- # self.wfile.write(response)
- else:
- response = {"result":"Eureka"}
- self.wfile.write(json.dumps(response))
- def do_POST(self):
- #print "POST RCVD"
- self._set_headers()
- parsed_path = urlparse.urlparse(self.path)
- request_id = parsed_path.path
- #response = subprocess.check_output(["python", request_id])
- #self.wfile.write(json.dumps(response))
- def do_HEAD(self):
- self._set_headers()
- def do_OPTIONS(self):
- self.sendResponse(200)
- self.processRequest()
- def run(server_class=HTTPServer, handler_class=S, port=443):
- server_address = ('', port)
- httpd = server_class(server_address, handler_class)
- httpd.socket = ssl.wrap_socket (httpd.socket, certfile='/home/pi/ca.pem', server_side=True)
- print 'Starting httpd...'
- httpd.serve_forever()
- s = socket.socket() #Create a socket object
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- #host = socket.gethostname() #Get the local machine name
- port = 42001 # Reserve a port for your service
- s.bind(('127.0.0.1',port)) #Bind to the port
- s.listen(5) #Wait for the client connection
- print "trying to listen to scratchGPIO_handler"
- c,addr = s.accept() #Establish a connection with the client
- print "Got connection from ScratchGPIOHandler", addr
- d = threading.Thread(name='rcv_from_sgh', target=rcv_from_sgh)
- d.setDaemon(True)
- d.start()
- run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement