touchscreen.py 18 KB

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