touchscreen.py 21 KB

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