touchscreen.py 20 KB

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