touchscreen.py 20 KB

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