Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import os
- import threading
- import socket
- import hashlib
- import time
- import pygame
- from sys import exit
- from pygame.locals import *
- import cv2
- import urllib
- import numpy as np
- import ConfigParser
- ############################
- #####Def. des fonctions#####
- ############################
- def __unicode__(self):
- return unicode(self.name)
- def dat_heure():
- return time.strftime('%d/%m/%y %H:%M:%S',time.localtime())
- def rotateImage(image, angel):#parameter angel in degrees
- height = image.shape[0]
- width = image.shape[1]
- height_big = height * 2
- width_big = width * 2
- image_big = cv2.resize(image, (width_big, height_big))
- image_center = (width_big/2, height_big/2)#rotation center
- rot_mat = cv2.getRotationMatrix2D(image_center,angel, 0.5)
- result = cv2.warpAffine(image_big, rot_mat, (width_big, height_big), flags=cv2.INTER_LINEAR)
- return result
- class thread_get(threading.Thread):
- def __init__(self, nom=''):
- threading.Thread.__init__(self)
- self.nom = nom
- self.Terminated = False
- def run(self):
- while True:
- try:
- data, addr = sock_recu.recvfrom(1024) # buffer size is 1024 bytes
- if(hashlib.sha256(PW).hexdigest() == data.split('|-|')[0]):
- if(data.split('|-|')[1] == "L"):
- liste_ana = eval(data.split('|-|')[2])
- liste_digi = eval(data.split('|-|')[3])
- print dat_heure(), "(" + addr[0] + ")" + " Données reçu: " + str(liste_ana) + str(liste_digi)
- elif(data.split('|-|')[1] == "auto_kill"):
- sock_recu.close()
- exit(0)
- else:
- print dat_heure(), "(" + addr[0] + ")" + " Données reçu: " + data.split('|-|')[1]
- except:
- sock_recu.close()
- exit(0)
- def stop(self):
- self.Terminated = True
- def send_k8055_cmd(event,value1,value2):
- if value1 and value2:
- print dat_heure(), "(" + UDP_IP + ")" + " Commande envoyé:"+event+"("+value1+","+value2+")"
- sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event+"|-|"+value1+"|-|"+value2, (UDP_IP, UDP_PORT))
- elif value1:
- print dat_heure(),"(" + UDP_IP + ")" + " Commande envoyé:"+event+"("+value1+")"
- sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event+"|-|"+value1, (UDP_IP, UDP_PORT))
- else:
- print dat_heure(), "(" + UDP_IP + ")" + " Commande envoyé:"+event+"()"
- sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+event, (UDP_IP, UDP_PORT))
- if(event == "end"):
- sock_recu.close()
- print dat_heure(),"Déconnexion du socket"
- 2
- class thread_cam(threading.Thread):
- def __init__(self, nom=''):
- threading.Thread.__init__(self)
- self.nom = nom
- self.Terminated = False
- def run(self):
- bytes=''
- c_quit = False
- global retourner
- retourner = False
- while not self.Terminated:
- bytes+=stream.read(40)
- a = bytes.find('\xff\xd8')
- b = bytes.find('\xff\xd9')
- if a!=-1 and b!=-1:
- jpg = bytes[a:b+2]
- bytes= bytes[b+2:]
- #i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
- if (retourner == True):
- imageOriginal = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
- imageRotated = rotateImage(imageOriginal, 180)
- else:
- imageOriginal = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
- imageRotated = rotateImage(imageOriginal, 0)
- cv2.imshow('Webcam',imageRotated)
- if cv2.waitKey(1) == 27:
- break
- def stop(self):
- self.Terminated = True
- class thread_voiture(threading.Thread):
- def __init__(self, nom=''):
- threading.Thread.__init__(self)
- self.nom = nom
- self.Terminated = False
- def run(self):
- pygame.init()
- window = pygame.display.set_mode((358,221))
- pygame.display.set_caption("Info")
- black = (0,0,0)
- white=(255,255,255)
- #Chargement img
- fond = pygame.image.load("fond.jpg").convert()
- window.blit(fond, (0,0))
- pygame.display.update()
- gameLoop=True
- moving_left = False
- moving_right = False
- moving_forward = False
- moving_back = False
- break_loop = False
- light = False
- value_add = 0
- global retourner
- retourner = False
- auto_cam = False
- orientation_cam = 90
- while (not self.Terminated and gameLoop==True) or not b.isAlive:
- for event in pygame.event.get():
- if (event.type==pygame.KEYDOWN):
- if (event.key==pygame.K_ESCAPE):
- gameLoop=False
- if (event.key==pygame.K_l):
- if (light == True):
- light = False
- value_add = value_add - 16
- send_k8055_cmd("digital_all_off","","")
- else:
- light = True
- send_k8055_cmd("digital_write","16","")
- value_add = value_add + 16
- if (event.key==pygame.K_c):
- if (auto_cam == True):
- auto_cam = False
- else:
- auto_cam = True
- if (event.key==pygame.K_KP_PLUS):
- if (orientation_cam < 75):
- retourner = True
- else:
- retourner = False
- if (orientation_cam < 170):
- orientation_cam = orientation_cam + 5
- send_k8055_cmd("digital_write",str(value_add + 32),"")
- send_k8055_cmd("analog_out","1",str(orientation_cam))
- else:
- print "Angle maximum atteint"
- if (event.key==pygame.K_KP_MINUS):
- if (orientation_cam > 75):
- retourner = False
- else:
- retourner = True
- if (orientation_cam > 50):
- orientation_cam = orientation_cam - 5
- send_k8055_cmd("digital_write",str(value_add + 32),"")
- send_k8055_cmd("analog_out","1",str(orientation_cam))
- else:
- print "Angle minimum atteint"
- if (event.key==pygame.K_UP and moving_back == False):
- if (auto_cam == True):
- send_k8055_cmd("digital_write",str(value_add + 5 + 32),"")
- send_k8055_cmd("analog_out","1",str(170))
- retourner = False
- else:
- send_k8055_cmd("digital_write",str(value_add + 5),"")
- print "Avant"
- moving_forward = True
- if (event.key==pygame.K_DOWN and moving_forward == False):
- if (auto_cam == True):
- send_k8055_cmd("digital_write",str(value_add + 10 + 32),"")
- send_k8055_cmd("analog_out","1",str(50))
- retourner = True
- else:
- send_k8055_cmd("digital_write",str(value_add + 10),"")
- print "Arrière"
- moving_back = True
- if (event.key==pygame.K_LEFT):
- moving_left = True
- if (event.key==pygame.K_RIGHT):
- moving_right = True
- 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)):
- send_k8055_cmd("digital_write",str(value_add + 1),"")
- print "AVANT GAUCHE"
- moving_left = True
- 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)):
- send_k8055_cmd("digital_write",str(value_add + 4),"")
- print "AVANT DROITE"
- moving_right = True
- 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)):
- send_k8055_cmd("digital_write",str(value_add + 8),"")
- print "Arrière DROITE"
- moving_right = True
- 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)):
- send_k8055_cmd("digital_write",str(value_add + 2),"")
- print "Arrière GAUCHE"
- moving_left = True
- if (event.type==pygame.KEYUP):
- if (event.key==pygame.K_LEFT):
- moving_left = False
- if (event.key==pygame.K_RIGHT):
- moving_right = False
- if (event.key==pygame.K_LEFT and moving_forward == True ):
- send_k8055_cmd("digital_write",str(value_add + 5),"")
- print "Gauche Stop / reprise avant"
- moving_left = False
- if (event.key==pygame.K_LEFT and moving_back == True):
- send_k8055_cmd("digital_write",str(value_add + 10),"")
- print "Gauche Stop / Reprise arriére"
- moving_left = False
- if (event.key==pygame.K_RIGHT and moving_forward == True ):
- send_k8055_cmd("digital_write",str(value_add + 5),"")
- print "Droite Stop / reprise avant"
- moving_right = False
- if (event.key==pygame.K_RIGHT and moving_back == True):
- send_k8055_cmd("digital_write",str(value_add + 10),"")
- print "Droite Stop / Reprise arriére"
- moving_right = False
- if (event.key==pygame.K_UP and moving_back == False):
- send_k8055_cmd("digital_write",str(value_add),"")
- print "Avant Stop"
- moving_forward = False
- if (event.key==pygame.K_DOWN and moving_forward == False):
- send_k8055_cmd("digital_write",str(value_add),"")
- print "Arrière Stop"
- moving_back = False
- sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|auto_kill", (UDP_IP_loc, UDP_PORT_loc))
- pygame.quit()
- def stop(self):
- self.Terminated = True
- #Run....
- print "------------------------"
- print "-- Programme de Tlams"
- print "-- Version 1.0"
- print "-- Date: 01/09/13"
- print "-- Langage: Python V2.7"
- print u"-- Email: tlams[@]free.fr"
- print u"-- Fonction: Permet de gérer une voiture téléguidé"
- print "------------------------"
- print ""
- print u"Informations de configurations:"
- print "- Ports par defaut(Voiture/local):26010"
- print u"- Ip type sur réseau local: 192.168.0.5"
- print "- Ip type avec utilisation de VPN: 10.8.0.1"
- print ""
- print "Lecture du fichier de configurations...",
- config = ConfigParser.RawConfigParser()
- config.read('config.ini')
- print "[OK]"
- default_IP_dest = config.get('IP', 'dest')
- IP_dest = raw_input("IP voiture (%s):" %default_IP_dest)
- if not IP_dest:
- IP_dest = default_IP_dest
- default_IP_local = config.get('IP', 'local')
- IP_local = raw_input("IP locale (%s):" %default_IP_local)
- if not IP_local:
- IP_local = default_IP_local
- default_port_dest = config.get('PORT', 'dest')
- PORT_dest = raw_input("PORT voiture (%s):" %default_port_dest)
- if not PORT_dest:
- PORT_dest = default_port_dest
- default_port_local = config.get('PORT', 'local')
- PORT_local = raw_input("PORT local (%s):" %default_port_local)
- if not PORT_local:
- PORT_local = default_port_local
- passwd = raw_input("Password:")
- config.set('IP', 'local', IP_local)
- config.set('IP', 'dest', IP_dest)
- config.set('PORT', 'dest', PORT_dest)
- config.set('PORT', 'local', PORT_local)
- print u"Ecriture des données...",
- with open('config.ini', 'wb') as configfile:
- config.write(configfile)
- print "[OK]"
- UDP_IP = IP_dest #DEST
- UDP_IP_loc = IP_local #Local IP
- UDP_PORT = int(PORT_dest)
- UDP_PORT_loc = int(PORT_local)
- PW = passwd
- close_sock = False
- bind_sock = False
- stream_flux = False
- test_pw = False
- only_flux = False
- compteur = 0
- sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- sock_recu = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- print u"Test des paramètres..."
- while (bind_sock == False or stream_flux == False):
- if (bind_sock == False):
- try:
- #sock_recu.bind((socket.gethostbyname(socket.gethostname()), UDP_PORT))
- sock_recu.bind((UDP_IP_loc, UDP_PORT_loc))
- bind_sock = True
- except:
- new_test_bind = None
- print "Etablissement du socket local impossible"
- 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."
- while (new_test_bind != "y" and new_test_bind != "n"):
- new_test_bind = raw_input("Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
- if(new_test_bind == "y"):
- default_port_local = config.get('PORT', 'local')
- PORT_local = raw_input("PORT local (%s):" %default_port_local)
- if not PORT_local:
- PORT_local = default_port_local
- default_IP_local = config.get('IP', 'local')
- IP_local = raw_input("IP locale (%s):" %default_IP_local)
- if not IP_local:
- IP_local = default_IP_local
- config.set('IP', 'local', IP_local)
- config.set('PORT', 'local', PORT_local)
- print u"Ecriture des données...",
- with open('config.ini', 'wb') as configfile:
- config.write(configfile)
- UDP_IP_loc = IP_local
- UDP_PORT_loc = int(PORT_local)
- print "[OK]"
- print u"Test des paramètres...",
- if (stream_flux == False):
- try:
- dateheure = time.strftime('%d/%m/%y %H:%M:%S',time.localtime())
- stream=urllib.urlopen('http://'+UDP_IP+':8081/videofeed?something.mjpeg')
- stream_flux = True
- except:
- print "Capture du flux video impossible"
- sock_recu.close()
- new_test_flux = None
- while (new_test_flux != "y" and new_test_flux != "n"):
- new_test_flux = raw_input(u"Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
- if(new_test_flux == "y"):
- #default_port_dest = config.get('PORT', 'dest')
- #PORT_dest = raw_input("PORT voiture (%s):" %default_port_dest)
- #if not PORT_dest:
- #PORT_dest = default_port_dest
- default_IP_dest = config.get('IP', 'dest')
- IP_dest = raw_input("IP voiture (%s):" %default_IP_dest)
- if not IP_dest:
- IP_dest = default_IP_dest
- config.set('IP', 'dest', IP_dest)
- #config.set('PORT', 'dest', PORT_dest)
- print u"Ecriture des données...",
- with open('config.ini', 'wb') as configfile:
- config.write(configfile)
- UDP_IP = IP_dest
- #UDP_PORT = int(PORT_dest)
- print "[OK]"
- print u"Test des paramètres..."
- #TEST MDP
- while(test_pw == False and only_flux == False):
- print u"Envoie de données de tests...",
- sock.sendto(hashlib.sha256(PW).hexdigest()+"|-|"+"digital_all_off", (UDP_IP, UDP_PORT))
- data, addr = sock_recu.recvfrom(1024) # buffer size is 1024 bytes
- print u"Connexion réussi !"
- print u"Test du mot de passe"
- if (" Mot de passe incorrect" == data.split('|-|')[1]):
- print "Mot de passe incorrect"
- new_test_mdp = None
- while (new_test_mdp != "y" and new_test_mdp != "n"):
- new_test_mdp = raw_input(u"Voulez-vous tenter avec de nouveaux parametres ?(y/n)")
- if(new_test_mdp == "n"):
- only_flux = True
- print "Flux Video uniquement"
- break
- else:
- PW = raw_input("Password:")
- else:
- test_pw = True
- print "Mot de passe valide!"
- print "Lancement des threads...",
- close_sock = False
- a = thread_get('recep_k8055_info')
- a.start()
- b = thread_cam('video_cam')
- b.start()
- c = thread_voiture('voiture_conduite')
- c.start()
- print "[OK]"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement