Code style

This commit is contained in:
Petr Kracik 2020-06-04 13:50:01 +02:00
parent 4cfea640f9
commit 5853ae6dda
3 changed files with 64 additions and 195 deletions

View File

@ -4,8 +4,6 @@ from flask import render_template
from flask import request from flask import request
import threading import threading
import argparse import argparse
import datetime
import time
import json import json
from hidkeycodes import hidkeycodes from hidkeycodes import hidkeycodes
@ -20,10 +18,12 @@ app = Flask(__name__)
hiddev = None hiddev = None
hidmouse = None hidmouse = None
def hid_init(): def hid_init():
global hiddev, hidmouse global hiddev, hidmouse
hiddev=open('/dev/hidg0', 'rb+') hiddev = open('/dev/hidg0', 'rb+')
hidmouse=open('/dev/hidg1', 'rb+') hidmouse = open('/dev/hidg1', 'rb+')
def hid_write(data): def hid_write(data):
if hiddev is None: if hiddev is None:
@ -32,6 +32,7 @@ def hid_write(data):
hiddev.write(data) hiddev.write(data)
hiddev.flush() hiddev.flush()
def hid_mouse_write(btn, x, y, wheel): def hid_mouse_write(btn, x, y, wheel):
if hidmouse is None: if hidmouse is None:
return False return False
@ -57,7 +58,7 @@ def send_key(hidkey, shift, alt, ctlr, mod):
if mod and (hidkey == hidkeycodes['KEY_MOD_LMETA'] or hidkey == hidkeycodes['KEY_MOD_RMETA']): if mod and (hidkey == hidkeycodes['KEY_MOD_LMETA'] or hidkey == hidkeycodes['KEY_MOD_RMETA']):
data[0] += hidkey data[0] += hidkey
hidkey=0 hidkey = 0
data[2] = hidkey data[2] = hidkey
@ -104,17 +105,17 @@ def mouse():
x = x if x >= 0 else 255-abs(x) x = x if x >= 0 else 255-abs(x)
y = y if y >= 0 else 255-abs(y) y = y if y >= 0 else 255-abs(y)
print ("X: {}, Y: {}".format(x,y)) print("X: {}, Y: {}".format(x, y))
hid_mouse_write(btn, x, y, wheel) hid_mouse_write(btn, x, y, wheel)
return Response("", mimetype = "text/plain") return Response("", mimetype="text/plain")
@app.route("/hid/keyboard", methods=["POST"]) @app.route("/hid/keyboard", methods=["POST"])
def keypress(): def keypress():
keyevent = json.loads(request.data) keyevent = json.loads(request.data)
print ("Raw data: {}".format(request.data)) print("Raw data: {}".format(request.data))
rawkeycode = keyevent['code'] rawkeycode = keyevent['code']
hidkeycode, mod = get_hid_by_jscode(rawkeycode) hidkeycode, mod = get_hid_by_jscode(rawkeycode)
@ -130,7 +131,7 @@ def keypress():
except Exception as e: except Exception as e:
print("Error sending HID message", e) print("Error sending HID message", e)
return Response("Press {}".format(hidkeycode), mimetype = "text/plain") return Response("Press {}".format(hidkeycode), mimetype="text/plain")
# check to see if this is the main thread of execution # check to see if this is the main thread of execution

View File

@ -1,134 +1,3 @@
jskeycodes = {
'KEY_A': 'KeyA',
'KEY_B': 'KeyB',
'KEY_C': 'KeyC',
'KEY_D': 'KeyD',
'KEY_E': 'KeyE',
'KEY_F': 'KeyF',
'KEY_G': 'KeyG',
'KEY_H': 'KeyH',
'KEY_I': 'KeyI',
'KEY_J': 'KeyJ',
'KEY_K': 'KeyK',
'KEY_L': 'KeyL',
'KEY_M': 'KeyM',
'KEY_N': 'KeyN',
'KEY_O': 'KeyO',
'KEY_P': 'KeyP',
'KEY_Q': 'KeyQ',
'KEY_R': 'KeyR',
'KEY_S': 'KeyS',
'KEY_T': 'KeyT',
'KEY_U': 'KeyU',
'KEY_V': 'KeyV',
'KEY_W': 'KeyW',
'KEY_X': 'KeyX',
'KEY_Y': 'KeyY',
'KEY_Z': 'KeyZ',
'KEY_GRAVE': 'Backquote',
'KEY_0': 'Digit0',
'KEY_1': 'Digit1',
'KEY_2': 'Digit2',
'KEY_3': 'Digit3',
'KEY_4': 'Digit4',
'KEY_5': 'Digit5',
'KEY_6': 'Digit6',
'KEY_7': 'Digit7',
'KEY_8': 'Digit8',
'KEY_9': 'Digit9',
'KEY_MINUS': 'Minus',
'KEY_EQUAL': 'Equal',
'KEY_LEFTBRACE': 'BracketLeft',
'KEY_RIGHTBRACE': 'BracketRight',
'KEY_SEMICOLON': 'Semicolon',
'KEY_APOSTROPHE': 'Quote',
'KEY_BACKSLASH': 'Backslash',
'KEY_COMMA': 'Comma',
'KEY_DOT': 'Period',
'KEY_SLASH': 'Slash',
'KEY_102ND': 'IntlBackslash',
'KEY_KP0': 'Numpad0',
'KEY_KP1': 'Numpad1',
'KEY_KP2': 'Numpad2',
'KEY_KP3': 'Numpad3',
'KEY_KP4': 'Numpad4',
'KEY_KP5': 'Numpad5',
'KEY_KP6': 'Numpad6',
'KEY_KP7': 'Numpad7',
'KEY_KP8': 'Numpad8',
'KEY_KP9': 'Numpad9',
'KEY_KPASTERISK': 'NumpadMultiply',
'KEY_KPPLUS': 'NumpadAdd',
'KEY_KPMINUS': 'NumpadSubtract',
'KEY_KPDOT': 'NumpadDecimal',
'KEY_KPSLASH': 'NumpadDivide',
'KEY_KPENTER': 'NumpadEnter',
'KEY_ESC': 'Escape',
'KEY_F1': 'F1',
'KEY_F2': 'F2',
'KEY_F3': 'F3',
'KEY_F4': 'F4',
'KEY_F5': 'F5',
'KEY_F6': 'F6',
'KEY_F7': 'F7',
'KEY_F8': 'F8',
'KEY_F9': 'F9',
'KEY_F10': 'F10',
'KEY_F11': 'F11',
'KEY_F12': 'F12',
'KEY_F13': 'F13',
'KEY_F14': 'F14',
'KEY_F15': 'F15',
'KEY_F16': 'F16',
'KEY_F17': 'F17',
'KEY_F18': 'F18',
'KEY_F19': 'F19',
'KEY_F20': 'F20',
'KEY_F21': 'F21',
'KEY_F22': 'F22',
'KEY_F23': 'F23',
'KEY_BACKSPACE': 'Backspace',
'KEY_SPACE': 'Space',
'KEY_TAB': 'Tab',
'KEY_ENTER' : 'Enter',
'KEY_PAGEUP': 'PageUp',
'KEY_PAGEDOWN': 'PageDown',
'KEY_HOME': 'Home',
'KEY_END': 'End',
'KEY_INSERT': 'Insert',
'KEY_DELETE': 'Delete',
'KEY_UP': 'ArrowUp',
'KEY_DOWN': 'ArrowDown',
'KEY_LEFT': 'ArrowLeft',
'KEY_RIGHT': 'ArrowRight',
'KEY_NUMLOCK': 'NumLock',
'KEY_CAPSLOCK': 'CapsLock',
'KEY_SCROLLLOCK': 'ScrollLock',
'KEY_MOD_LMETA': 'MetaLeft',
'KEY_MOD_RMETA': 'MetaRight',
# Because firefox must sending different
'KEY_MOD_LMETA': 'OSLeft',
'KEY_MOD_RMETA': 'OSRight',
'KEY_COMPOSE': 'ContextMenu',
}
jscodehidmap = { jscodehidmap = {
'KeyA': 'KEY_A', 'KeyA': 'KEY_A',
'KeyB': 'KEY_B', 'KeyB': 'KEY_B',

View File

@ -4,7 +4,6 @@ from flask import render_template
import threading import threading
import argparse import argparse
import datetime import datetime
import imutils
import time import time
import cv2 import cv2
from hashlib import md5 from hashlib import md5
@ -27,77 +26,77 @@ time.sleep(1.0)
@app.route("/") @app.route("/")
def index(): def index():
# return the rendered template # return the rendered template
return render_template("index.html") return render_template("index.html")
def detect_motion(frameCount): def detect_motion(frameCount):
global vs, outputFrame, lock global vs, outputFrame, lock
lastframe = None lastframe = None
while True: while True:
flag, frame = cap.read() flag, frame = cap.read()
framedig = md5(frame).digest() framedig = md5(frame).digest()
if lastframe == framedig: if lastframe == framedig:
print("Duplicate frame, skipping") print("Duplicate frame, skipping")
continue continue
if not flag: if not flag:
continue continue
lastframe = framedig lastframe = framedig
timestamp = datetime.datetime.now() timestamp = datetime.datetime.now()
cv2.putText(frame, timestamp.strftime( cv2.putText(frame, timestamp.strftime(
"%A %d %B %Y %I:%M:%S%p"), (10, 15), "%A %d %B %Y %I:%M:%S%p"), (10, 15),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1) cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)
with lock:
outputFrame = frame.copy()
with lock:
outputFrame = frame.copy()
def generate(): def generate():
global outputFrame, lock global outputFrame, lock
while True: while True:
with lock: with lock:
if outputFrame is None: if outputFrame is None:
continue continue
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame) (flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
# ensure the frame was successfully encoded # ensure the frame was successfully encoded
if not flag: if not flag:
continue continue
# yield the output frame in the byte format # yield the output frame in the byte format
yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encodedImage) + b'\r\n') bytearray(encodedImage) + b'\r\n')
time.sleep(0.2) time.sleep(0.2)
@app.route("/video_feed") @app.route("/video_feed")
def video_feed(): def video_feed():
# return the response generated along with the specific media # return the response generated along with the specific media
# type (mime type) # type (mime type)
return Response(generate(), return Response(generate(),
mimetype = "multipart/x-mixed-replace; boundary=frame") mimetype = "multipart/x-mixed-replace; boundary=frame")
# check to see if this is the main thread of execution # check to see if this is the main thread of execution
if __name__ == '__main__': if __name__ == '__main__':
# construct the argument parser and parse command line arguments # construct the argument parser and parse command line arguments
ap = argparse.ArgumentParser() ap = argparse.ArgumentParser()
ap.add_argument("-i", "--ip", type=str, required=True, ap.add_argument("-i", "--ip", type=str, required=True,
help="ip address of the device") help="ip address of the device")
ap.add_argument("-o", "--port", type=int, required=True, ap.add_argument("-o", "--port", type=int, required=True,
help="ephemeral port number of the server (1024 to 65535)") help="ephemeral port number of the server (1024 to 65535)")
ap.add_argument("-f", "--frame-count", type=int, default=32, ap.add_argument("-f", "--frame-count", type=int, default=32,
help="# of frames used to construct the background model") help="# of frames used to construct the background model")
args = vars(ap.parse_args()) args = vars(ap.parse_args())
# start a thread that will perform motion detection # start a thread that will perform motion detection
t = threading.Thread(target=detect_motion, args=( t = threading.Thread(target=detect_motion, args=(
args["frame_count"],)) args["frame_count"],))
t.daemon = True t.daemon = True
t.start() t.start()
# start the flask app # start the flask app
app.run(host=args["ip"], port=args["port"], debug=True, app.run(host=args["ip"], port=args["port"], debug=True,
threaded=True, use_reloader=False) threaded=True, use_reloader=False)