touchscreen.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. #!/usr/bin/python3
  2. #cat touchscreen_pointer_mapping_5.py
  3. import os, tempfile
  4. import time
  5. import subprocess
  6. from _thread import start_new_thread
  7. import sys
  8. sys.stdout.write("\x1b]2;TOUCHSCREEN EVENT\x07")
  9. debug = 0
  10. def mapFromTo_(x,a,b,c,d):
  11. y=(x-a)/(b-a)*(d-c)+c
  12. return y
  13. def mapFromTo(value,in_min,in_max,out_min,out_max):
  14. #y=(value-in_min)/(in_max-in_min)*(out_max-out_min)+out_min
  15. y= (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
  16. if y < out_min:
  17. y = out_min
  18. if y > out_max:
  19. y = out_max
  20. return y
  21. class PIPE():
  22. def __init__(self):
  23. self.tmpdir = tempfile.mkdtemp()
  24. try:os.mkdir(self.tmpdir)
  25. except:pass
  26. self.filename = os.path.join(self.tmpdir, 'myfifo')
  27. def init(self):
  28. print()
  29. print( "create ifio file")
  30. print( self.filename)
  31. try:
  32. os.mkfifo(self.filename)
  33. except OSError as e:
  34. print( "Failed to create FIFO: %s" % e)
  35. print( "ende")
  36. return self.filename
  37. def __del__(self):
  38. print( "PIPE DESTRUKTOR")
  39. #self.fifo.close()
  40. os.remove(self.filename)
  41. os.rmdir(self.tmpdir)
  42. def get_touch_id():
  43. cmd = ["xinput"]
  44. sub = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  45. output = sub.communicate()[0]
  46. #print( output)
  47. data = output.split("\n")
  48. odata = []
  49. pattern = "TouchController"
  50. print( "GET INPUT TUCHSCREEN ID")
  51. for line in data:
  52. if pattern in line:
  53. print( line,end="")
  54. if "id=" in line:
  55. idx = line.index("id=")
  56. idx = line.index("id=")
  57. line = line[idx+3:]
  58. line = line.split(" ")[0]
  59. line = line.split("\t")[0]
  60. print( [line])
  61. odata.append(line)
  62. return odata
  63. def system(cmd):
  64. print( "EXECUTE ",cmd)
  65. os.system(cmd)
  66. print( "END PROCESS",cmd)
  67. def start_xinput(filename):
  68. print()
  69. print( "START suprocess")
  70. input_id0 = 14 #touch digitizer
  71. input_id = 15 #touch digitizer
  72. #input_id = 12 #mouse
  73. input_ids = get_touch_id()
  74. for i in input_ids:
  75. system("xinput map-to-output %s VGA1" % str(i) )
  76. #system("xinput map-to-output %s VGA1" % str(input_id0) )
  77. cmd = ["xinput", "test",str(i),">",filename]
  78. print( cmd)
  79. #os.system( " ".join(cmd) )
  80. start_new_thread( system, ( " ".join(cmd), ) )
  81. #subprocess.Popen(cmd)
  82. #stdoutdata, stderrdata = p.communicate()
  83. #print stdoutdata, stderrdata
  84. #subprocess.run(["tail", "-l"])
  85. print( "end suprocess")
  86. def start_evtest(filename):
  87. print()
  88. print("START suprocess")
  89. input_id0 = 14 #touch digitizer
  90. input_id = 15 #touch digitizer
  91. input_id = 23 #touch digitizer
  92. input_id = 5 #touch digitizer
  93. #input_id = 12 #mouse
  94. #input_ids = get_touch_id()
  95. cmd = ["evtest", "/dev/input/event3",">",filename]
  96. #cmd = ["evtest", "/dev/input/by-id/usb-eGalax_Inc._USB_TouchController-event-mouse",">",filename]
  97. cmd = ["evtest", "/dev/input/event23",">",filename]
  98. #cmd = ["cat", "/dev/input/event23",">",filename]
  99. cmd = ["evtest", "/dev/input/event5",">",filename]
  100. cmd = ["evtest", "/dev/input/event24",">",filename]
  101. #xrandr --listmonitors
  102. print( cmd)
  103. start_new_thread( system, ( " ".join(cmd), ) )
  104. print( "end suprocess")
  105. def disable_xinput_touch(name):
  106. cmd="xinput list"
  107. print("cmd",cmd)
  108. r=os.popen(cmd)
  109. lines = r.readlines()
  110. for line in lines:
  111. if name in line:
  112. line = line.strip()
  113. line = line.split("\t")
  114. print("DISABLE !!",[line])
  115. _id =""
  116. for l in line:
  117. if "id=" in l:
  118. _id = l.replace("id=","")
  119. if _id:
  120. cmd="xinput disable {}".format(_id) # disable touch as normal input
  121. print("cmd:",cmd)
  122. os.system(cmd)
  123. #exit()
  124. def read(filename):
  125. #filename = "eventlog"
  126. import fcntl
  127. print()
  128. print( "START readinloop",filename)
  129. #stream = open(filename,"rt", )
  130. stream = open(filename,"rb", buffering=0)
  131. # NON BLOCKING FILE
  132. fd = stream.fileno()
  133. flag = fcntl.fcntl(fd,fcntl.F_GETFL)
  134. #print flag
  135. fcntl.fcntl(fd,fcntl.F_SETFL,flag | os.O_NONBLOCK)
  136. flag = fcntl.fcntl(fd,fcntl.F_GETFL)
  137. #print flag
  138. #stream.seek(0 ,2)
  139. line =""
  140. A = Action()
  141. A.mode = "touchpad" # or touchscreen
  142. A.mode = "touchscreen"
  143. while 1:
  144. stream_read = ""
  145. try:
  146. stream_read = stream.read()
  147. except IOError as err:
  148. if err.errno == 11: # no data
  149. pass
  150. else:
  151. raise err
  152. for ch in stream_read:
  153. #print [ch ]
  154. if ch:
  155. if "\n" == ch:
  156. if debug:print( "------", len(line))
  157. if line:
  158. if debug:print( [line])
  159. A.action(line)
  160. line = ""
  161. else:
  162. line += ch
  163. time.sleep(0.01)
  164. def cleanup_multipointer(prefix="multipointer_"):
  165. import os
  166. cmd="xinput list | grep '{}'".format(prefix)
  167. print("cleanup xinput", cmd)
  168. r=os.popen(cmd )
  169. lines = r.readlines()
  170. for line in lines:
  171. line = line.strip()
  172. line = line.replace("\t"," " )
  173. if " " in line:
  174. line = line.replace(" "," ")
  175. if "id=" in line and "pointer" in line:
  176. line = line.split()
  177. print("LINE",[line])
  178. _id = line[-4]
  179. _id = _id.replace("id=","")
  180. cmd= "xinput remove-master '{}'".format(_id)
  181. print(cmd)
  182. print(" kill X11 ")
  183. #os.system(cmd)
  184. """traps: xfce4-terminal[283904] trap int3 ip:7f784386cabb sp:7ffebb961c10 error:0 in libglib-2.0.so.0.6600.8[7f784382e000+88000]
  185. [24187.974998] xfce4-terminal[306138]: segfault at 90 ip 00007f1b725ac838 sp 00007ffd8e83b940 error 4 in libgdk-3.so.0.2404.20[7f1b72573000+7f000]
  186. [24187.975015] Code: 41 0f 10 4f 60 48 89 5d 38 f2 0f 5e c8 f2 0f 11 4d 48 e8 8b 72 fd ff 48 89 df e8 93 fb fc ff 48 89 ef 48 89 c6 e8 38 7f fd ff <49> 8b b5 90 00 00 00 48 89 ef e8 89 7f fd ff 49 8d 97 b8 00 00 00
  187. """
  188. class Action():
  189. def __init__(self, output=""):
  190. self._X = 0
  191. self._Y = 0
  192. self._Xmin = 10000000000
  193. self._Ymin = 10000000000
  194. self._Xmax = 0
  195. self._Ymax = 0
  196. self.touch_config= {"x_max":1024,"y_max":"768"}
  197. self.touch = ""
  198. self.screen_config = {}
  199. self.screen = output # "DP-2"
  200. self.timer = time.time()
  201. self.motion_changeX =0
  202. self.motion_changeY =0
  203. self.motion_change = 0
  204. self.btn_cmd = ""
  205. self.btn_timer = time.time()
  206. self.btn_down = 0
  207. self.btn_up = 0
  208. self._btn_timer = 0
  209. self._config_ok = 0
  210. self._config_data = []
  211. self.pointer_config = []
  212. self.pointer_create_count = 0
  213. self.MT_SLOT = 0 #int(ix)
  214. self.mode = "touchpad" # or touchscreen
  215. self.refresh_screen_config()
  216. self.refresh_multipointer_config(cleanup=1)
  217. def refresh_multipointer_config(self,cleanup=0):
  218. print("==============")
  219. self.pointer_config = []
  220. prefix = "multipointer_"
  221. prefix = "librelight_pointer_z"
  222. if cleanup:
  223. cleanup_multipointer(prefix=prefix)
  224. cmd = "xinput list | grep '{}' | grep 'XTEST pointer'".format(prefix)
  225. r = os.popen(cmd)
  226. lines = r.readlines()
  227. for line in lines:
  228. cfg = {}
  229. line = line.strip().split()
  230. print([line])
  231. _id = line[5]
  232. _id = _id.replace(")","")
  233. _id = _id.replace("(","")
  234. _id = _id.replace("id=","")
  235. cfg["id"] = _id
  236. cfg["name"] = line[2]
  237. self.pointer_config.append( cfg )
  238. create = []
  239. for i in range(1,5+1):
  240. ok = 0
  241. n = "{}{}".format(prefix,i)
  242. for j in self.pointer_config:
  243. print("pt",i,j)
  244. print("pt",n, j["name"])
  245. if n == j["name"]:
  246. ok = 1
  247. break
  248. if not ok:
  249. create.append(n)
  250. if 0: #for i in create:
  251. cmd = "xinput create-master '{}'".format(i)
  252. print("CMD:",cmd)
  253. os.system(cmd)
  254. if len(create) and self.pointer_create_count < 10: # recursion !!
  255. print("self.refresh_multipointer_config() # recursion !!!")
  256. self.pointer_create_count += 1
  257. #print(self.pointer_create_count)
  258. self.refresh_multipointer_config()
  259. #exit()
  260. def refresh_screen_config(self):
  261. #self.screen_config = {}
  262. cmd = "xrandr --listmonitors"
  263. r = os.popen(cmd)
  264. lines = r.readlines()
  265. for line in lines[1:]:
  266. cfg = {}
  267. line = line.strip().split()
  268. #print("scr_cfg",[line])
  269. cfg["id"] = line[0]
  270. cfg["name"] = line[1]
  271. cfg["res"] = line[2]
  272. output = line[3]
  273. cfg["output"] = output
  274. if "*" in cfg["name"]:
  275. cfg["primary"] = 1
  276. else:
  277. cfg["primary"] = 0
  278. x,y = cfg["res"].split("x")
  279. cfg["x"] = x.split("/")[0]
  280. cfg["y"] = y.split("/")[0]
  281. pos = y.split("/")
  282. pos = pos[-1]
  283. pos = pos.split("+")
  284. cfg["x_pos"] = pos[1]
  285. cfg["y_pos"] = pos[2]
  286. for k in cfg:
  287. v = cfg[k]
  288. try:
  289. cfg[k] = int(v)
  290. except ValueError:
  291. pass
  292. print(cfg)
  293. self.screen_config[ output] = cfg
  294. print()
  295. #exit()
  296. def x(self):
  297. v = self._X
  298. if self.mode == "touchpad":
  299. scr = self.screen_config[self.screen]
  300. v = mapFromTo(self._X,0,self.touch_config["ABS_X"]["Max"],scr["x_pos"],scr["x_pos"]+scr["x"])
  301. elif self.mode == "touchscreen":
  302. v = mapFromTo(self._X,10,4000,0,1600)
  303. return round(v,2)
  304. def y(self):
  305. v = self._Y
  306. if self.mode == "touchpad":
  307. scr = self.screen_config[self.screen]
  308. v = mapFromTo(self._Y,0,self.touch_config["ABS_Y"]["Max"],scr["y_pos"],scr["y_pos"]+scr["y"])
  309. elif self.mode == "touchscreen":
  310. v = mapFromTo(self._Y,0,1400,0,1600)
  311. return round(v,2)
  312. def _parse_config(self):
  313. print("_parse_config")
  314. code = ""
  315. lines = self._config_data
  316. for i,line in enumerate(lines):
  317. #print(i,[line])
  318. cfg = {}
  319. if "Event code" in line:
  320. line = line.strip()
  321. if " " in line:
  322. line = line.replace(" "," ")
  323. tmp = line.split()
  324. key = tmp[3]
  325. key = key.replace("(","").replace(")","")
  326. cfg["key"] = key
  327. cfg["code"] = tmp[2]
  328. for j in range(1,10):
  329. tmp = lines[i+j]
  330. if not tmp.startswith(" "): #sub config
  331. break
  332. tmp = tmp.strip()
  333. if " " in tmp:
  334. tmp = tmp.replace(" "," ")
  335. tmp = tmp.split()
  336. k = tmp[0]
  337. v = tmp[1]
  338. try:
  339. v = int(v)
  340. except ValueError:
  341. pass
  342. cfg[k] = v
  343. #print(" ADD CFG",key,[k,v])
  344. print("t_cfg",cfg)
  345. self.touch_config[key] = cfg
  346. def check_config(self,line):
  347. if not self._config_ok:
  348. self._config_data.append( line)
  349. print("CONFIG:",[line])
  350. if "Testing ... (interrupt to exit)" in line:
  351. self._config_ok = 1
  352. self._parse_config()
  353. return 0
  354. else: #init touch screen config
  355. if "Input driver version is" in line:
  356. self._config_ok = 0
  357. elif "Input device ID:" in line:
  358. self._config_ok = 0
  359. return 1
  360. def cur_pointer_id(self):
  361. i = self.MT_SLOT
  362. return "xxx"
  363. return self.pointer_config[i]["id"]
  364. def _check_ABS(self,line):
  365. #print([line])
  366. if "ABS_MT_SLOT" in line:
  367. key =", value "
  368. #print("ABS_MT_SLOT", line)
  369. line = line.strip()
  370. if key in line:
  371. ix = line.split()[-1] #.index(key)
  372. try:
  373. ix = int(ix)
  374. if ix > 5:
  375. ix = 5
  376. self.MT_SLOT = ix
  377. #print("++++++++++++++++++++++++++++++++++++++++++++++++++++ NEW SLOT",ix)
  378. #self.cur_pointer_id()
  379. except ValueError:
  380. pass
  381. if "ABS_X" in line or "ABS_Y" in line:# or "ABS_MT_POSITION_X" in line or "ABS_MT_POSITION_Y" in line:
  382. key =", value "
  383. #print("ABS", [line])
  384. if key in line:
  385. ix = line.index(key)
  386. try:
  387. c = line[ix+len(key):]
  388. c = int(c)
  389. if "_X" in line:
  390. self._X =c
  391. if c > self._Xmax:
  392. self._Xmax = c
  393. if c < self._Xmin:
  394. self._Xmin = c
  395. self.motion_changeX += 1
  396. else:
  397. self._Y =c
  398. if debug:print( [c , self._Ymin,c < self._Ymin])
  399. if c > self._Ymax:
  400. self._Ymax = c
  401. if c < self._Ymin:
  402. self._Ymin = c
  403. self.motion_changeY += 1
  404. #cmd = "xdotool mousemove {} {}".format(self.x(),self.y())
  405. # 3 position changes to acept position
  406. if self.motion_changeX >0 and self.motion_changeY >0:
  407. self.motion_changeX =0
  408. self.motion_changeY =0
  409. self.motion_change = 1
  410. if debug:
  411. print( line)
  412. print( cmd)
  413. print( self._Xmin,self._Xmax,self._Ymin,self._Ymax)
  414. #os.system(cmd)
  415. except Exception as e:
  416. print( "ERR:",e)
  417. print( "E:", [line])
  418. def action(self,line):
  419. """GET DEVICE INPUT LINE AND DECODE IT
  420. xinput test
  421. motion a[0]=366 a[1]=558
  422. evtestEvent:
  423. time 1556826444.499763, type 2 (EV_REL), code 0 (REL_X), value 8
  424. """
  425. if "motion" in line: #xinput test id
  426. if "a[2]=1" in line:
  427. #cmd = "xdotool click 1"
  428. cmd = "xdotool mouseup 1"
  429. p = self.cur_pointer_id()
  430. cmd = "xte -i {} mouseup 1".format(p)
  431. print("\033[92m{}\033[0m".format( cmd))
  432. #print( line,cmd)
  433. os.system(cmd)
  434. #os.system("ls -l")
  435. if "a[2]=0" in line:
  436. #cmd = "xdotool click 1"
  437. cmd = "xdotool mousedown 1"
  438. print("\033[95m{}\033[0m".format( cmd))
  439. #print( line,cmd)
  440. #os.system(cmd)
  441. #os.system("ls -l")
  442. if "BTN_LEFT" in line or "BTN_TOUCH" in line: #evtest /dev/input/eventX
  443. " Mouse Button Click "
  444. key =", value "
  445. if key in line:
  446. ix = line.index(key)
  447. try:
  448. c = line[ix+len(key):]
  449. c = int(c)
  450. if c:
  451. self.btn_down = 1
  452. else:
  453. self.btn_up = 1
  454. #RESET MOTION CHANGE
  455. self.motion_changeX =0
  456. self.motion_changeY =0
  457. self.motion_change = 0
  458. self.btn_timer = time.time()
  459. #print( line)
  460. #print( self.btn_cmd )
  461. except Exception as e:
  462. print( "ERR:",e)
  463. print( "E:", [line])
  464. if not self.check_config(line):
  465. return
  466. self._check_ABS(line)
  467. self.run()
  468. def btn(self,val):
  469. if val:
  470. #time.sleep(0.01)
  471. cmd = "xdotool mousedown 1"
  472. p = self.cur_pointer_id()
  473. cmd = "xte -i {} 'mousedown 1'".format(p)
  474. print("\033[92m{:30}\033[0m".format( cmd),"{:8} {:8} ".format(self.x(),self.y()) , self.screen ,"MT_SLOT",self.MT_SLOT)
  475. if self.MT_SLOT == 0:
  476. pass
  477. os.system(cmd)
  478. self.btn_down = 0
  479. self._btn_timer = time.time()
  480. else:
  481. cmd = "xdotool mouseup 1"
  482. p = self.cur_pointer_id()
  483. cmd = "xte -i {} 'mouseup 1'".format(p)
  484. #print( cmd)
  485. t = time.time() - self._btn_timer
  486. print("\033[95m{:30}\033[0m".format( cmd),"{:8} {:8} ".format(self.x(),self.y()) , self.screen ,"MT_SLOT", self.MT_SLOT,"t:",round(t,2))
  487. os.system(cmd)
  488. self.btn_up = 0
  489. self._btn_timer = time.time()
  490. time.sleep(0.001)
  491. def set_pointer(self):
  492. cmd = "xdotool mousemove {:8} {:8} ".format(self.x(),self.y())
  493. p = self.cur_pointer_id()
  494. cmd = "xte -i {} 'mousemove {:8} {:8}' ".format(p,int(self.x()),int(self.y()))
  495. t = int((time.time() - self._btn_timer)*10)/10.
  496. #print(t,"\033[95m{}\033[0m".format( cmd),self.mode)
  497. if self.MT_SLOT == 0:
  498. os.system(cmd)
  499. #os.system(cmd)
  500. self.motion_changeX =0
  501. self.motion_changeY =0
  502. self.motion_change = 0
  503. self.timer = time.time()
  504. #time.sleep(0.000001)
  505. def run(self):
  506. #print "RUN"
  507. if self.btn_up:
  508. if time.time() - self._btn_timer > 0.05: # long press
  509. self.set_pointer()
  510. self.btn(0)
  511. #self.btn(0)
  512. if self.motion_change and self.timer+0.01 < time.time():
  513. if self.btn_down:
  514. #self.btn(0)
  515. self.set_pointer()
  516. self.btn(1)
  517. if self.motion_change and self.timer+0.01 < time.time():
  518. if time.time() - self._btn_timer > 0.05: # long press
  519. self.set_pointer()
  520. def main():
  521. pipe = PIPE()
  522. time.sleep(0.1)
  523. filename = pipe.init()
  524. time.sleep(0.2)
  525. #start_xinput(filename)
  526. start_evtest(filename)
  527. time.sleep(0.2)
  528. #time.sleep(2)
  529. #read from evtest or xinput and redirekt std output into file(fifo pipe)
  530. read(filename)
  531. def get_touch_list():
  532. cmd = 'echo "\n" | evtest 2>&1 | grep event'
  533. print("cmd", [cmd])
  534. r = os.popen(cmd)
  535. lines = r.readlines()
  536. out = []
  537. for line in lines:
  538. line = line.strip()
  539. #line = line.replace("\t"," ")
  540. line = line.split("\t")
  541. if len(line) >= 2:
  542. path = line[0][:-1]
  543. name = line[1]
  544. out.append([name,path])
  545. return out
  546. def touch_filter(name,lines):
  547. out = []
  548. for line in lines:
  549. if name == line[0]:
  550. out = line
  551. return out
  552. #touch_list = get_touch_list()
  553. #name="ELAN Touchscreen"
  554. #x= touch_filter(name,touch_list)
  555. #print(x)
  556. #
  557. #name = "iSolution multitouch"
  558. #x= touch_filter(name,touch_list)
  559. #print(x)
  560. def main_threading():
  561. pipe = PIPE()
  562. filename = pipe.init()
  563. start_xinput(filename)
  564. #start_evtest(filename)
  565. #time.sleep(2)
  566. read(filename)
  567. def main2(cmd="",output=""):
  568. a = Action(output)
  569. line = ""
  570. #cmd="evtest /dev/input/event5"
  571. #cmd="evtest /dev/input/event24"
  572. r = os.popen(cmd)
  573. print(cmd)
  574. while 1:
  575. line = r.readline()
  576. a.action(line)
  577. if __name__ == "__main__":
  578. #main()
  579. touch_list = get_touch_list()
  580. touchscreen_count = 0
  581. #TOUCH 1
  582. name = "iSolution multitouch"
  583. x= touch_filter(name,touch_list)
  584. print(x)
  585. if len(x):
  586. disable_xinput_touch(name)
  587. #cmd="evtest /dev/input/event24"
  588. cmd="evtest {}".format(x[1])
  589. start_new_thread(main2,(cmd,"DP-2"))
  590. touchscreen_count +=1
  591. #TOUCH 1
  592. name="ELAN Touchscreen"
  593. x= touch_filter(name,touch_list)
  594. print(x)
  595. if len(x):
  596. disable_xinput_touch(name)
  597. #cmd="evtest /dev/input/event5"
  598. cmd="evtest {}".format(x[1])
  599. start_new_thread(main2,(cmd,"eDP-1"))
  600. touchscreen_count +=1
  601. #main2()
  602. while 1:
  603. time.sleep(1)