Advertisement
Tlams

Voiture_slaveV2

Sep 8th, 2013
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.46 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. import threading
  6. import socket
  7. import hashlib
  8. import time
  9. import pygame
  10. from sys import exit
  11. from pygame.locals import *
  12. import cv2
  13. import urllib
  14. import numpy as np
  15. import ConfigParser
  16.  
  17.  
  18. ############################
  19. #####Def. des fonctions#####
  20. ############################
  21.  
  22.  
  23. def __unicode__(self):
  24.     return unicode(self.name)
  25.  
  26. def dat_heure():
  27.     return time.strftime('%d/%m/%y %H:%M:%S',time.localtime())
  28.  
  29. def rotateImage(image, angel):#parameter angel in degrees
  30.     height = image.shape[0]
  31.     width = image.shape[1]
  32.     height_big = height * 2
  33.     width_big = width * 2
  34.     image_big = cv2.resize(image, (width_big, height_big))
  35.     image_center = (width_big/2, height_big/2)#rotation center
  36.     rot_mat = cv2.getRotationMatrix2D(image_center,angel, 0.5)
  37.     result = cv2.warpAffine(image_big, rot_mat, (width_big, height_big), flags=cv2.INTER_LINEAR)
  38.     return result
  39.  
  40.  
  41. class thread_get(threading.Thread):    
  42.     def __init__(self, nom=''):
  43.         threading.Thread.__init__(self)
  44.         self.nom = nom
  45.         self.Terminated = False
  46.        
  47.     def run(self):
  48.         while True:
  49.             try:
  50.                 data, addr = sock_recu.recvfrom(1024) # buffer size is 1024 bytes                
  51.                 if(hashlib.sha256(PW).hexdigest() == data.split('|-|')[0]):
  52.                     if(data.split('|-|')[1] == "L"):
  53.                         liste_ana = eval(data.split('|-|')[2])
  54.                         liste_digi = eval(data.split('|-|')[3])
  55.                         print dat_heure(), "(" + addr[0] + ")" + " Données reçu: " + str(liste_ana) + str(liste_digi)
  56.                     elif(data.split('|-|')[1] == "auto_kill"):
  57.                         sock_recu.close()
  58.                         exit(0)
  59.                     else:
  60.                         print dat_heure(), "(" + addr[0] + ")" + " Données reçu: " + data.split('|-|')[1]
  61.             except:
  62.                 sock_recu.close()
  63.                 exit(0)
  64.                
  65.                
  66.     def stop(self):
  67.         self.Terminated = True
  68.        
  69.                                                                                                    
  70. def send_k8055_cmd(event,value1,value2):
  71.     if value1 and value2:
  72.         print dat_heure(), "(" + UDP_IP + ")" + " Commande envoyé:"+event+"("+value1+","+value2+")"
  73.         sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event+"|-|"+value1+"|-|"+value2, (UDP_IP, UDP_PORT))
  74.     elif value1:
  75.         print dat_heure(),"(" + UDP_IP + ")" + " Commande envoyé:"+event+"("+value1+")"
  76.         sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event+"|-|"+value1, (UDP_IP, UDP_PORT))
  77.     else:
  78.         print dat_heure(), "(" + UDP_IP + ")" + " Commande envoyé:"+event+"()"
  79.         sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event, (UDP_IP, UDP_PORT))
  80.          
  81.     if(event == "end"):
  82.         sock_recu.close()
  83.         print dat_heure(),"Déconnexion du socket"
  84. 2
  85. class thread_cam(threading.Thread):    
  86.     def __init__(self, nom=''):
  87.         threading.Thread.__init__(self)
  88.         self.nom = nom
  89.         self.Terminated = False
  90.        
  91.     def run(self):
  92.         bytes=''
  93.         c_quit = False
  94.         global retourner
  95.         retourner = False
  96.         while not self.Terminated:                
  97.             bytes+=stream.read(40)
  98.             a = bytes.find('\xff\xd8')
  99.             b = bytes.find('\xff\xd9')
  100.             if a!=-1 and b!=-1:
  101.                 jpg = bytes[a:b+2]
  102.                 bytes= bytes[b+2:]
  103.                 #i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
  104.                 if (retourner == True):
  105.                     imageOriginal = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
  106.                     imageRotated = rotateImage(imageOriginal, 180)
  107.                 else:
  108.                     imageOriginal = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
  109.                     imageRotated = rotateImage(imageOriginal, 0)
  110.  
  111.                 cv2.imshow('Webcam',imageRotated)
  112.                 if cv2.waitKey(1) == 27:                
  113.                     break
  114.     def stop(self):
  115.         self.Terminated = True
  116.        
  117.  
  118. class thread_voiture(threading.Thread):    
  119.     def __init__(self, nom=''):
  120.         threading.Thread.__init__(self)
  121.         self.nom = nom
  122.         self.Terminated = False
  123.        
  124.        
  125.     def run(self):
  126.         pygame.init()
  127.         window = pygame.display.set_mode((358,221))
  128.         pygame.display.set_caption("Info")
  129.          
  130.         black = (0,0,0)
  131.         white=(255,255,255)
  132.         #Chargement img
  133.         fond = pygame.image.load("fond.jpg").convert()
  134.        
  135.         window.blit(fond, (0,0))  
  136.         pygame.display.update()
  137.        
  138.         gameLoop=True
  139.         moving_left = False
  140.         moving_right = False
  141.         moving_forward = False
  142.         moving_back = False
  143.         break_loop = False
  144.         light = False
  145.         value_add = 0
  146.         global retourner
  147.         retourner = False
  148.         auto_cam = False
  149.         orientation_cam = 90
  150.         while (not self.Terminated and gameLoop==True) or not b.isAlive:
  151.             for event in pygame.event.get():
  152.                 if (event.type==pygame.KEYDOWN):                
  153.                     if (event.key==pygame.K_ESCAPE):
  154.                         gameLoop=False
  155.  
  156.                     if (event.key==pygame.K_l):
  157.                         if (light == True):
  158.                             light = False
  159.                             value_add = value_add - 16
  160.                             send_k8055_cmd("digital_all_off","","")
  161.                         else:
  162.                             light = True
  163.                             send_k8055_cmd("digital_write","16","")
  164.                             value_add = value_add + 16
  165.  
  166.                     if (event.key==pygame.K_c):
  167.                         if (auto_cam == True):
  168.                             auto_cam = False
  169.                         else:
  170.                             auto_cam = True
  171.  
  172.                     if (event.key==pygame.K_KP_PLUS):
  173.                         if (orientation_cam < 75):
  174.                             retourner = True
  175.                         else:
  176.                             retourner = False
  177.                            
  178.                         if (orientation_cam < 170):
  179.                             orientation_cam = orientation_cam + 5
  180.                             send_k8055_cmd("digital_write",str(value_add + 32),"")
  181.                             send_k8055_cmd("analog_out","1",str(orientation_cam))
  182.                         else:
  183.                             print "Angle maximum atteint"
  184.  
  185.                     if (event.key==pygame.K_KP_MINUS):
  186.                         if (orientation_cam > 75):
  187.                             retourner = False
  188.                         else:
  189.                             retourner = True
  190.                            
  191.                         if (orientation_cam > 50):
  192.                             orientation_cam = orientation_cam - 5
  193.                             send_k8055_cmd("digital_write",str(value_add + 32),"")
  194.                             send_k8055_cmd("analog_out","1",str(orientation_cam))                          
  195.                         else:
  196.                             print "Angle minimum atteint"
  197.  
  198.                        
  199.                        
  200.                     if (event.key==pygame.K_UP and moving_back == False):
  201.                         if (auto_cam == True):
  202.                             send_k8055_cmd("digital_write",str(value_add + 5 + 32),"")
  203.                             send_k8055_cmd("analog_out","1",str(170))
  204.                             retourner = False
  205.                         else:
  206.                             send_k8055_cmd("digital_write",str(value_add + 5),"")
  207.                         print "Avant"
  208.                         moving_forward = True
  209.                                              
  210.                     if (event.key==pygame.K_DOWN and moving_forward == False):
  211.                         if (auto_cam == True):
  212.                             send_k8055_cmd("digital_write",str(value_add + 10 + 32),"")
  213.                             send_k8055_cmd("analog_out","1",str(50))
  214.                             retourner = True
  215.                         else:
  216.                             send_k8055_cmd("digital_write",str(value_add + 10),"")
  217.                         print "Arrière"
  218.                         moving_back = True
  219.  
  220.                     if (event.key==pygame.K_LEFT):
  221.                         moving_left = True
  222.                        
  223.                     if (event.key==pygame.K_RIGHT):
  224.                         moving_right = True
  225.                      
  226.                     if ((moving_forward == True and moving_right == False and event.key==pygame.K_LEFT) or (moving_left == True and moving_right == False and event.key==pygame.K_UP)):
  227.                         send_k8055_cmd("digital_write",str(value_add + 1),"")
  228.                         print "AVANT GAUCHE"
  229.                         moving_left = True
  230.                        
  231.                     if ((moving_forward == True and moving_left == False and event.key==pygame.K_RIGHT) or (moving_right == True and moving_left == False and event.key==pygame.K_UP)):
  232.                         send_k8055_cmd("digital_write",str(value_add + 4),"")
  233.                         print "AVANT DROITE"
  234.                         moving_right = True
  235.  
  236.                     if ((moving_back == True and moving_left == False and event.key==pygame.K_RIGHT) or (moving_right == True and moving_left == False and event.key==pygame.K_DOWN)):
  237.                         send_k8055_cmd("digital_write",str(value_add + 8),"")
  238.                         print "Arrière DROITE"
  239.                         moving_right = True
  240.                        
  241.                     if ((moving_back == True and moving_right == False and event.key==pygame.K_LEFT) or (moving_left == True and moving_right == False and event.key==pygame.K_DOWN)):
  242.                         send_k8055_cmd("digital_write",str(value_add + 2),"")
  243.                         print "Arrière GAUCHE"                  
  244.                         moving_left = True
  245.  
  246.                        
  247.                 if (event.type==pygame.KEYUP):
  248.  
  249.                     if (event.key==pygame.K_LEFT):
  250.                         moving_left = False
  251.                        
  252.                     if (event.key==pygame.K_RIGHT):
  253.                         moving_right = False
  254.                        
  255.                     if (event.key==pygame.K_LEFT and moving_forward == True ):
  256.                         send_k8055_cmd("digital_write",str(value_add + 5),"")
  257.                         print "Gauche Stop / reprise avant"
  258.                         moving_left = False
  259.  
  260.                     if (event.key==pygame.K_LEFT and  moving_back == True):
  261.                         send_k8055_cmd("digital_write",str(value_add + 10),"")
  262.                         print "Gauche Stop / Reprise arriére"
  263.                         moving_left = False
  264.  
  265.                     if (event.key==pygame.K_RIGHT and moving_forward == True ):
  266.                         send_k8055_cmd("digital_write",str(value_add + 5),"")
  267.                         print "Droite Stop / reprise avant"
  268.                         moving_right = False
  269.  
  270.                     if (event.key==pygame.K_RIGHT and  moving_back == True):
  271.                         send_k8055_cmd("digital_write",str(value_add + 10),"")
  272.                         print "Droite Stop / Reprise arriére"
  273.                         moving_right = False
  274.  
  275.                        
  276.                     if (event.key==pygame.K_UP and moving_back == False):
  277.                         send_k8055_cmd("digital_write",str(value_add),"")
  278.                         print "Avant Stop"
  279.                         moving_forward = False
  280.                        
  281.                     if (event.key==pygame.K_DOWN  and moving_forward == False):
  282.                         send_k8055_cmd("digital_write",str(value_add),"")
  283.                         print "Arrière Stop"
  284.                         moving_back = False
  285.                        
  286.         sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|auto_kill", (UDP_IP_loc, UDP_PORT_loc))                
  287.         pygame.quit()
  288.        
  289.     def stop(self):
  290.         self.Terminated = True
  291.  
  292. #Run....  
  293. print "------------------------"
  294. print "-- Programme de Tlams"
  295. print "-- Version 1.0"
  296. print "-- Date: 01/09/13"
  297. print "-- Langage: Python V2.7"
  298. print u"-- Email: tlams[@]free.fr"
  299. print u"-- Fonction: Permet de gérer une voiture téléguidé"
  300. print "------------------------"
  301. print ""
  302. print u"Informations de configurations:"
  303. print "- Ports par defaut(Voiture/local):26010"
  304. print u"- Ip type sur réseau local: 192.168.0.5"
  305. print "- Ip type avec utilisation de VPN: 10.8.0.1"
  306. print ""
  307.  
  308. print "Lecture du fichier de configurations...",
  309. config = ConfigParser.RawConfigParser()
  310. config.read('config.ini')
  311. print "[OK]"
  312.  
  313. default_IP_dest = config.get('IP', 'dest')
  314. IP_dest = raw_input("IP voiture (%s):" %default_IP_dest)
  315. if not IP_dest:
  316.     IP_dest = default_IP_dest
  317.  
  318. default_IP_local = config.get('IP', 'local')
  319. IP_local = raw_input("IP locale (%s):" %default_IP_local)
  320. if not IP_local:
  321.     IP_local = default_IP_local
  322.  
  323.    
  324. default_port_dest = config.get('PORT', 'dest')
  325. PORT_dest = raw_input("PORT voiture (%s):" %default_port_dest)
  326. if not PORT_dest:
  327.     PORT_dest = default_port_dest
  328.  
  329. default_port_local = config.get('PORT', 'local')
  330. PORT_local = raw_input("PORT local (%s):" %default_port_local)
  331. if not PORT_local:
  332.     PORT_local = default_port_local
  333.  
  334.  
  335. passwd = raw_input("Password:")
  336.  
  337. config.set('IP', 'local', IP_local)
  338. config.set('IP', 'dest', IP_dest)
  339.  
  340.  
  341. config.set('PORT', 'dest', PORT_dest)
  342. config.set('PORT', 'local', PORT_local)
  343.  
  344. print u"Ecriture des données...",
  345. with open('config.ini', 'wb') as configfile:
  346.     config.write(configfile)
  347. print "[OK]"
  348.  
  349.  
  350.  
  351. UDP_IP = IP_dest #DEST
  352. UDP_IP_loc = IP_local #Local IP
  353. UDP_PORT = int(PORT_dest)
  354. UDP_PORT_loc = int(PORT_local)
  355. PW = passwd
  356.  
  357. close_sock = False
  358. bind_sock = False
  359. stream_flux = False
  360. test_pw = False
  361. only_flux = False
  362. compteur = 0
  363.  
  364. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  365. sock_recu = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  366.  
  367. print u"Test des paramètres..."
  368.    
  369. while (bind_sock == False or stream_flux == False):
  370.     if (bind_sock == False):
  371.         try:                                  
  372.             #sock_recu.bind((socket.gethostbyname(socket.gethostname()), UDP_PORT))
  373.             sock_recu.bind((UDP_IP_loc, UDP_PORT_loc))
  374.             bind_sock = True              
  375.         except:
  376.             new_test_bind = None
  377.             print "Etablissement du socket local impossible"
  378.             print u"Si vous êtes sur de vos paramètres, vérifier qu'une session n'est pas déjà ouverte ou que le port ne soit pas déjà utilisé par un autre programe."
  379.             while (new_test_bind != "y" and new_test_bind != "n"):
  380.                 new_test_bind = raw_input("Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
  381.             if(new_test_bind == "y"):
  382.                 default_port_local = config.get('PORT', 'local')
  383.                 PORT_local = raw_input("PORT local (%s):" %default_port_local)
  384.                 if not PORT_local:
  385.                     PORT_local = default_port_local
  386.                 default_IP_local = config.get('IP', 'local')
  387.                 IP_local = raw_input("IP locale (%s):" %default_IP_local)
  388.                 if not IP_local:
  389.                     IP_local = default_IP_local
  390.                 config.set('IP', 'local', IP_local)
  391.                 config.set('PORT', 'local', PORT_local)
  392.                 print u"Ecriture des données...",
  393.                 with open('config.ini', 'wb') as configfile:
  394.                     config.write(configfile)
  395.                 UDP_IP_loc = IP_local
  396.                 UDP_PORT_loc = int(PORT_local)
  397.                 print "[OK]"
  398.                 print u"Test des paramètres...",
  399.                    
  400.     if (stream_flux == False):
  401.         try:
  402.             dateheure = time.strftime('%d/%m/%y %H:%M:%S',time.localtime())
  403.             stream=urllib.urlopen('http://'+UDP_IP+':8081/videofeed?something.mjpeg')
  404.             stream_flux = True
  405.         except:
  406.             print "Capture du flux video impossible"
  407.             sock_recu.close()
  408.             new_test_flux = None
  409.             while (new_test_flux != "y" and new_test_flux != "n"):
  410.                 new_test_flux = raw_input(u"Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
  411.             if(new_test_flux == "y"):
  412.                 #default_port_dest = config.get('PORT', 'dest')
  413.                 #PORT_dest = raw_input("PORT voiture (%s):" %default_port_dest)
  414.                 #if not PORT_dest:
  415.                     #PORT_dest = default_port_dest
  416.                 default_IP_dest = config.get('IP', 'dest')
  417.                 IP_dest = raw_input("IP voiture (%s):" %default_IP_dest)
  418.                 if not IP_dest:
  419.                     IP_dest = default_IP_dest
  420.                 config.set('IP', 'dest', IP_dest)
  421.                 #config.set('PORT', 'dest', PORT_dest)
  422.                 print u"Ecriture des données...",
  423.                 with open('config.ini', 'wb') as configfile:
  424.                     config.write(configfile)
  425.                 UDP_IP = IP_dest
  426.                 #UDP_PORT = int(PORT_dest)
  427.                 print "[OK]"
  428.                 print u"Test des paramètres..."
  429.  
  430. #TEST MDP
  431. while(test_pw == False and only_flux == False):
  432.     print u"Envoie de données de tests...",
  433.     sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+"digital_all_off", (UDP_IP, UDP_PORT))
  434.     data, addr = sock_recu.recvfrom(1024) # buffer size is 1024 bytes
  435.     print u"Connexion réussi !"
  436.     print u"Test du mot de passe"
  437.     if (" Mot de passe incorrect" == data.split('|-|')[1]):
  438.         print "Mot de passe incorrect"
  439.         new_test_mdp = None
  440.         while (new_test_mdp != "y" and new_test_mdp != "n"):
  441.             new_test_mdp = raw_input(u"Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
  442.         if(new_test_mdp == "n"):
  443.             only_flux = True
  444.             print "Flux Video uniquement"
  445.             break
  446.         else:          
  447.             PW = raw_input("Password:")
  448.     else:
  449.         test_pw = True
  450.         print "Mot de passe valide!"
  451.  
  452.  
  453. print "Lancement des threads...",
  454.    
  455. close_sock = False
  456. a = thread_get('recep_k8055_info')
  457. a.start()
  458.  
  459. b = thread_cam('video_cam')
  460. b.start()
  461.  
  462. c = thread_voiture('voiture_conduite')
  463. c.start()
  464.  
  465. print "[OK]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement