touchscreen.py 20 KB

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