-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxhid.py
executable file
·180 lines (157 loc) · 5.9 KB
/
xhid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python
#
# xHID is program for sharing keyboard, mouse and possibly other devices between computers
#
import os
import sys
import configparser
import logging
import logging.config
import argparse
import importlib
import asyncio
from time import sleep
from threading import Thread
from pprint import pprint,pformat
from queue import Queue
from classes import event, feature, field
script_path = os.path.dirname(os.path.abspath(__file__))
logging.config.fileConfig(os.path.join(script_path, 'logging.ini'))
logger = logging.getLogger('xhid.main')
VERSION="0.1-alfa"
class Task():
method = None
name = None
def __init__(self, name, method):
if not callable(method): raise Exception
self.name = name
self.method = method
class Dispatcher():
__loop = None
__tasks = []
__event_cbs = []
__queue = None
queue_logger = None
def __init__(self):
pass
async def queue_processor(self, queue):
interval = 2
if not self.queue_logger: self.queue_logger = logging.getLogger('xhid.dispatcher')
while True:
item = queue.get()
#if item[field.EVENT] not in [ event.MOUSE_MOVE ]:
# implement some throttling for intensive events
#self.queue_logger.info('Dispatcher:queue_processor: processing queue item: [{}]'.format(pformat(item)))
#await asyncio.sleep(interval)
for t in self.__event_cbs:
t.method(item)
queue.task_done()
def load_module(self, module_name, module_type, params):
logger.debug('Loading module: {}'.format(module_name))
module = importlib.import_module('plugins.'+module_name)
try:
module_object = module.base_class()
ret = module_object.initialize(module_type, params)
try:
self.__tasks.append(
Task(module_name+'_run_method', ret['register_run_method'])
)
except:
logger.debug('Module does not have run mathod.')
pass
try:
self.__event_cbs.append(
Task(module_name+'_event_method', ret['register_event_method'])
)
except:
logger.debug('Module does not have event callback.')
pass
except AttributeError:
logger.error('Plugin %s missing mandatory definitions!', module_name)
raise
except:
raise
def run(self):
#executor = ThreadPoolExecutor(4)
self.__queue = Queue()
#self.__queue.put_nowait(1)
self.__loop = asyncio.get_event_loop()
self.__loop.set_debug(enabled=True)
#logging.getLogger("asyncio").setLevel(logging.DEBUG)
#self.__tasks.append(
# Task('dispatcher_sleeper', self.queue_processor)
# )
#asyncio.run(self.sleeper())
for task in self.__tasks:
#pprint(task)
logger.debug('Scheduling task: {}'.format(task.name))
x = Thread(target=task.method, name=task.name, args=(self.__queue,))
x.start()
# start queue_processor
asyncio.ensure_future(log_exceptions(self.queue_processor(self.__queue)))
try:
self.__loop.run_forever()
except KeyboardInterrupt:
pass
except:
raise
self.__loop.close()
async def log_exceptions(awaitable):
try:
return await awaitable
except Exception:
logger.exception("Unhandled exception")
# global dispatcher
dispatcher = Dispatcher()
def main():
logger.info('xhid, version %s', VERSION)
logger.debug('reading command-line arguments')
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', help='configuration file')
parser.add_argument('-m', '--module', help='module configuration', action='append')
args = parser.parse_args()
#pprint(args)
config = configparser.ConfigParser()
if (args.config):
logger.debug('reading configuration files(s)')
config.read(args.config)
# translate --module options to config
if args.module != None:
for module in args.module:
mdict = module.split(':')
mdict[0] = 'module='+mdict[0]
mdict[1] = 'type='+mdict[1]
xdict = dict(item.split("=") for item in mdict)
#pprint(mdict)
config.read_dict(
{'module:'+xdict['module']+'-'+xdict['type']: xdict }
)
for section in config:
if section.startswith('module:'):
# each device must have type, module, enabled by default
if (config[section].getboolean('enabled', True)):
logger.info('Device {} is enabled, loading...'.format(section))
module = config[section].get('module')
module_type = feature.__dict__[config[section].get('type')]
logger.info(' module: {}'.format(module))
logger.info(' type: {}'.format(module_type.name))
try:
params = {}
for key, val in config[section].items():
if val.lower() in ['true', 'yes']:
v = True
elif val.lower() in ['false', 'no']:
v = False
else:
v = val
params[key] = v
dispatcher.load_module( module,
module_type,
params
)
except:
logger.error('Device {} - Module cannot be loaded.'.format(section))
raise
dispatcher.run()
if __name__ == '__main__':
main()