RaspFR :: Forum

Version complète : Lancer une seule fois une fonction dans une boucle
Vous consultez actuellement la version basse qualité d’un document. Voir la version complète avec le bon formatage.
Bonjour,

J'ai un programme qui gère différentes entrées/sorties. Les entrées sont des interrupteurs et les sorties sont des lumières et un électro aimant.
Au démarrage les entrées sont à 0 et l'électro aimant à 1.
Voici la fonction qui se trouve dans un while
Code :
check_if_won(self):
    input_1 = GPIO.input(WebHandler.toGPIO_IN[1])
    input_3 = GPIO.input(WebHandler.toGPIO_IN[3])
    if (input_1 == 1 and input_3 == 0) or (input_1 == 0 and input_3 == 1):
      self.update_out_port(1, GPIO.LOW)
      self.update_out_port(2, GPIO.HIGH)
    elif input_1 == 1 and input_3 == 1:
      self.update_out_port(1, GPIO.HIGH)
      self.update_out_port(2, GPIO.LOW)
      self.update_out_port(3, GPIO.LOW)
    else:
      self.update_out_port(1, GPIO.HIGH)
      self.update_out_port(2, GPIO.LOW)
J'aimerai que lorsque input_1 et input_3 sont à 1 cela bascule les sorties juste pendant 1 seconde.
Je suis pas fort dans le domaine, c'est un ami qui a développé le soft cependant il n'est plus dispo pour m'aider.
Auriez-vous une piste/un exemple pour que je fasse le nécessaire ?
Salutations

Daniel
Bonjour,
38decibel a écrit :...
Auriez-vous une piste/un exemple pour que je fasse le nécessaire ?
Une solution est de lancer sur la condition "elif input_1 == 1 and input_3 == 1:" un Thread d'une durée de vie de 1 seconde.
Ce Thread positionnera les sorties comme actuellement et avant de mourir remettra lesdites sorties comme il les a trouvées au moment de son activation...

Exemple: cf. Python Multithreaded Programming
Ahhhh, je ne m'en sors pas.
Quand je start mon thread ça bascule comme il faut et après plus rien !
J'ai beau changer l'état des entrées rien ne se passe.
Je pige pas ce qu'il se passe. Je m'en réfère à votre expertise.

Le code est ci-dessous
Code :
[== Indéfini ==]
#!/usr/bin/python3

#####################################################
##
## LOG
##

#Parametres du journal
LOG_NAME = "webcontroller"
LOG_PATH = "./log/webcontroller.log"
LOG_FORMAT = "%(asctime)s -> %(levelname)s -> %(message)s"

#Procedure d'ecriture dans le journal
def log(message, level = 0):
  print(message)
  if level == 0:
    logger.setLevel(logging.INFO)
    logger.info(message)
  elif level == 1:
    logger.setLevel(logging.WARNING)
    logger.warning(message)
  elif level == 2:
    logger.setLevel(logging.ERROR)
    logger.exception(message)

###########################################################
##
## Scenario
##
import threading
import time

class Game(threading.Thread):
  def __init__(self, event):
    threading.Thread.__init__(self)
    self.running = False
    self.stopped = False
    self.timedout = False
    self.killed = False
    self.event = event
    self.ready2go = threading.Event()

  def init_room(self):
      self.reset()
      GPIO.output(WebHandler.toGPIO_OUT[1], GPIO.HIGH)
      GPIO.output(WebHandler.toGPIO_OUT[2], GPIO.LOW)
      GPIO.output(WebHandler.toGPIO_OUT[3], GPIO.HIGH)
      GPIO.output(WebHandler.toGPIO_OUT[4], GPIO.LOW) # unused but safier
      self.timedout = False
      self.stopped = False
      self.running = True

  def reset(self):
    WebHandler.OutPortForce[1] = False
    WebHandler.OutPortForce[2] = False
    WebHandler.OutPortForce[3] = False
    WebHandler.OutPortForce[4] = False

  def post_init(self):
    GPIO.output(WebHandler.toGPIO_OUT[1], GPIO.LOW)
    GPIO.output(WebHandler.toGPIO_OUT[2], GPIO.LOW)
    GPIO.output(WebHandler.toGPIO_OUT[3], GPIO.HIGH)
    GPIO.output(WebHandler.toGPIO_OUT[4], GPIO.LOW) # Unused but safier

  def update_out_port(self, num, val):
    if not WebHandler.OutPortForce[num]:
      GPIO.output(WebHandler.toGPIO_OUT[num], val)

  def check_input_value(self, pin):
    print("input pin", pin, "value is", GPIO.input(pin))

  def check_if_won(self):
    flag = False
    input_1 = GPIO.input(WebHandler.toGPIO_IN[1])
    input_3 = GPIO.input(WebHandler.toGPIO_IN[3])
    input_4 = GPIO.input(WebHandler.toGPIO_IN[4])
    if (input_1 == 1 and input_3 == 0) or (input_1 == 0 and input_3 == 1):
      self.update_out_port(1, GPIO.LOW)
      self.update_out_port(2, GPIO.HIGH)
      self.update_out_port(3, GPIO.HIGH)
    elif input_1 == 1 and input_3 == 1:
      #self.update_out_port(1, GPIO.HIGH)
      #self.update_out_port(2, GPIO.LOW)
      #self.update_out_port(3, GPIO.LOW)
      thread_1.start()
    elif input_4 == 1:
      os.system("sudo shutdown -r now")
    else:
      self.update_out_port(1, GPIO.HIGH)
      self.update_out_port(2, GPIO.LOW)
      self.update_out_port(3, GPIO.HIGH)

  def run(self):
    while True:
        self.ready2go.set()
        self.event.wait()
        self.ready2go.clear()
        self.init_room()
        #if not self.killed:
        #  timeout_timer = threading.Timer(3600.0, self.timeout)
        #  timeout_timer.start()
        while not self.stopped and not self.timedout and not self.killed:
          time.sleep(0.3)
          self.check_if_won()

        self.running = False

        #if not self.timedout:
        #  timeout_timer.cancel()

        self.post_init()
          
        self.event.clear()
        print("Game ends !")

        if self.killed:
            return
          

  def timeout(self):
    self.timedout = True

  def stop(self):
    self.stopped = True

  def kill(self):
    self.killed = True
    
####Fin Scenario##########################################

class ShutDown(Exception):
  pass
  
###########################################################
##
## Blink
##
class Blink(threading.Thread):

  #Thread chargé simplement de basculer la sortie pendant une seconde.
  def __init__(self):
    threading.Thread.__init__(self)

  def run(self):
  #Code à exécuter pendant l'exécution du thread.
    GPIO.output(WebHandler.toGPIO_OUT[1], not GPIO.input(WebHandler.toGPIO_OUT[1]))
    time.sleep(1)
    GPIO.output(WebHandler.toGPIO_OUT[1], not GPIO.input(WebHandler.toGPIO_OUT[1]))

####Fin Blink##########################################
    
import logging
import http.server
import socketserver
import urllib.parse
import os

import RPi.GPIO as GPIO


###########################################################
##
## Traitement des requetes
##

#LOCAL_WEB_ADDR = "127.0.0.1"
LOCAL_WEB_ADDR = "192.168.0.23"
WEB_PORT = 8000
WEB_ADDR = LOCAL_WEB_ADDR

class WebHandler(http.server.BaseHTTPRequestHandler):

  #Procedure permettant de retourner une reponse formatee JSON au client
  def response(self, json):
    self.send_response(200)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(bytes(json, "UTF-8"))

  #Fonction d'obtention de la temperature du CPU
  def getCPUtemp(self):
    res = os.popen("vcgencmd measure_temp").readline()
    return(res.replace("temp=","").replace("'C\n",""))

  #Fonction d'obtention de l'espace memoire 1: Total, 2: Utilise, 3: Libre
  def getRAMinfo(self):
    p = os.popen('free')
    i = 0
    while True:
      i += 1
      line = p.readline()
      if i == 2:
        return(line.split()[1:4])

  #Fonction d'obtention de la charge du CPU
  def getCPUusage(self):
    return(str(os.popen("top -b -n 5 -d 0.2 | grep \"Cpu\" | awk 'NR==3{ print($2)}'").readline().strip().replace(",", ".")))

  #Fonction d'obtention de l'espace disque 1: Total, 2: Utilise, 3: Libre, 4: Pourcentage utilise
  def getDiskSpace(self):
    p = os.popen("df -m /")
    i = 0
    while True:
      i += 1
      line = p.readline()
      if i == 2:
        return(line.split()[1:5])  

##  def update_port(self, port):
##    if port in self.query_components:
##        port_num = int(port.replace("port", ""))
##        print("print num = ", port_num)
##        action = self.query_components[port][0]
##        if action == "ON" and self.Port[port_num] == "OFF":
##          self.Port[port_num] = "ON"
##          return True
##        elif action == "OFF" and self.Port[port_num] == "ON":
##          self.Port[port_num] = "OFF"
##          return True
##    return False

  def set_to_high(self, pin):
    print("setting pin output ", pin, " to high")
    GPIO.output(pin, GPIO.HIGH)

  def set_to_low(self, pin):
    print("setting pin output ", pin, " to low")
    GPIO.output(pin, GPIO.LOW)

  def update_port(self, num, dir, val):
    port_num = int(num)
    if dir == "in":
        if val == "ON" and self.InPort[port_num] == "OFF":
          self.InPort[port_num] = "ON"
          return True
        elif val == "OFF" and self.InPort[port_num] == "ON":
          self.InPort[port_num] = "OFF"
          return True
    elif dir == "out":
        if val == "ON":
          #self.OutPort[port_num] = "ON"
          self.set_to_high(self.toGPIO_OUT[port_num])
          self.OutPortForce[port_num] = True
          return True
        elif val == "OFF":
          #self.OutPort[port_num] = "OFF"
          self.set_to_low(self.toGPIO_OUT[port_num])
          self.OutPortForce[port_num] = True
          return True
        elif val == "RESET":
          self.OutPortForce[port_num] = False
          return True
    return False

  def start_game(self):
    log("Starting Game", 1)
    self.thread_event.set()

  def stop_game(self):
    log("Ending Game", 1)
    self.thread_event.clear()
    self.timer.stop()
    self.restart_game_event.wait()
        
  #Fonction appelee lors d'une requete http
  def do_GET(self):
    try:
      #Extraction des parametres
      qs = urllib.parse.urlparse(self.path).query
      query_components = urllib.parse.parse_qs(qs)
      self.query_components = query_components

      if "server" in query_components:
        action = query_components["server"][0]
        if action == "stop":
          self.response("{\"server\": \"shutting\"}")
          self.thread_event.set()
          self.timer.kill()
          self.timer.join()
          self.assassin.start()
          return

      if "game" in query_components:
        action = query_components["game"][0]
        if action == "restart":
          self.stop_game()
          self.start_game()
          self.response("{\"game\": \"restarted\"}")
          return
        if action == "start":
          self.start_game()
          self.response("{\"game\": \"launched\"}")
          return
        if action == "stop":
          self.stop_game()
          self.response("{\"game\": \"stopped\"}")
          return
        if action == "status":
          if self.timer.stopped:
            self.response("{\"game\": \"stopped\"}")
          elif self.timer.timedout:
            self.response("{\"game\": \"timed out\"}")
          elif self.timer.killed:
            self.response("{\"game\": \"killed\"}")
          elif self.timer.running:
            self.response("{\"game\": \"running\"}")
          else:
            self.response("{\"game\": \"not running\"}")
          return
        
      #Informations du systeme
      if "system" in query_components:
        action = query_components["system"][0]

        #Informations sur le systeme
        if action == "infos":
          CPU_temp = self.getCPUtemp()
          CPU_used = self.getCPUusage()
          RAM_infos = self.getRAMinfo()
          DISK_infos = self.getDiskSpace()

          RAM_total = round(int(RAM_infos[0]) / 1024, 1)
          RAM_used = round(int(RAM_infos[1]) / 1024, 1)
          RAM_free = round(int(RAM_infos[2]) / 1024, 1)

          DISK_total = round(int(DISK_infos[0]) / 1000, 1)
          DISK_free = round(int(DISK_infos[1]) / 1000, 1)
          DISK_used = round(int(DISK_infos[2]) / 1000, 1)
          DISK_perc = DISK_infos[3][:-1]

          self.response("""
          {{
            "cpu\" :
            {{
              \"used\" : \"{0}\",
              \"temp\" : \"{1}\"
            }},

            \"memory\" :
            {{
              \"used\" : \"{2}\",
              \"total\" : \"{3}\",
              \"free\" : \"{4}\"
            }},
            \"disk\" :
            {{
              \"used\" : \"{5}\",
              \"total\" : \"{6}\",
              \"free\" : \"{7}\",
              \"perc\" : \"{8}\"
            }}
          }}""".format(CPU_used, CPU_temp, RAM_used, RAM_total, RAM_free, DISK_used, DISK_total, DISK_free, DISK_perc))
          return

      if "port" in query_components:
        changed = self.update_port(query_components["port"][0], query_components["dir"][0], query_components["val"][0])
        if changed:
          self.response("{\"answer\": \"port changes ok\"}")
        else:
          self.response("{\"answer\": \"no port change\"}")
        return

      #Requete concernant le statut
      if "all" in query_components:
        action = query_components["all"][0]

        #Statut des Ports
        if action == "status":

          in_port1 = GPIO.input(self.toGPIO_IN[1])
          in_port2 = GPIO.input(self.toGPIO_IN[2])
          in_port3 = GPIO.input(self.toGPIO_IN[3])
          in_port4 = GPIO.input(self.toGPIO_IN[4])

          out_port1 = GPIO.input(self.toGPIO_OUT[1])
          out_port2 = GPIO.input(self.toGPIO_OUT[2])
          out_port3 = GPIO.input(self.toGPIO_OUT[3])
          out_port4 = GPIO.input(self.toGPIO_OUT[4])

          self.response("""
          {{
            \"in_port1\" : \"{0}\",
            \"in_port2\" : \"{1}\",
            \"in_port3\" : \"{2}\",
            \"in_port4\" : \"{3}\",
            \"out_port1\" : \"{4}\",
            \"out_port2\" : \"{5}\",
            \"out_port3\" : \"{6}\",
            \"out_port4\" : \"{7}\"
          }}""".format(in_port1, in_port2, in_port3, in_port4, out_port1, out_port2, out_port3, out_port4))
          return

      #Requete invalide
      log("Invalid query", 1)
      self.response("{\"error\": \"Invalid query\"}")
    except Exception as ex:
      log(ex, 2)
      pass
    return
    
####Fin Traitement des requêtes###########################
class ThreadingServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
  pass

def GPIO_Init():
  GPIO.cleanup()
  GPIO.setmode(GPIO.BCM)

  print("Changing configuration")
  GPIO.setup(4, GPIO.IN)
  GPIO.setup(17, GPIO.IN)
  GPIO.setup(27, GPIO.IN)
  GPIO.setup(22, GPIO.IN)
        
  GPIO.setup(5, GPIO.OUT)
  GPIO.output(5, GPIO.LOW)
  GPIO.setup(6, GPIO.OUT)
  GPIO.output(6, GPIO.LOW)
  GPIO.setup(13, GPIO.OUT)
  GPIO.output(13, GPIO.LOW)
  GPIO.setup(19, GPIO.OUT)
  GPIO.output(19, GPIO.LOW)
  
############################################################
## MAIN method
##
if __name__ == "__main__":
  thread_1 = Blink()
  GPIO_Init()
  
  #Initialisation du journal
  logger = logging.getLogger(LOG_NAME)
  hdlr = logging.FileHandler(LOG_PATH)
  formatter = logging.Formatter(LOG_FORMAT)
  hdlr.setFormatter(formatter)
  logger.addHandler(hdlr)

  WebHandler.InPort = ["IN Ports status", "OFF", "OFF", "OFF", "OFF"]
  WebHandler.OutPort = ["OUT Ports status", "OFF", "OFF", "OFF", "OFF"]
  WebHandler.OutPortForce = ["OUT Ports status", False, False, False, False]

  WebHandler.toGPIO_IN = ["IN Ports matching", 4, 17, 27, 22]
  WebHandler.toGPIO_OUT = ["OUT Ports matching", 19, 13, 6, 5]

  WebHandler.thread_event = threading.Event()
  WebHandler.thread_event.clear()
  WebHandler.timer = Game(WebHandler.thread_event)
  WebHandler.timer.start()
  WebHandler.restart_game_event = WebHandler.timer.ready2go
  
  log("Starting Room Server")

  #Parametres du serveur HTTP
  server_address = (WEB_ADDR, WEB_PORT)
  try:
    #Instanciation du serveur HTTP
    httpd = ThreadingServer(server_address, WebHandler)
    WebHandler.assassin = threading.Thread(target=httpd.shutdown)
    WebHandler.assassin.daemon = True
    httpd.serve_forever()
  except KeyboardInterrupt:
    log("Shutting down server")
    WebHandler.timer.kill()
    WebHandler.thread_event.set()
    WebHandler.timer.join()
    thread_1.join()
    httpd.socket.close()
    hdlr.close()
    GPIO.cleanup()
Vous cassez plus la tête, mon pote est passé est a résolu le truc en l'espace de 10 minutes !
Voici le code fonctionnel
Code :
#!/usr/bin/python3

#####################################################
##
## LOG
##

#Parametres du journal
LOG_NAME = "webcontroller"
LOG_PATH = "./log/webcontroller.log"
LOG_FORMAT = "%(asctime)s -> %(levelname)s -> %(message)s"

#Procedure d'ecriture dans le journal
def log(message, level = 0):
  print(message)
  if level == 0:
    logger.setLevel(logging.INFO)
    logger.info(message)
  elif level == 1:
    logger.setLevel(logging.WARNING)
    logger.warning(message)
  elif level == 2:
    logger.setLevel(logging.ERROR)
    logger.exception(message)

###########################################################
##
## Scenario
##
import threading
import time

class Game(threading.Thread):
  def __init__(self, event):
    threading.Thread.__init__(self)
    self.running = False
    self.stopped = False
    self.timedout = False
    self.killed = False
    self.event = event
    self.ready2go = threading.Event()
    self.blink_event = threading.Event()
    GPIO.add_event_detect(WebHandler.toGPIO_IN[1], GPIO.RISING)
    GPIO.add_event_detect(WebHandler.toGPIO_IN[3], GPIO.RISING)

  def init_room(self):
      self.reset()
      GPIO.output(WebHandler.toGPIO_OUT[1], GPIO.HIGH)
      GPIO.output(WebHandler.toGPIO_OUT[2], GPIO.LOW)
      GPIO.output(WebHandler.toGPIO_OUT[3], GPIO.HIGH)
      GPIO.output(WebHandler.toGPIO_OUT[4], GPIO.LOW) # unused but safier
      self.timedout = False
      self.stopped = False
      self.running = True

  def reset(self):
    WebHandler.OutPortForce[1] = False
    WebHandler.OutPortForce[2] = False
    WebHandler.OutPortForce[3] = False
    WebHandler.OutPortForce[4] = False

  def post_init(self):
    GPIO.output(WebHandler.toGPIO_OUT[1], GPIO.LOW)
    GPIO.output(WebHandler.toGPIO_OUT[2], GPIO.LOW)
    GPIO.output(WebHandler.toGPIO_OUT[3], GPIO.HIGH)
    GPIO.output(WebHandler.toGPIO_OUT[4], GPIO.LOW) # Unused but safier

  def update_out_port(self, num, val):
    if not WebHandler.OutPortForce[num]:
      GPIO.output(WebHandler.toGPIO_OUT[num], val)

  def check_input_value(self, pin):
    print("input pin", pin, "value is", GPIO.input(pin))

  def check_if_won(self):
    flag = False
    input_1 = GPIO.input(WebHandler.toGPIO_IN[1])
    input_3 = GPIO.input(WebHandler.toGPIO_IN[3])
    input_4 = GPIO.input(WebHandler.toGPIO_IN[4])

    if (input_1 == 1 and input_3 == 0) or (input_1 == 0 and input_3 == 1):
      self.update_out_port(1, GPIO.LOW)
      self.update_out_port(2, GPIO.HIGH)
      self.update_out_port(3, GPIO.HIGH)
    elif (input_1 == 1 and GPIO.event_detected(WebHandler.toGPIO_IN[3])) or (GPIO.event_detected(WebHandler.toGPIO_IN[1]) and input_3 == 1):
      self.blink_event.set()
    elif (input_1 == 1 and input_3 == 1):
      pass
    elif input_4 == 1:
      os.system("sudo shutdown -r now")
    else:
      self.update_out_port(1, GPIO.HIGH)
      self.update_out_port(2, GPIO.LOW)
      self.update_out_port(3, GPIO.HIGH)

  def run(self):
    while True:
        self.ready2go.set()
        self.event.wait()
        self.ready2go.clear()
        self.init_room()
        #if not self.killed:
        #  timeout_timer = threading.Timer(3600.0, self.timeout)
        #  timeout_timer.start()
        while not self.stopped and not self.timedout and not self.killed:
          time.sleep(0.3)
          self.check_if_won()

        self.running = False

        #if not self.timedout:
        #  timeout_timer.cancel()

        self.post_init()
          
        self.event.clear()
        print("Game ends !")

        if self.killed:
            return
          

  def timeout(self):
    self.timedout = True

  def stop(self):
    self.stopped = True

  def kill(self):
    self.killed = True
    
####Fin Scenario##########################################

class ShutDown(Exception):
  pass
  
###########################################################
##
## Blink
##
class Blink(threading.Thread):

  #Thread chargé simplement de basculer la sortie pendant une seconde.
  def __init__(self, event):
    threading.Thread.__init__(self)
    self.event = event

  def run(self):
  #Code à exécuter pendant l'exécution du thread.
    while True:
      self.event.wait()
      GPIO.output(WebHandler.toGPIO_OUT[3], not GPIO.input(WebHandler.toGPIO_OUT[3]))
      time.sleep(1.5)
      GPIO.output(WebHandler.toGPIO_OUT[3], not GPIO.input(WebHandler.toGPIO_OUT[3]))
      self.event.clear()

####Fin Blink##########################################
    
import logging
import http.server
import socketserver
import urllib.parse
import os

import RPi.GPIO as GPIO


###########################################################
##
## Traitement des requetes
##

#LOCAL_WEB_ADDR = "127.0.0.1"
LOCAL_WEB_ADDR = "192.168.0.23"
WEB_PORT = 8000
WEB_ADDR = LOCAL_WEB_ADDR

class WebHandler(http.server.BaseHTTPRequestHandler):

  #Procedure permettant de retourner une reponse formatee JSON au client
  def response(self, json):
    self.send_response(200)
    self.send_header("Content-type", "application/json")
    self.end_headers()
    self.wfile.write(bytes(json, "UTF-8"))

  #Fonction d'obtention de la temperature du CPU
  def getCPUtemp(self):
    res = os.popen("vcgencmd measure_temp").readline()
    return(res.replace("temp=","").replace("'C\n",""))

  #Fonction d'obtention de l'espace memoire 1: Total, 2: Utilise, 3: Libre
  def getRAMinfo(self):
    p = os.popen('free')
    i = 0
    while True:
      i += 1
      line = p.readline()
      if i == 2:
        return(line.split()[1:4])

  #Fonction d'obtention de la charge du CPU
  def getCPUusage(self):
    return(str(os.popen("top -b -n 5 -d 0.2 | grep \"Cpu\" | awk 'NR==3{ print($2)}'").readline().strip().replace(",", ".")))

  #Fonction d'obtention de l'espace disque 1: Total, 2: Utilise, 3: Libre, 4: Pourcentage utilise
  def getDiskSpace(self):
    p = os.popen("df -m /")
    i = 0
    while True:
      i += 1
      line = p.readline()
      if i == 2:
        return(line.split()[1:5])  

##  def update_port(self, port):
##    if port in self.query_components:
##        port_num = int(port.replace("port", ""))
##        print("print num = ", port_num)
##        action = self.query_components[port][0]
##        if action == "ON" and self.Port[port_num] == "OFF":
##          self.Port[port_num] = "ON"
##          return True
##        elif action == "OFF" and self.Port[port_num] == "ON":
##          self.Port[port_num] = "OFF"
##          return True
##    return False

  def set_to_high(self, pin):
    print("setting pin output ", pin, " to high")
    GPIO.output(pin, GPIO.HIGH)

  def set_to_low(self, pin):
    print("setting pin output ", pin, " to low")
    GPIO.output(pin, GPIO.LOW)

  def update_port(self, num, dir, val):
    port_num = int(num)
    if dir == "in":
        if val == "ON" and self.InPort[port_num] == "OFF":
          self.InPort[port_num] = "ON"
          return True
        elif val == "OFF" and self.InPort[port_num] == "ON":
          self.InPort[port_num] = "OFF"
          return True
    elif dir == "out":
        if val == "ON":
          #self.OutPort[port_num] = "ON"
          self.set_to_high(self.toGPIO_OUT[port_num])
          self.OutPortForce[port_num] = True
          return True
        elif val == "OFF":
          #self.OutPort[port_num] = "OFF"
          self.set_to_low(self.toGPIO_OUT[port_num])
          self.OutPortForce[port_num] = True
          return True
        elif val == "RESET":
          self.OutPortForce[port_num] = False
          return True
    return False

  def start_game(self):
    log("Starting Game", 1)
    self.thread_event.set()

  def stop_game(self):
    log("Ending Game", 1)
    self.thread_event.clear()
    self.timer.stop()
    self.restart_game_event.wait()
        
  #Fonction appelee lors d'une requete http
  def do_GET(self):
    try:
      #Extraction des parametres
      qs = urllib.parse.urlparse(self.path).query
      query_components = urllib.parse.parse_qs(qs)
      self.query_components = query_components

      if "server" in query_components:
        action = query_components["server"][0]
        if action == "stop":
          self.response("{\"server\": \"shutting\"}")
          self.thread_event.set()
          self.timer.kill()
          self.timer.join()
          self.assassin.start()
          return

      if "game" in query_components:
        action = query_components["game"][0]
        if action == "restart":
          self.stop_game()
          self.start_game()
          self.response("{\"game\": \"restarted\"}")
          return
        if action == "start":
          self.start_game()
          self.response("{\"game\": \"launched\"}")
          return
        if action == "stop":
          self.stop_game()
          self.response("{\"game\": \"stopped\"}")
          return
        if action == "status":
          if self.timer.stopped:
            self.response("{\"game\": \"stopped\"}")
          elif self.timer.timedout:
            self.response("{\"game\": \"timed out\"}")
          elif self.timer.killed:
            self.response("{\"game\": \"killed\"}")
          elif self.timer.running:
            self.response("{\"game\": \"running\"}")
          else:
            self.response("{\"game\": \"not running\"}")
          return
        
      #Informations du systeme
      if "system" in query_components:
        action = query_components["system"][0]

        #Informations sur le systeme
        if action == "infos":
          CPU_temp = self.getCPUtemp()
          CPU_used = self.getCPUusage()
          RAM_infos = self.getRAMinfo()
          DISK_infos = self.getDiskSpace()

          RAM_total = round(int(RAM_infos[0]) / 1024, 1)
          RAM_used = round(int(RAM_infos[1]) / 1024, 1)
          RAM_free = round(int(RAM_infos[2]) / 1024, 1)

          DISK_total = round(int(DISK_infos[0]) / 1000, 1)
          DISK_free = round(int(DISK_infos[1]) / 1000, 1)
          DISK_used = round(int(DISK_infos[2]) / 1000, 1)
          DISK_perc = DISK_infos[3][:-1]

          self.response("""
          {{
            "cpu\" :
            {{
              \"used\" : \"{0}\",
              \"temp\" : \"{1}\"
            }},

            \"memory\" :
            {{
              \"used\" : \"{2}\",
              \"total\" : \"{3}\",
              \"free\" : \"{4}\"
            }},
            \"disk\" :
            {{
              \"used\" : \"{5}\",
              \"total\" : \"{6}\",
              \"free\" : \"{7}\",
              \"perc\" : \"{8}\"
            }}
          }}""".format(CPU_used, CPU_temp, RAM_used, RAM_total, RAM_free, DISK_used, DISK_total, DISK_free, DISK_perc))
          return

      if "port" in query_components:
        changed = self.update_port(query_components["port"][0], query_components["dir"][0], query_components["val"][0])
        if changed:
          self.response("{\"answer\": \"port changes ok\"}")
        else:
          self.response("{\"answer\": \"no port change\"}")
        return

      #Requete concernant le statut
      if "all" in query_components:
        action = query_components["all"][0]

        #Statut des Ports
        if action == "status":

          in_port1 = GPIO.input(self.toGPIO_IN[1])
          in_port2 = GPIO.input(self.toGPIO_IN[2])
          in_port3 = GPIO.input(self.toGPIO_IN[3])
          in_port4 = GPIO.input(self.toGPIO_IN[4])

          out_port1 = GPIO.input(self.toGPIO_OUT[1])
          out_port2 = GPIO.input(self.toGPIO_OUT[2])
          out_port3 = GPIO.input(self.toGPIO_OUT[3])
          out_port4 = GPIO.input(self.toGPIO_OUT[4])

          self.response("""
          {{
            \"in_port1\" : \"{0}\",
            \"in_port2\" : \"{1}\",
            \"in_port3\" : \"{2}\",
            \"in_port4\" : \"{3}\",
            \"out_port1\" : \"{4}\",
            \"out_port2\" : \"{5}\",
            \"out_port3\" : \"{6}\",
            \"out_port4\" : \"{7}\"
          }}""".format(in_port1, in_port2, in_port3, in_port4, out_port1, out_port2, out_port3, out_port4))
          return

      #Requete invalide
      log("Invalid query", 1)
      self.response("{\"error\": \"Invalid query\"}")
    except Exception as ex:
      log(ex, 2)
      pass
    return
    
####Fin Traitement des requêtes###########################
class ThreadingServer(socketserver.ThreadingMixIn, http.server.HTTPServer):
  pass

def GPIO_Init():
  GPIO.cleanup()
  GPIO.setmode(GPIO.BCM)

  print("Changing configuration")
  GPIO.setup(4, GPIO.IN)
  GPIO.setup(17, GPIO.IN)
  GPIO.setup(27, GPIO.IN)
  GPIO.setup(22, GPIO.IN)
        
  GPIO.setup(5, GPIO.OUT)
  GPIO.output(5, GPIO.LOW)
  GPIO.setup(6, GPIO.OUT)
  GPIO.output(6, GPIO.LOW)
  GPIO.setup(13, GPIO.OUT)
  GPIO.output(13, GPIO.LOW)
  GPIO.setup(19, GPIO.OUT)
  GPIO.output(19, GPIO.LOW)
  
############################################################
## MAIN method
##
if __name__ == "__main__":
  GPIO_Init()
  
  #Initialisation du journal
  logger = logging.getLogger(LOG_NAME)
  hdlr = logging.FileHandler(LOG_PATH)
  formatter = logging.Formatter(LOG_FORMAT)
  hdlr.setFormatter(formatter)
  logger.addHandler(hdlr)

  WebHandler.InPort = ["IN Ports status", "OFF", "OFF", "OFF", "OFF"]
  WebHandler.OutPort = ["OUT Ports status", "OFF", "OFF", "OFF", "OFF"]
  WebHandler.OutPortForce = ["OUT Ports status", False, False, False, False]

  WebHandler.toGPIO_IN = ["IN Ports matching", 4, 17, 27, 22]
  WebHandler.toGPIO_OUT = ["OUT Ports matching", 19, 13, 6, 5]

  WebHandler.thread_event = threading.Event()
  WebHandler.thread_event.clear()
  WebHandler.timer = Game(WebHandler.thread_event)
  WebHandler.timer.start()
  WebHandler.restart_game_event = WebHandler.timer.ready2go
  thread_1 = Blink(WebHandler.timer.blink_event)
  thread_1.start()
  log("Starting Room Server")

  #Parametres du serveur HTTP
  server_address = (WEB_ADDR, WEB_PORT)
  try:
    #Instanciation du serveur HTTP
    httpd = ThreadingServer(server_address, WebHandler)
    WebHandler.assassin = threading.Thread(target=httpd.shutdown)
    WebHandler.assassin.daemon = True
    httpd.serve_forever()
  except KeyboardInterrupt:
    log("Shutting down server")
    WebHandler.timer.kill()
    WebHandler.thread_event.set()
    WebHandler.timer.join()
    thread_1.join()
    httpd.socket.close()
    hdlr.close()
    GPIO.cleanup()