2 Replies Latest reply on Jan 18, 2014 12:52 PM by arthuz

    PIFACECAD : how to handle keys events btw 2 scripts ?

    arthuz

      Hi all,

       

      Proud new owner of a PiFace CAD, I'm trying to create a script that would "rule them all"... like a tiny OS... I explain

      I'm trying to create a main script that would give a "menu like interface" using the Question Method, easily understandable and useable by new comers (like myself).

       

      What I'm trying to achieve with this little project is to be able to use some of the exemples given with the PiFaceCAD (Sysinfo, hangman, weather, tweets...),

      with an interface that could be ran straigth out of the box and easily understandable (clear & commented) so it could be tweaked and modified with no knowledge of python.

       

      So the project (at least that's how I see it, I may be wrong), would be centered around a main scrypt (the "OS", here called MainExecute.py) that would display the menu like interface,

      handle some keys events and launch other scripts/shell commands.

       

      here is the code of MainExecute.py (the main script)...

       

      #!/usr/bin/env python3
      
      import subprocess
      import pifacecad
      import sys
      PY3 = sys.version_info[0] >= 3
      if not PY3:
          print("The script only works with `python3`, try using `python3 MainExecute.py`.")
          sys.exit(1)
      
      from time import sleep
      from pifacecad.tools.question import LCDQuestion
      
      cad = pifacecad.PiFaceCAD()
      
      GET_IP_CMD = "hostname --all-ip-addresses"
      GET_INFOS_CMD = "python3 sysinfo.py"
      
      def run_cmd(cmd):
          return subprocess.check_output(cmd, shell=True).decode('utf-8')
      
      def get_my_ip():
          return run_cmd(GET_IP_CMD)[:-1]
      
      def get_infos():
      ##    listener.deactivate()
          return run_cmd (GET_INFOS_CMD)
      
      
      if __name__ == "__main__":
          
              question = LCDQuestion(question="What do u want?",answers=('My IP','Sys Infos','Hangman', 'Exit'))
      
              while True:
                  answer_index = question.ask()
              
                  if answer_index == 0:
                      cad.lcd.clear()
                      cad.lcd.write("{}\n".format(get_my_ip()))
                      sleep(5)
                           
                  if answer_index == 1:            
                      cad.lcd.clear()
                      get_infos()
                           
                  else:
                      cad.lcd.clear()
                      cad.lcd.write("ByeBye")
                      print("Byebye")
      
      
      
      

       

      (since I'm not a programmer, I made this script by taking bits and pieces from different scripts found online, so this code isnt clean neither optimised, if you feel like "touching it up" to make it all nice and clean, feel free to do so )

       

      so far, so good... the script launches, the shell commands work, I can get the IP, launch the Sysinfo script, navigate through the menu using the rocking switch BUT

      I can't get the keys events interupts from button 0 to 3 to work properly (I've cleaned up the code of my "attempts" in the sake of readibility).

       

      Here is the SysInfos.py script that's called by MainExecute.py (it's the just a slightly modified version of the script given as an exemple with the PifaceCAD...)

       

      #!/usr/bin/env python3
      import sys
      import subprocess
      import pifacecad
      from time import sleep
      ##from threading import Barrier ## I was messing aroung with barrier to see what it does, havent figured it out yet... :/
      
      cad = pifacecad.PiFaceCAD()
      
      UPDATE_INTERVAL = 10  # 60 * 5 = 5 mins
      GET_IP_CMD = "hostname --all-ip-addresses"
      GET_TEMP_CMD = "/opt/vc/bin/vcgencmd measure_temp"
      TOTAL_MEM_CMD = "free | grep 'Mem' | awk '{print $2}'"
      USED_MEM_CMD = "free | grep '\-\/+' | awk '{print $3}'"
      
      temperature_symbol = pifacecad.LCDBitmap(
          [0x4, 0x4, 0x4, 0x4, 0xe, 0xe, 0xe, 0x0])
      memory_symbol = pifacecad.LCDBitmap(
          [0xe, 0x1f, 0xe, 0x1f, 0xe, 0x1f, 0xe, 0x0])
      temp_symbol_index, memory_symbol_index = 0, 1
      
      def run_cmd(cmd):
          return subprocess.check_output(cmd, shell=True).decode('utf-8')
      
      def get_my_ip():
          return run_cmd(GET_IP_CMD)[:-1]
      
      def get_my_temp():
          return run_cmd(GET_TEMP_CMD)[5:9]
      
      def get_my_free_mem():
          total_mem = int(run_cmd(TOTAL_MEM_CMD))
          used_mem = int(run_cmd(USED_MEM_CMD))
          mem_perc = used_mem / total_mem
          return "{:.1%}".format(mem_perc)
      
      def wait_for_ip():
          ip = ""
          while len(ip) <= 0:
              sleep(1)
              ip = get_my_ip()
      
      def show_sysinfo():
          while True:
              cad.lcd.clear()
              cad.lcd.write("{}\n".format(get_my_ip()))
              cad.lcd.write_custom_bitmap(temp_symbol_index)
              cad.lcd.write(":{}C ".format(get_my_temp()))
              cad.lcd.write_custom_bitmap(memory_symbol_index)
              cad.lcd.write(":{}".format(get_my_free_mem()))
              sleep(UPDATE_INTERVAL)
      ##        sys.exit(0) ## doesnt quits the script, doesnt work 
      
      if __name__ == "__main__":
          cad.lcd.blink_off()
          cad.lcd.cursor_off()
      
          if "clear" in sys.argv:
              cad.lcd.clear()
              cad.lcd.display_off()
              cad.lcd.backlight_off()
          else:
              cad.lcd.store_custom_bitmap(temp_symbol_index, temperature_symbol)
              cad.lcd.store_custom_bitmap(memory_symbol_index, memory_symbol)
              cad.lcd.backlight_on()
              cad.lcd.write("Waiting for IP..")
              wait_for_ip()
              show_sysinfo()
      
      
      
      

       

      So, here are the reasons why I come before you :

       

      I'd like to be able to use button 4 as a "quit/go back to menu" button (quits whatever the script is doing and go back to the begin of MainExecute.py) from "anywhere" (from a shell command acting like a CTRL+C, from another script... ).

      And I'd like to be able to use buttons from 0 to 3, depending on the need of the running script/shell command (a press on btn0 would display the ipV6 adress when running the IP shell command, or would display some other infos while running SysInfos.py, for exemple...)

       

      Sorry for the long thread, I could have summit it in few words by saying "I have 2 scripts, and I'd like to be able to quit 1 to go to the other by a press of a button", but I thought that giving you the whole picture would be better

       

      thanks in advance all

       

      AP

        • Re: PIFACECAD : how to handle keys events btw 2 scripts ?
          ragapack

          Hi Alain,

           

          I did this with 2 while loops of the LCDQuestion tool.

           

          The first

          Mquestion = LCDQuestion(question="Auswahl:",answers=('Drucken','Testdruck','Neustart','Beenden'),selector='#',cad=cad)
          while True:
              main_index = Mquestion.ask()
          

           

          and this way I go out of the first loop and shutdown.

          if main_index == 3:
                      cad.lcd.clear()
                      cad.lcd.write("Schalte Aus!!")
                      cad.lcd.backlight_off()
                      sleep(1)
                      cad.lcd.backlight_on()
                      sleep(1)
                      cad.lcd.backlight_off()
                      cad.lcd.clear()
                      cad.lcd.display_off()
                      shutdown()
                      break
          

           

          Inside this I have a second loop, where I read files_list from an USB stick to print out on my Kiosk Printer.

          Pquestion = LCDQuestion(question="Auswahl Drucken:",answers= file_list,selector='>',cad=cad)
          

           

          The second while loop can depend until a key is pressed and you make a break and go back to the main menue.

           

          The LCDQuestion is linked to the 3 switches 5,6 and 7 .of the 3-position navigation switch.

          https://github.com/piface/pifacecad/blob/master/pifacecad/tools/question.py

           

           

          # wait for user input
                  listener = pifacecad.SwitchEventListener(self.cad)
                  listener.register(7, pifacecad.IODIR_ON, self.next_answer)
                  listener.register(6, pifacecad.IODIR_ON, self.previous_answer)
                  listener.register(5,
                                    pifacecad.IODIR_ON,
                                    self.select_answer_switch_pressed)

           

           

          So if we want to change the the buttons used we can do this here.

          Better I think is to change the question.py to overwrite the 3 key numbers

           

          def__init__(self,question,answers,selector=">",cad=None, switch_pressed=5, previous_answer=6, next_answer=7 ):
                  self.question = question
                  self.answers = answers
                  self.selector = selector
                  self.switch_pressed= switch_pressed
          
                  self.previous_answer= previous_answer
          
                  self.next_answer=next_answer
          


          And the user input

           

          # wait for user input
                  listener = pifacecad.SwitchEventListener(self.cad)
                  listener.register(next_answer, pifacecad.IODIR_ON, self.next_answer)
                  listener.register(previous_answer, pifacecad.IODIR_ON, self.previous_answer)
                  listener.register(switch_pressed,
                                    pifacecad.IODIR_ON,
          self.select_answer_switch_pressed)

           

          If you have any more ideas please let me know.

           

          Thomas