Advertisement
ROVniels

JoystickReceive.py and JoystickSend.py

Nov 27th, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.18 KB | None | 0 0
  1. #On the server side (ROV):------------------------------------------------------------------------------------------
  2. #!/usr/bin/env python
  3. # version joystickreceive10.py
  4. # trial to incorporate heartbeat with bash script that pings
  5. # included sql
  6. from __future__ import division
  7. from subprocess import PIPE, Popen
  8. import socket
  9. import time
  10. import datetime
  11. import os
  12. import subprocess
  13. import mysql.connector
  14.  
  15. import psutil
  16. #!/usr/bin/env python
  17. # install with $sudo apt-get install python-dev
  18. # install with $sudo pip install psutil
  19.  
  20. def get_cpu_temperature():
  21. process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
  22. output, _error = process.communicate()
  23. return float(output[output.index('=') + 1:output.rindex("'")])
  24.  
  25. cnx = mysql.connector.connect(user='ROV', password='passROV' , database='sensors')
  26. cursor = cnx.cursor()
  27. ##add_data = ("INSERT INTO sensordata "
  28. ## "(Time,Heading,Roll,Pitch,Tin,Tout,Pin,Pout,Vlipo1)"
  29. ## "VALUES (%s, %s, %s,%s, %s, %s,%s, %s, %s)")
  30.  
  31. add_data = ("INSERT INTO diagnostics "
  32. "(Mleft,Mright,Mvert,Tilt,Free,Light,Time,RamPct,DiskFree,Tcpu,CPUpct)"
  33. "VALUES (%s, %s, %s,%s, %s, %s, %s, %s, %s, %s, %s)")
  34.  
  35.  
  36. # https://gist.github.com/SkyRocknRoll/8718086 get socket IP of client
  37. ServoChnl = [4,17,18,27,22,23,24,25]
  38. DELAY = 0.05
  39. sett=0 #set date time first loop than set=1
  40. SQLwrite=0 #every 4 steps write sql data
  41. LightChange=0
  42. RecMode='RecStart'
  43. cmd="gpio mode 10 out" ##lights out
  44. os.system(cmd)
  45. cmd="gpio write 10 0"
  46. os.system(cmd)
  47.  
  48. def pwm(pin, axis):
  49. cmd = "echo \"" + str(ServoChnl[pin]) + "=" + str(axis) + "\" > /dev/pi-blaster"
  50. ## print cmd
  51. os.system(cmd)
  52. ## time.sleep(DELAY)
  53.  
  54. port = 5000
  55. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  56. s.bind(("", port))
  57. ok=1
  58. FirstMessage=1 #this is a trigger to set the system time to the first timestamp from socket
  59. print "waiting on port:", port
  60. try: # try is used to trap errors
  61. while ok==1:
  62.  
  63. ## ips = s.accept()
  64. ## print ips + " connected"
  65. data, addr = s.recvfrom(1024)
  66. # ['0.15', '0.15', '0.15', '0.158475', '', '0', '2015-12-08 21:12:01.994000']
  67. if data=="Bye":
  68. print "Client pressed 8, server terminated."
  69. quit()
  70. Controls=data.split(",")
  71. # print Controls
  72.  
  73.  
  74.  
  75. if FirstMessage==1: #step to synchronize time on RPI with laptop
  76.  
  77.  
  78. cmd = "sudo date -s \"" + Controls[6] + "\""
  79. os.system(cmd)
  80. FirstMessage=0
  81. print "Connected to client"
  82. ## cmd ="sudo /data/testping.sh &"
  83. ## os.system(cmd)
  84. ## p=subprocess.Popen(cmd)
  85. ## serverip=s.getsockname()
  86. ## print serverip
  87.  
  88. now= datetime.datetime.now() #for heartbeat
  89. if sett==0:
  90. # 2015-10-21 00:10:08.693000
  91. now3=Controls[6]
  92. if len(now3)<26: # '2015-10-23 21:50:39' gives error (int, no float)
  93. now3=now3+".000000"
  94. ## print now3
  95. TimeStamp1=datetime.datetime.strptime(now3, "%Y-%m-%d %H:%M:%S.%f")
  96.  
  97.  
  98. delay=now-TimeStamp1
  99. lag=delay.total_seconds() # 2.7+
  100. ## print lag
  101. if lag>0.5:
  102. #do nothing and skip command to read more recent
  103. drop=1
  104. print "Line dropped"
  105. else:
  106. ## print Controls
  107. for i in range(0,4):
  108. Controls[i]=float(Controls[i])
  109. pwm(i,Controls[i])
  110. cmd=""
  111. if Controls[5]<>LightChange:
  112. if Controls[5]=='1':
  113. cmd = "gpio write 10 1"
  114. else:
  115. cmd = "gpio write 10 0"
  116. os.system(cmd) ##time consuming command
  117. LightChange=Controls[5]
  118. SQLwrite +=1
  119. if SQLwrite ==5:
  120. cpu_temperature = get_cpu_temperature()
  121. ram = psutil.virtual_memory()
  122. cpu_pct=psutil.cpu_percent()
  123. ram_percent_used = ram.percent
  124. disk = psutil.disk_usage('/')
  125. disk_free = disk.free / 2**30
  126. disk_percent_used = disk.percent
  127.  
  128. sensorstring=Controls
  129. sensorstring=(sensorstring)
  130. sensorstring.append(ram_percent_used)
  131. sensorstring.append(disk_free)
  132. sensorstring.append(cpu_temperature)
  133. sensorstring.append(cpu_pct)
  134. cursor.execute(add_data, sensorstring)
  135. cnx.commit()
  136. SQLwrite=0
  137. time.sleep(DELAY)
  138.  
  139.  
  140.  
  141.  
  142.  
  143. ## if Controls[[4]<>RecMode]:
  144. ## if Controls[4]=='RecStop':
  145. ## cmd = "raspivid -t 9999999 -w 1900 -h 1080 -fps 10 -b 500000 -rot 270 -hf -o - | tee /data/stream.h264 | ffmpeg -i - -vcodec copy -an -r 25 -f flv -metadata streamName=myStream tcp://0.0.0.0:6666 &"
  146. ## else:
  147. ## cmd = "raspivid -t 9999999 -w 1900 -h 1080 -fps 10 -b 500000 -vf -hf -o - | ffmpeg -i - -vcodec copy -an -r 25 -f flv -metadata streamName=myStream tcp://0.0.0.0:6666 &"
  148. ## os.system(cmd) ##time consuming command
  149. ## RecMode=Controls[4]
  150.  
  151.  
  152.  
  153. except: #if try failed (in case of error) set servo's to 0 and lights out
  154. for i in range(0,4):
  155. pwm(i,0.15)
  156. cmd = "gpio write 10 0"
  157. os.system(cmd)
  158. print "No connection or error encountered."
  159. cmd= "echo \"release 4\" > /dev/pi-blaster"
  160. os.system(cmd)
  161. cmd= "echo \"release 17\" > /dev/pi-blaster"
  162. os.system(cmd)
  163. cmd= "echo \"release 18\" > /dev/pi-blaster"
  164. os.system(cmd)
  165.  
  166.  
  167. ## 1.25-1.75
  168. ## GPIO number Pin in P1 header
  169. ## 4 P1-7
  170. ## 17 P1-11
  171. ## 18 P1-12
  172. ## 21 P1-13
  173. ## 22 P1-15
  174. ## 23 P1-16
  175. ## 24 P1-18
  176. ## 25 P1-22
  177. cursor.close()
  178. cnx.close()
  179. s.close()
  180.  
  181. #on the client side (laptop):
  182. #-------------------------------------------------------------------------------------------------------------
  183. # # version joystickSend10.py
  184. # Purpose:
  185. #
  186. # Author: Niels
  187. #
  188. # Created: 01-02-2015
  189. # Copyright: (c) Niels 2015
  190. # Licence: <your licence>
  191. # TODO: heartbeat for fail safe. Feedback via website (lights on/off etc)
  192. # pull umbilical and stop motor
  193. #-------------------------------------------------------------------------------
  194.  
  195. import socket
  196. import pygame
  197. import time
  198. import datetime
  199. # Setup pygame and key states
  200. global DriveCommands
  201. global Command
  202. ##global fps
  203. global moveLeft
  204. global moveRighte
  205. global moveQuit
  206. hadEvent = True
  207.  
  208. fps = 5 # Quantity read Joystick per second (def 20 times per second)
  209. # Settings for the RemoteJoyBorg client 61 for ethernet 64 for wifi
  210. broadcastIP = '192.168.1.45' # IP address to send to, 255 in one or more positions is a broadcast / wild-card
  211. #broadcastIP = '192.168.178.24'
  212. broadcastPort = 5000 # What message number to send with
  213.  
  214. # values will be send in list. Item in list explained below:
  215. MotorPort1 = 0 # Drive number for left motor
  216. MotorStar2 = 1 # Drive number for right motor
  217. MotorVert3 = 2 # Drive number for vertical motor
  218. tilt = 0.0 # initialize tilt of webcam
  219. Lights = 0 # toggle lights on or off.
  220. ## Joystick INPUT settings
  221. regularUpdate = True # If True we send a command at a regular interval, if False we only send commands when keys are pressed or released
  222. AxesForward = 0
  223. AxesSide = 1
  224. AxesThrottle = 2 # regulate up down speed.
  225. DurationmSec = 0
  226. ##ButtonDescend = 0
  227. ##ButtonAscend = 1
  228. ##ButtonTiltUp = 2
  229. ##ButtonTiltDown = 3
  230. ##ButtonLights = 4 # after 0.5s turn on/off lights
  231. ##ButtonRecordStart= 5 # after 0.5s Start recording
  232. ##ButtonRecordStop= 6 # after 0.5s Stop recording
  233. ##Button_Quit = 7 # quit python script
  234. ##ButtonCalESC = 8 # Keep pressed for 5 seconds to start calibration routine ESC Turn off ESC, full throttle, startup ESC etc)
  235. ServoMax = [0.245,0.245,0.245,0.185,0.245,0.245] #limit sweep on some servos
  236. ServoMin = [0.055,0.055,0.055,0.13195,0.055,0.055]
  237.  
  238.  
  239. # Tilt # Tilt parameter down0-10up for webcam
  240. DriveCommands = [1,1,1,1,'x','x',1]
  241. AxisInvert = [1,-1,-1] #invert axis 3
  242. AxisAdjust = [0.008,0.008,0]
  243. Command=""
  244. # Setup the connection for sending on
  245. sender = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create the socket
  246. ##sender.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) # Enable broadcasting (sending to many IPs based on wild-cards)
  247. ##sender.bind(('0.0.0.0', 0)) # Set the IP and port number to use locally, IP 0.0.0.0 means all connections and port 0 means assign a number for us (do not care)
  248. #sender.sendto("JoystickSendPC1 activated.", (broadcastIP, broadcastPort)) # hello world
  249.  
  250.  
  251.  
  252.  
  253. pygame.init()
  254.  
  255.  
  256. #Loop until the user clicks the close button.
  257. done = False
  258.  
  259. # Used to manage how fast the screen updates
  260. clock = pygame.time.Clock()
  261.  
  262. # Initialize the joysticks
  263. pygame.joystick.init()
  264.  
  265. # Get ready to #print
  266. ##text#print = Text#print()
  267. buttonPressed=0
  268. ##when_pressed=0.0
  269. # -------- Main Program Loop -----------
  270. while done==False:
  271. # EVENT PROCESSING STEP
  272. for event in pygame.event.get(): # User did something
  273. if event.type == pygame.QUIT: # If user clicked close
  274. done=True # Flag that we are done so we exit this loop
  275.  
  276. # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
  277. if event.type == pygame.JOYBUTTONDOWN:
  278. #print "Joystick button pressed."
  279. if buttonPressed <> 1:
  280. when_pressed = datetime.datetime.now()
  281. buttonPressed=1
  282. if event.type == pygame.JOYBUTTONUP:
  283. buttonPressed=0
  284.  
  285.  
  286. # Get count of joysticks
  287. joystick_count = pygame.joystick.get_count()
  288.  
  289. # For each joystick:
  290. for i in range(joystick_count):
  291. joystick = pygame.joystick.Joystick(i)
  292. joystick.init()
  293.  
  294. # Get the name from the OS for the controller/joystick
  295. name = joystick.get_name()
  296. #print "Joystick name: %s" % name
  297.  
  298. # Usually axis run in pairs, up/down for one, and left/right for
  299. # the other.
  300. axes = joystick.get_numaxes() #3 axis
  301. #print axes
  302.  
  303. for i in range( axes ):
  304. axis = joystick.get_axis( i )*AxisInvert[i]+AxisAdjust[i]
  305. if abs(axis)<0.03: axis=0.00
  306. #print "Axes number is %i" % axis
  307. DriveCommands[i]=round(axis,2) # fill list with values
  308. VertThrustAbs=round((DriveCommands[2]+ 1)/2,2) #Vertical absolute value between 1 and 0
  309. DriveCommands[2]=0
  310. buttons = joystick.get_numbuttons()
  311. #print "number of buttons %i)" % buttons
  312.  
  313. for i in range( buttons ):
  314. if buttonPressed ==1:
  315. Duration=(datetime.datetime.now()-when_pressed)
  316. DurationmSec=int(Duration.total_seconds()*1000)
  317. else:
  318. DurationmSec=0
  319. ## print DurationmSec
  320. button = joystick.get_button( i )
  321. if i == 0 and button == 1:
  322. DriveCommands[2] = VertThrustAbs #while pressed UP power according to lever
  323. if i == 1 and button == 1:
  324. DriveCommands[2] = -VertThrustAbs #while pressed Down power according to lever
  325. if i == 2 and button == 1:
  326. if tilt < 1.0: tilt = tilt +0.25/fps
  327. ## print "Button nr %i value %f with value %f " %(i,button,tilt)
  328. hadEvent = True
  329. if i == 3 and button == 1:
  330. if tilt > -1.0: tilt = tilt -0.25/fps
  331. hadEvent = True
  332. ## print "Button nr %i value %f with value %f " %(i,button,tilt)
  333. if i == 4 and button == 1: #lights
  334. if DurationmSec > 100:
  335. ## print when_pressed
  336. if Lights == 1 : Lights=0 # 1=ON
  337. else: Lights = 1
  338. ## print 'Lights are turned : %i' % Lights
  339. buttonPressed=0
  340. if i == 5 and button == 1: #start recording picam
  341. if DurationmSec > 200:
  342. Command='RecStart'
  343. ## print 'Stream recording turned ON ( %s )' %Command
  344. buttonPressed=0
  345. if i == 6 and button == 1: #stop recording picam
  346. if DurationmSec > 200:
  347. Command='RecStop'
  348. ## print 'Stream recording turned OFF ( %s )' %Command
  349. buttonPressed=0
  350. if i == 7 and button == 1:
  351. if DurationmSec > 500:
  352. sender.sendto("Bye", (broadcastIP, broadcastPort))
  353. print "Button 8 is pressed, server terminated"
  354. quit() #stop script
  355. now= (datetime.datetime.now())
  356. # timecode=now.hour*3600+now.minute*60+now.second+int(now.microsecond/100000)/10.0
  357.  
  358.  
  359. DriveCommands[3]=round(tilt,2)
  360. DriveCommands[4]=Command #commands button only one simultaneously
  361. DriveCommands[5]=Lights
  362. DriveCommands[6]=now
  363.  
  364. for i in range(0,4): #keep values within allowable
  365. if DriveCommands[i] <-1.0 : DriveCommands[i]=-1.0
  366. elif DriveCommands[i] >1.0: DriveCommands[i]=1.0
  367.  
  368.  
  369. M1=DriveCommands[1]+DriveCommands[0] # Convert forward-side to lef and right
  370. M2=DriveCommands[1]-DriveCommands[0] # motor.
  371. if M1 >1:M1=1.0
  372. elif M1 < -1.0: M1=-1.0
  373. if M2 >1 :M2=1
  374. elif M2 < -1.0: M2=-1.0
  375. DriveCommands[0]=M1 # overwrite original array (ugly way)
  376. DriveCommands[1]=M2
  377.  
  378. for ID in range(0,4):
  379. PulseNeu=(ServoMax[ID]+ServoMin[ID])/2 #0.150 0.95 range=PulsePos
  380. PulseNeg=PulseNeu-ServoMin[ID] # width above 0 0.095
  381. PulsePos=ServoMax[ID]-PulseNeu # width below 0
  382. ## print PulsePos,PulseNeu,PulseNeg
  383. if DriveCommands[ID]>0.0 : pulse=DriveCommands[ID]*PulsePos+PulseNeu
  384. else: pulse=DriveCommands[ID]*PulseNeg+PulseNeu # axis already <= 1 max.
  385. ## print "pulse of servo %i is %f " % (ID,pulse)
  386. DriveCommands[ID]=pulse
  387.  
  388. for i in range(0,7):
  389. DriveCommands[i]=str(DriveCommands[i])
  390. print DriveCommands
  391.  
  392.  
  393. sender.sendto(','.join(DriveCommands), (broadcastIP, broadcastPort))
  394. ## recv_data, addr = sender.recvfrom(2048)
  395. ## recv_data, addr = sender.recvfrom(2048)
  396. ## print recv_data
  397. # Hat switch. All or nothing for direction, not like joysticks.
  398. # Value comes back in an array.
  399. ## hats = joystick.get_numhats()
  400. ## #print "Number of hats: %f" %hats
  401. ##
  402. ##
  403. ## for i in range( hats ):
  404. ## hat = joystick.get_hat( i )
  405. ## #print "Hat %f value: %s" % i,hat
  406.  
  407.  
  408.  
  409. # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
  410.  
  411. # Go ahead and update the screen with what we've drawn.
  412. ## pygame.display.flip()
  413.  
  414. # Limit to 4 frames per second
  415. clock.tick(fps)
  416.  
  417.  
  418.  
  419. # Get the currently pressed keys on the keyboard
  420. #PygameHandler(pygame.event.get())
  421. ## if hadEvent or regularUpdate:
  422. ## # Keys have changed, generate the command list based on keys
  423. ## hadEvent = False
  424. ## driveCommands = ['X', 'X', 'X', 'X'] # Default to do not change
  425. ## if AxesTilt:
  426. ## driveCommands[0] = tilt
  427. ## driveCommands[rightDrive - 1] = 'ON'
  428.  
  429. # Close the window and quit.
  430. # If you forget this line, the program will 'hang'
  431. # on exit if running from IDLE.
  432.  
  433. pygame.quit ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement