Skip to content

Commit

Permalink
Merge pull request #30 from juwis/poll
Browse files Browse the repository at this point in the history
Poll
  • Loading branch information
SaschaMzH authored Mar 25, 2018
2 parents 149c2a8 + e30f695 commit 33b026d
Show file tree
Hide file tree
Showing 45 changed files with 4,480 additions and 1,036 deletions.
2 changes: 1 addition & 1 deletion code/EyeSetColor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
eye = None


HSTerm.term_exec('Set the color for the top left eye.')
print('Set the color for the top left eye.')
eye = Eye(1)
eye.set_color(255, 0, 0)
6 changes: 3 additions & 3 deletions code/Function.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"""I am a Function and I will HSTerm.term_exec a message.
"""I am a Function and I will print a message.
"""
def FunctionA():
HSTerm.term_exec('Hello from the function!')
print('Hello from the function!')


HSTerm.term_exec('Hello HackerSchool')
print('Hello HackerSchool')
FunctionA()
6 changes: 3 additions & 3 deletions code/HardwareTest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def test_eyes():
"""
def test_servo():
global eyes, servo, motor, j, eye, i
HSTerm.term_exec('Test the servo on channel 2')
print('Test the servo on channel 2')
servo = Servo(1)
servo.set_angle(90)
time.sleep(0.5)
Expand All @@ -43,7 +43,7 @@ def test_servo():
"""
def test_motor():
global eyes, servo, motor, j, eye, i
HSTerm.term_exec('Test the motor on channel 1')
print('Test the motor on channel 1')
motor = Motor(2)
motor.set_speed(0)
time.sleep(0.5)
Expand All @@ -54,7 +54,7 @@ def test_motor():
motor.set_speed(0)


HSTerm.term_exec('Do a test for the hardware.')
print('Do a test for the hardware.')
test_eyes()
test_servo()
test_motor()
2 changes: 1 addition & 1 deletion code/Loops.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@


for i in range(1, 6):
HSTerm.term_exec(str('HackerSchool Rocks ') + str(i))
print(str('HackerSchool Rocks ') + str(i))
7 changes: 5 additions & 2 deletions code/Loops.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<xml xmlns="http://www.w3.org/1999/xhtml">
<variables>
<variable type="" id=";@i-ypfvT7KTS3XWIIJn">i</variable>
</variables>
<block type="controls_for" id="SvGt_rXl)-*teaP0:n*A" x="131" y="147">
<field name="VAR">i</field>
<field name="VAR" id=";@i-ypfvT7KTS3XWIIJn" variabletype="">i</field>
<value name="FROM">
<shadow type="math_number" id="y4QPh18R~6/+tuh;;9h9">
<field name="NUM">1</field>
Expand Down Expand Up @@ -31,7 +34,7 @@
</value>
<value name="ADD1">
<block type="variables_get" id="[I|MVF00Mt]@+TcnfYj(">
<field name="VAR">i</field>
<field name="VAR" id=";@i-ypfvT7KTS3XWIIJn" variabletype="">i</field>
</block>
</value>
</block>
Expand Down
4 changes: 2 additions & 2 deletions code/MotionTrackingAccelerometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
mpu = None


HSTerm.term_exec('Get the data from the accelerometer.')
print('Get the data from the accelerometer.')
mpu = Mpu6050()
HSTerm.term_exec(mpu.get_accel_data())
print(mpu.get_accel_data())
2 changes: 1 addition & 1 deletion code/MotorSetSpeed.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
motor = None


HSTerm.term_exec('Set the motor to full speed forward.')
print('Set the motor to full speed forward.')
motor = Motor(2)
motor.set_speed(100)
2 changes: 1 addition & 1 deletion code/ServoSetAngle.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
servo = None


HSTerm.term_exec('Set the servo to 90 degrees.')
print('Set the servo to 90 degrees.')
servo = Servo(2)
servo.set_angle(90)
236 changes: 16 additions & 220 deletions webserver/HSHttpServer.py
Original file line number Diff line number Diff line change
@@ -1,216 +1,15 @@
#!/usr/bin/python


import SimpleHTTPServer
from BaseHTTPServer import HTTPServer
from SocketServer import ThreadingMixIn
import os
import json
import subprocess

from HSTerm import HSTerm
from HSRequestHandler import HSRequestHandler

ThreadingMixIn.daemon_threads = True

class HSRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

def do_AUTHHEAD(self):
self.send_response(401)
self.send_header('WWW-Authenticate', 'Basic realm="HackerSchool"')
self.send_header('Content-type', 'text/html')
self.end_headers()

def do_GET(self):
''' Present frontpage with user authentication. '''
if self.headers.get('Authorization') is None:
self.do_AUTHHEAD()
self.wfile.write('no auth header received')

elif self.headers.get('Authorization') == 'Basic ' + str(self.server._authorization_key):
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

else:
self.do_AUTHHEAD()
self.wfile.write('not authenticated')

def do_POST(self):
''' Present frontpage with user authentication. '''
if self.headers.get('Authorization') is None:
self.do_AUTHHEAD()
self.wfile.write('no auth header received')
self.wfile.close()

elif self.headers.get('Authorization') == 'Basic ' + str(self.server._authorization_key):

content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)

# Clear the exec file.
HSTerm.clear_exec()

# Set the filename to the exec file anyway.
filename = HSTerm.exec_filename()

if self.path.startswith('/__FILE_ACCESS__?'):
try:
# Extract the variables and handle the file access
variables = HSHttpServer.get_dict_from_url(self.path)

HSTerm.term('FileAccess: %s' % variables['command'])

if variables['command'] == 'save':
# Store all incomming data into the file.
HSTerm.term('Save file %s' % variables['filename'])
savename = HSHttpServer._CODE_ROOT + '/' + variables['filename']
with open(savename, 'wb') as file:
file.write(post_data)
HSTerm.term_exec('File %s saved.' % savename)
HSTerm.term_exec('%d bytes written.' % content_length)
self.sendFile(200, filename)

elif variables['command'] == 'execute':
# Execute the code from RAM when the content is smaller than 1k
HSTerm.term('Execute from RAM.')

post_data = post_data.decode('utf-8')

# Execute the give data.
try:
exec(post_data, globals())
self.sendFile(200, filename)
except Exception as e:
HSTerm.term_exec('Error: %s' % str(e))
self.sendFile(500, filename)

elif variables['command'] == 'load':
# Return the file.
filename = self.server._CODE_ROOT + '/' + variables['filename']
self.sendFile(200, filename)

else:
# The given command is not known.
self.sendFile(404, '404.html')

except Exception as e:
HSTerm.term_exec('Internal Error:\n%s' % str(e))
self.sendFile(500, filename)

elif self.path.startswith('/__COMMAND__'):
try:
# Convert the json data into a key/value dictionary.
args = json.loads(post_data.decode('utf-8'))

HSTerm.term('Command: "%s"' % args['command'])

# Save the new password key only when the oldkey is the same with the current.
if args['command'] == 'save_password':
if (args['oldKey'] == self.server._authorization_key and args['newKey'] != ''):

HSTerm.term('Store the new password')
# Store the password.
self.server._authorization_key = args['newKey']
with open('password', 'w') as file:
file.write(self.server._authorization_key)

HSTerm.term_exec('New password written.')

else:
HSTerm.term('auth key: %s' % self.server._authorization_key)
HSTerm.term('old key: %s' % args['oldKey'])
HSTerm.term('new key: %s' % args['newKey'])
HSTerm.term_exec('Error: Could not store the password.')
HSTerm.term_exec('The current Password is not the same!')
self.sendFile(200, filename)

# Get the list of all available code files.
elif args['command'] == 'get_file_list':

data = {}
data['files'] = os.listdir(self.server._CODE_ROOT)
data['files'].sort()
json_dump = json.dumps(data)

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(json_dump)

# Get the version of this project.
elif args['command'] == 'get_version':

data = {}
data['version'] = self.server._version
json_dump = json.dumps(data)

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(json_dump)

# Run the file which is saved on the device
elif args['command'] == 'run':
run_file = self.server._CODE_ROOT + '/' + args['filename']
try:
exec(open(run_file).read(), globals())
except Exception as e:
HSTerm.term_exec('Error: %s' % str(e))
self.sendFile(200, filename)

# Update all files from the project.
elif args['command'] == 'update':

# Run the update script and save the content to send.
bash = subprocess.Popen(['sh', self.server._UPDATE_FILE, '-c'], stdout=subprocess.PIPE)
data = bash.communicate()[0]

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(data)
self.wfile.write(b'\r\n')
self.wfile.write(b'\r\n')
self.wfile.flush();

# Reboot only if there is an update.
if bash.returncode == 1:
self.wfile.write('\nThe system will be updated / reboot and is available in a few seconds.\n\n\n')
self.wfile.write(b'\r\n')
self.wfile.write(b'\r\n')
self.wfile.flush();
subprocess.check_output(['sh', self.server._UPDATE_FILE, '-u', '-r'])

else:
# The given command is not known.
self.sendFile(404, '404.html')

except Exception as e:
HSTerm.term_exec('Internal Error:\n%s' % str(e))
self.sendFile(500, filename)

else:
self.do_AUTHHEAD()
self.wfile.write('Invalid credentials')

def send_error(self, code, message):
self.send_response(code)
self.send_header('Content-type', 'text/html')
self.end_headers()
f = open('404.html', 'rb')
self.wfile.write(f.read())
f.close()

def sendFile(self, response, filename):
if not os.path.exists(filename):
filename = os.path.join(self.server._DOCUMENT_ROOT, '404.hml')
response = 404

self.send_response(response)
self.send_header('Content-type', 'text/html')
self.end_headers()
f = open(filename, 'rb')
self.wfile.write(f.read())
f.close()


class HSHttpServer(HTTPServer):
class HSHttpServer(ThreadingMixIn, HTTPServer):
"""
This implementation is a simple HTTP Server which works on Windows, Linux and macOS with different Browser.
"""
Expand All @@ -224,6 +23,9 @@ class HSHttpServer(HTTPServer):
# Path to the version file.
_VERSION_FILE = os.path.join(os.path.abspath(os.path.join(os.getcwd(), os.pardir)), '__version__')

# Path to the password file.
_PASSWORD_FILE = os.path.join(os.path.abspath(os.path.join(os.getcwd(), os.pardir)), 'password')

# Path to the update file.
_UPDATE_FILE = os.path.join(os.path.abspath(os.path.join(os.getcwd(), os.pardir)), 'update.sh')

Expand All @@ -236,6 +38,8 @@ class HSHttpServer(HTTPServer):
# Current version of the server.
_version = 'beta\n'

is_running = False

def __init__(self, key):
"""
Create a socket to get its own ip address.
Expand All @@ -244,35 +48,27 @@ def __init__(self, key):
with open(self._VERSION_FILE, 'r') as file:
self._version = file.readline()

HSTerm.term("HackerSchool v. %s" % self._version)
HSTerm.term("Code path: '%s'" % self._CODE_ROOT)
HSTerm.term("WWW path: '%s'\n" % self._DOCUMENT_ROOT)
HSTerm.term('HackerSchool v. %s' % self._version)
HSTerm.term('Code path: \'%s\'' % self._CODE_ROOT)
HSTerm.term('WWW path: \'%s\'\n' % self._DOCUMENT_ROOT)
self._authorization_key = key
HTTPServer.__init__(self, ('', 8080), HSRequestHandler)

def get_auth_key(self):
"""
Returns the authorization key for the webpages.
"""
return self._authorization_key

def start(self):
"""
Configure the server completly and start it forever.
"""
HSTerm.term('Starting server, use <Ctrl+C> to stop.')
HSTerm.term_exec('Server started ...')
os.chdir(self._DOCUMENT_ROOT)
try:
self.serve_forever()
except KeyboardInterrupt:
pass
self.server_close()

@staticmethod
def get_dict_from_url(url):
"""
Get a dict of all variables from an url.
"""
variables = url.split('?')[1]
variables = variables.replace('&', '","')
variables = variables.replace('=', '":"')
variables = '{"%s"}' % variables
variables = json.loads(variables)
return variables
Loading

0 comments on commit 33b026d

Please sign in to comment.