Skip to content

Commit

Permalink
bf and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
blawar committed Nov 18, 2019
1 parent 0c2f714 commit 4083bb5
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 26 deletions.
42 changes: 29 additions & 13 deletions Server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from urllib.parse import urlparse
from urllib.parse import parse_qs
import collections
import queue

import Server.Controller.Api
import __main__
Expand Down Expand Up @@ -111,6 +112,17 @@ def __init__(self, handler):
def setHead(self, h):
self.head = h

class NutQueue:
def __init__(self):
self.q = queue.Queue(maxsize=10)
self.lock = threading.Lock()

def push(self, obj):
self.q.put(obj)

def shift(self):
return self.q.get(timeout=1)

class NutResponse:
def __init__(self, handler):
self.handler = handler
Expand All @@ -119,18 +131,26 @@ def __init__(self, handler):
self.head = False
self.headersSent = False
self.headers = {'Content-type': 'text/html'}
self.q = collections.deque(maxlen=10)
self.q = NutQueue()
self.thread = None
self.running = False

def worker(self):
while self.running:
while True:
try:
item = self.q.popleft()
item = self.q.shift()
self._write(item)
except:
pass

except queue.Empty:
if not self.running:
return
except IndexError:
if not self.running:
return
except BaseException:
self.running = False
return


def __enter__(self):
if not self.running:
self.running = True
Expand Down Expand Up @@ -184,10 +204,7 @@ def write(self, data):
if self.running == False:
raise IOError('no writer thread')

while len(self.q) == self.q.maxlen:
time.sleep(0.5)

self.q.append(data)
self.q.push(data)

def _write(self, data):
if self.bytesSent == 0 and not self.headersSent:
Expand Down Expand Up @@ -219,16 +236,15 @@ def Response401(request, response):

def route(request, response, verb = 'get'):
try:
print('routing')
if len(request.bits) > 0 and request.bits[0] in mappings:
i = request.bits[1]
methodName = verb + i[0].capitalize() + i[1:]
print('routing to ' + methodName)
Print.info('routing to ' + methodName)
method = getattr(mappings[request.bits[0]], methodName, Response404)
method(request, response, **request.query)
return True
except BaseException as e:
print(str(e))
Print.error('route exception: ' + str(e))
return None
return False

Expand Down
23 changes: 11 additions & 12 deletions nut/Usb.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def sendHeader(self):
pass

def _write(self, data):
print('usbresponse write')
Print.info('usbresponse write')
if self.bytesSent == 0 and not self.headersSent:
self.sendHeader()

Expand All @@ -99,10 +99,9 @@ def __init__(self, url):
self.head = False
self.url = urlparse(self.path)

print('url ' + self.path);
Print.info('url ' + self.path);

self.bits = [x for x in self.url.path.split('/') if x]
print(self.bits)
self.query = parse_qs(self.url.query)

try:
Expand All @@ -126,9 +125,9 @@ def __init__(self, i, o):
self.o = o

def recv(self, timeout = 60000):
print('begin recv')
Print.info('begin recv')
header = bytes(self.i.read(32, timeout=timeout))
print('read complete')
Print.info('read complete')
magic = header[:4]
self.command = int.from_bytes(header[4:8], byteorder='little')
self.size = int.from_bytes(header[8:16], byteorder='little')
Expand All @@ -138,15 +137,15 @@ def recv(self, timeout = 60000):
self.timestamp = int.from_bytes(header[24:32], byteorder='little')

if magic != b'\x12\x12\x12\x12':
print('invalid magic! ' + str(magic));
Print.error('invalid magic! ' + str(magic));
return False

print('receiving %d bytes' % self.size)
Print.info('receiving %d bytes' % self.size)
self.payload = bytes(self.i.read(self.size, timeout=0))
return True

def send(self, timeout = 60000):
print('sending %d bytes' % len(self.payload))
Print.info('sending %d bytes' % len(self.payload))
self.o.write(b'\x12\x12\x12\x12', timeout=timeout)
self.o.write(struct.pack('<I', self.command), timeout=timeout)
self.o.write(struct.pack('<Q', len(self.payload)), timeout=timeout) # size
Expand All @@ -161,14 +160,14 @@ def poll_commands(in_ep, out_ep):
while True:
if p.recv(0):
if p.command == 1:
print('Recv command! %d' % p.command)
Print.debug('Recv command! %d' % p.command)
req = UsbRequest(p.payload.decode('utf-8'))
with UsbResponse(p) as resp:
Server.route(req, resp)
else:
print('Unknown command! %d' % p.command)
Print.error('Unknown command! %d' % p.command)
else:
print('failed to read!')
Print.error('failed to read!')

def daemon():
global status
Expand Down Expand Up @@ -199,5 +198,5 @@ def daemon():

poll_commands(in_ep, out_ep)
except BaseException as e:
print('usb exception: ' + str(e))
Print.error('usb exception: ' + str(e))
time.sleep(1)
2 changes: 1 addition & 1 deletion server.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def __init__(self):
super().__init__()
self.setWindowIcon(QIcon('public_html/images/logo.jpg'))
screen = QDesktopWidget().screenGeometry()
self.title = 'NUT USB / Web Server v2.3'
self.title = 'NUT USB / Web Server v2.4'
self.left = screen.width() / 4
self.top = screen.height() / 4
self.width = screen.width() / 2
Expand Down

0 comments on commit 4083bb5

Please sign in to comment.