touchscreen.py 18 KB

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