#!/usr/bin/python
# coding: utf-8
#
#    lirc_domo.py 
#
#  Python 2.7 script to convert IR codes to http command to
#  toggle lamps on or off with Domoticz
#
#  Does not work in Python 3.
#
#  Based on pylirc_test.py by Linus McCabe
#  http://pylirc.mccabe.nu/
# 
#  2019/02/04 21:30 Michel Deslierres
#
import pylirc
import time
import urllib

blocking       = 0;  # set to 0 for non blocking operation
url_json       = "http://192.168.0.22:8080/json.htm?type=command&param=switchlight&idx="
toggle_json    = "&switchcmd=Toggle"
lampe_charline = 5
lampe_michel   = 6

if(pylirc.init("pylirc", "pylirc.conf", blocking)):

   code = {"config" : ""}
   while(code["config"] != "quit"):

      # Very intuitive indeed
      if(not blocking):
         print(".")

         # Delay...
         time.sleep(1)

      # Read next code
      s = pylirc.nextcode(1)

      # Loop as long as there are more on the queue
      # (dont want to wait a second if the user pressed many buttons...)
      while(s):
         
         # Print all the configs...
         for (code) in s:
         
            cmd = ''
            print("Command: %s, Repeat: %d" % (code["config"], code["repeat"]))
            
            if(code["config"] == "1"):
               cmd = url_json  + str(lampe_charline)

            elif(code["config"] == "2"):
               cmd = url_json  + str(lampe_charline)

            if cmd != '':
              cmd = cmd + toggle_json
              hf = urllib.urlopen(cmd)
              print('URL JSON pour Domoticz: ' + cmd)
              print('Réponse: ' + hf.read())
              hf.close
              
         # Read next code?
         if(not blocking):
            s = pylirc.nextcode(1)
         else:
            s = []

   # Clean up lirc
   pylirc.exit()

