touchscreen.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. if 1:
  167. # creat 5 pointer on screen for Mutlitouch input
  168. # pointer jump's around on X11
  169. create = []
  170. for i in [1]: #range(1,5+1):
  171. ok = 0
  172. n = "{}{}".format(prefix,i)
  173. for j in self.pointer_config:
  174. print("pt",i,j)
  175. print("pt",n, j["name"])
  176. if n == j["name"]:
  177. ok = 1
  178. break
  179. if not ok:
  180. create.append(n)
  181. for i in create:
  182. cmd = "xinput create-master '{}'".format(i)
  183. print("CMD:",cmd)
  184. os.system(cmd)
  185. if len(create) and self.pointer_create_count < 10: # recursion !!
  186. print("self.refresh_multipointer_config() # recursion !!!")
  187. self.pointer_create_count += 1
  188. #print(self.pointer_create_count)
  189. self.refresh_multipointer_config()
  190. #for p in range(12):
  191. #for p in self.pointer_config:
  192. # cmd = "xte -i {} 'mousemove {:8} {:8}' ".format(p,10,20)
  193. # os.system(cmd)
  194. def refresh_screen_config(self):
  195. #self.screen_config = {}
  196. cmd = "xrandr --listmonitors"
  197. r = os.popen(cmd)
  198. lines = r.readlines()
  199. for line in lines[1:]:
  200. cfg = {}
  201. line = line.strip().split()
  202. #print("scr_cfg",[line])
  203. cfg["id"] = line[0]
  204. cfg["name"] = line[1]
  205. cfg["res"] = line[2]
  206. output = line[3]
  207. cfg["output"] = output
  208. if "*" in cfg["name"]:
  209. cfg["primary"] = 1
  210. else:
  211. cfg["primary"] = 0
  212. x,y = cfg["res"].split("x")
  213. cfg["x"] = x.split("/")[0]
  214. cfg["y"] = y.split("/")[0]
  215. pos = y.split("/")
  216. pos = pos[-1]
  217. pos = pos.split("+")
  218. cfg["x_pos"] = pos[1]
  219. cfg["y_pos"] = pos[2]
  220. for k in cfg:
  221. v = cfg[k]
  222. try:
  223. cfg[k] = int(v)
  224. except ValueError:
  225. pass
  226. print(cfg)
  227. self.screen_config[ output] = cfg
  228. print()
  229. #exit()
  230. def x(self):
  231. v = self._X
  232. if self.mode == "touchpad":
  233. scr = self.screen_config[self.screen]
  234. v = mapFromTo(self._X,0,self.touch_config["ABS_X"]["Max"],scr["x_pos"],scr["x_pos"]+scr["x"])
  235. elif self.mode == "touchscreen":
  236. v = mapFromTo(self._X,10,4000,0,1600)
  237. return round(v,2)
  238. def y(self):
  239. v = self._Y
  240. if self.mode == "touchpad":
  241. scr = self.screen_config[self.screen]
  242. v = mapFromTo(self._Y,0,self.touch_config["ABS_Y"]["Max"],scr["y_pos"],scr["y_pos"]+scr["y"])
  243. elif self.mode == "touchscreen":
  244. v = mapFromTo(self._Y,0,1400,0,1600)
  245. return round(v,2)
  246. def _parse_config(self):
  247. print("_parse_config")
  248. code = ""
  249. lines = self._config_data
  250. for i,line in enumerate(lines):
  251. #print(i,[line])
  252. cfg = {}
  253. if "Event code" in line:
  254. line = line.strip()
  255. if " " in line:
  256. line = line.replace(" "," ")
  257. tmp = line.split()
  258. key = tmp[3]
  259. key = key.replace("(","").replace(")","")
  260. cfg["key"] = key
  261. cfg["code"] = tmp[2]
  262. for j in range(1,10):
  263. tmp = lines[i+j]
  264. if not tmp.startswith(" "): #sub config
  265. break
  266. tmp = tmp.strip()
  267. if " " in tmp:
  268. tmp = tmp.replace(" "," ")
  269. tmp = tmp.split()
  270. k = tmp[0]
  271. v = tmp[1]
  272. try:
  273. v = int(v)
  274. except ValueError:
  275. pass
  276. cfg[k] = v
  277. #print(" ADD CFG",key,[k,v])
  278. print("t_cfg",cfg)
  279. self.touch_config[key] = cfg
  280. def check_config(self,line):
  281. if not self._config_ok:
  282. self._config_data.append( line)
  283. print("CONFIG:",[line])
  284. if "Testing ... (interrupt to exit)" in line:
  285. self._config_ok = 1
  286. self._parse_config()
  287. return 0
  288. else: #init touch screen config
  289. if "Input driver version is" in line:
  290. self._config_ok = 0
  291. elif "Input device ID:" in line:
  292. self._config_ok = 0
  293. return 1
  294. def cur_pointer_id(self):
  295. i = self.MT_SLOT
  296. #return "xxx"
  297. return self.pointer_config[i]["id"]
  298. def _check_ABS(self,line):
  299. #print([line])
  300. if "ABS_MT_SLOT" in line:
  301. key =", value "
  302. #print("ABS_MT_SLOT", line)
  303. line = line.strip()
  304. if key in line:
  305. ix = line.split()[-1] #.index(key)
  306. try:
  307. ix = int(ix)
  308. if ix > 5:
  309. ix = 5
  310. self.MT_SLOT = ix
  311. #print("++++++++++++++++++++++++++++++++++++++++++++++++++++ NEW SLOT",ix)
  312. #self.cur_pointer_id()
  313. except ValueError:
  314. pass
  315. if "ABS_X" in line or "ABS_Y" in line:# or "ABS_MT_POSITION_X" in line or "ABS_MT_POSITION_Y" in line:
  316. key =", value "
  317. #print("ABS", [line])
  318. if key in line:
  319. ix = line.index(key)
  320. try:
  321. c = line[ix+len(key):]
  322. c = int(c)
  323. if "_X" in line:
  324. self._X =c
  325. if c > self._Xmax:
  326. self._Xmax = c
  327. if c < self._Xmin:
  328. self._Xmin = c
  329. self.motion_changeX += 1
  330. else:
  331. self._Y =c
  332. if debug:print( [c , self._Ymin,c < self._Ymin])
  333. if c > self._Ymax:
  334. self._Ymax = c
  335. if c < self._Ymin:
  336. self._Ymin = c
  337. self.motion_changeY += 1
  338. #cmd = "xdotool mousemove {} {}".format(self.x(),self.y())
  339. # 3 position changes to acept position
  340. if self.motion_changeX >0 and self.motion_changeY >0:
  341. self.motion_changeX =0
  342. self.motion_changeY =0
  343. self.motion_change = 1
  344. if debug:
  345. print( line)
  346. print( cmd)
  347. print( self._Xmin,self._Xmax,self._Ymin,self._Ymax)
  348. #os.system(cmd)
  349. except Exception as e:
  350. print( "ERR:",e)
  351. print( "E:", [line])
  352. def action(self,line):
  353. """GET DEVICE INPUT LINE AND DECODE IT
  354. xinput test
  355. motion a[0]=366 a[1]=558
  356. evtestEvent:
  357. time 1556826444.499763, type 2 (EV_REL), code 0 (REL_X), value 8
  358. """
  359. if "motion" in line: #xinput test id
  360. if "a[2]=1" in line:
  361. #cmd = "xdotool click 1"
  362. cmd = "xdotool mouseup 1"
  363. p = self.cur_pointer_id()
  364. cmd = "xte -i {} mouseup 1".format(p)
  365. print("\033[92m{}\033[0m".format( cmd))
  366. #print( line,cmd)
  367. os.system(cmd)
  368. #os.system("ls -l")
  369. if "a[2]=0" in line:
  370. #cmd = "xdotool click 1"
  371. cmd = "xdotool mousedown 1"
  372. print("\033[95m{}\033[0m".format( cmd))
  373. #print( line,cmd)
  374. #os.system(cmd)
  375. #os.system("ls -l")
  376. if "BTN_LEFT" in line or "BTN_TOUCH" in line: #evtest /dev/input/eventX
  377. " Mouse Button Click "
  378. key =", value "
  379. if key in line:
  380. ix = line.index(key)
  381. try:
  382. c = line[ix+len(key):]
  383. c = int(c)
  384. if c:
  385. self.btn_down = 1
  386. else:
  387. self.btn_up = 1
  388. #RESET MOTION CHANGE
  389. self.motion_changeX =0
  390. self.motion_changeY =0
  391. self.motion_change = 0
  392. self.btn_timer = time.time()
  393. #print( line)
  394. #print( self.btn_cmd )
  395. except Exception as e:
  396. print( "ERR:",e)
  397. print( "E:", [line])
  398. if not self.check_config(line):
  399. return
  400. self._check_ABS(line)
  401. self.run()
  402. def btn(self,val):
  403. if val:
  404. #time.sleep(0.01)
  405. cmd = "xdotool mousedown 1"
  406. p = self.cur_pointer_id()
  407. cmd = "xte -i {} 'mousedown 1'".format(p)
  408. print("\033[92m{:30}\033[0m".format( cmd),"{:8} {:8} ".format(self.x(),self.y()) , self.screen ,"MT_SLOT",self.MT_SLOT)
  409. if self.MT_SLOT == 0:
  410. pass
  411. os.system(cmd)
  412. self.btn_down = 0
  413. self._btn_timer = time.time()
  414. else:
  415. cmd = "xdotool mouseup 1"
  416. p = self.cur_pointer_id()
  417. cmd = "xte -i {} 'mouseup 1'".format(p)
  418. #print( cmd)
  419. t = time.time() - self._btn_timer
  420. 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))
  421. os.system(cmd)
  422. self.btn_up = 0
  423. self._btn_timer = time.time()
  424. time.sleep(0.001)
  425. def set_pointer(self):
  426. cmd = "xdotool mousemove {:8} {:8} ".format(self.x(),self.y())
  427. p = self.cur_pointer_id()
  428. cmd = "xte -i {} 'mousemove {:8} {:8}' ".format(p,int(self.x()),int(self.y()))
  429. t = int((time.time() - self._btn_timer)*10)/10.
  430. #print(t,"\033[95m{}\033[0m".format( cmd),self.mode)
  431. if self.MT_SLOT == 0:
  432. os.system(cmd)
  433. #os.system(cmd)
  434. self.motion_changeX =0
  435. self.motion_changeY =0
  436. self.motion_change = 0
  437. self.timer = time.time()
  438. #time.sleep(0.000001)
  439. def run(self):
  440. #print "RUN"
  441. if self.btn_up:
  442. if time.time() - self._btn_timer > 0.05: # long press
  443. self.set_pointer()
  444. self.btn(0)
  445. #self.btn(0)
  446. if self.motion_change and self.timer+0.01 < time.time():
  447. if self.btn_down:
  448. #self.btn(0)
  449. self.set_pointer()
  450. self.btn(1)
  451. if self.motion_change and self.timer+0.01 < time.time():
  452. if time.time() - self._btn_timer > 0.05: # long press
  453. self.set_pointer()
  454. def get_touch_list():
  455. cmd = 'echo "\n" | evtest 2>&1 | grep event'
  456. print("cmd", [cmd])
  457. r = os.popen(cmd)
  458. lines = r.readlines()
  459. out = []
  460. for line in lines:
  461. line = line.strip()
  462. #line = line.replace("\t"," ")
  463. line = line.split("\t")
  464. if len(line) >= 2:
  465. path = line[0][:-1]
  466. name = line[1]
  467. out.append([name,path])
  468. return out
  469. def touch_filter(name,lines):
  470. out = []
  471. for line in lines:
  472. if name == line[0]:
  473. out = line
  474. return out
  475. def main(cmd="",output="",name=""):
  476. a = Action(output)
  477. line = ""
  478. #cmd="evtest /dev/input/event5"
  479. #cmd="evtest /dev/input/event24"
  480. while 1:
  481. r = os.popen(cmd)
  482. print("main cmd: ",cmd)
  483. while 1:
  484. line = r.readline()
  485. if not line:
  486. print("main cmd r.readline return NONE !",int(time.time()))
  487. print("losst touchscteen connection",output)
  488. print()
  489. break
  490. a.action(line)
  491. time.sleep(1)
  492. # rescan touch input's
  493. touch_list = get_touch_list()
  494. x= touch_filter(name,touch_list)
  495. print(x)
  496. if len(x):
  497. disable_xinput_touch(name)
  498. #cmd="evtest /dev/input/event5"
  499. cmd="evtest {}".format(x[1])
  500. if __name__ == "__main__":
  501. touch_list = get_touch_list()
  502. touchscreen_count = 0
  503. #TOUCH 1 a
  504. name = "iSolution multitouch"
  505. x= touch_filter(name,touch_list)
  506. print(x)
  507. if len(x):
  508. disable_xinput_touch(name)
  509. #cmd="evtest /dev/input/event24"
  510. cmd="evtest {}".format(x[1])
  511. #start_new_thread(main,(cmd,"DP-2"))
  512. start_new_thread(main,(cmd,"HDMI-1",name))#),name)
  513. touchscreen_count +=1
  514. #TOUCH 1
  515. name = "iSolution multitouch"
  516. x= touch_filter(name,touch_list)
  517. print(x)
  518. if len(x):
  519. disable_xinput_touch(name)
  520. #cmd="evtest /dev/input/event24"
  521. cmd="evtest {}".format(x[1])
  522. start_new_thread(main,(cmd,"DP-2",name))#),name)
  523. #start_new_thread(main,(cmd,"HDMI-1"))
  524. touchscreen_count +=1
  525. #TOUCH 1
  526. name="ELAN Touchscreen"
  527. x= touch_filter(name,touch_list)
  528. print(x)
  529. if len(x):
  530. disable_xinput_touch(name)
  531. #cmd="evtest /dev/input/event5"
  532. cmd="evtest {}".format(x[1])
  533. start_new_thread(main,(cmd,"eDP-1",name))#),name)
  534. #start_new_thread(main,(cmd,"HDMI-1"))
  535. touchscreen_count +=1
  536. while 1:
  537. time.sleep(1)