def mea_xplCmndMsg(data):

   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

   try:
      id_actuator=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   try:
      device_name=data["device_name"]
      interface_id=data["interface_id"]
      typeoftype=data["typeoftype"]
      api_key=data["api_key"]
      parameters=data["device_parameters"]
      parameters=parameters.strip().lower()
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   except:
      verbose(2, "ERROR (", fn_name, ") - parameters error")
      return False

   mem_actuator=mea.getMemory(id_actuator)
   mem_interface=mea.getMemory("interface"+str(interface_id))

   return True
def mea_dataFromSensor(data):
   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

#   verbose(9, "DEBUG (", fn_name, ") data = ", data)

   try:
      device_id=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   try:
      device_name=data["device_name"]
      interface_id=data["interface_id"]
      api_key=data["api_key"]
      typeoftype=data["typeoftype"]
      parameters=data["device_parameters"]
      parameters=parameters.strip().lower()
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem_device=mea.getMemory(device_id)
   mem_interface=mea.getMemory("interface"+str(interface_id))

   else:
Exemplo n.º 3
0
def mea_dataFromSensor(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    try:
        device_id = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
        api_key = data["api_key"]

    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    if not "value" in params:
        verbose(2, "ERROR (", fn_name, ") - no value parameter")
        return False

    value = params["value"]

    mem_device = mea.getMemory(device_id)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    pdata = mea_utils.parseKeyValueDatasToDictionary(
        str(data['data']).strip().lower(), ";", "=")

    if value in pdata:
        v = pdata[value]
        f = 0.0
        if type(v) == str:
            try:
                f = float(v)
            except:
                return False

            mem_device["current"] = f

            mea.addDataToSensorsValuesTable(device_id, f, 0, 0, "")

            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor",
                                         "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", str(f))
            mea.xplSendMsg(xplMsg)


#         mea.interfaceAPI(api_key, "mea_writeData", "{{{OK}}}")

        else:
            return -1
Exemplo n.º 4
0
def mea_dataFromSensor(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    try:
        device_id = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
        api_key = data["api_key"]

    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    if not "value" in params:
        verbose(2, "ERROR (", fn_name, ") - no value parameter")
        return False

    value = params["value"]

    mem_device = mea.getMemory(device_id)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    pdata = mea_utils.parseKeyValueDatasToDictionary(
        str(data['data']).strip().lower(), ";", "=")

    if value in pdata:
        v = pdata[value].lower()
        f = 0
        if type(v) == str:
            try:
                f = float(v)
            except:
                if v in ["on", "off", "high", "low", "true", "false"]:
                    f = v
                else:
                    return False
            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor",
                                         "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", str(f))
            mea.xplSendMsg(xplMsg)

            mea.interfaceAPI(api_key, "mea_writeData",
                             "[[[" + device_name + "!OK]]]\n")
            return True
    return False
Exemplo n.º 5
0
def mea_dataFromSensor(data):
   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

   try:
      device_id=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   try:
      device_name=data["device_name"]
      interface_id=data["interface_id"]
      parameters=data["device_parameters"]
      parameters=parameters.strip().lower()
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
      typeoftype=data["typeoftype"]
      api_key=data["api_key"]

   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   if not "value" in params:
      verbose(2, "ERROR (", fn_name, ") - no value parameter")
      return False

   value = params["value"]
 
   mem_device=mea.getMemory(device_id)
   mem_interface=mea.getMemory("interface"+str(interface_id))

   pdata = mea_utils.parseKeyValueDatasToDictionary(str(data['data']).strip().lower(),";","=")

   if value in pdata:
      v = pdata[value]
      f = 0.0
      if type(v) == str:
         try:
            f=float(v)
         except:
            return False

         mem_device["current"]=f

         mea.addDataToSensorsValuesTable(device_id, f, 0,0,"")

         xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
         mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
         mea_utils.xplMsgAddValue(xplMsg, "current", str(f))
         mea.xplSendMsg(xplMsg)

#         mea.interfaceAPI(api_key, "mea_writeData", "{{{OK}}}")
 
      else:
         return -1
Exemplo n.º 6
0
def mea_dataFromSensor(data):
   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

#   verbose(9, fn_name, "data=", data)
   try:
      id_actuator=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   try:
      serial_data=data["data"]
   except:
      return False
   try:
      s=serial_data.decode('latin-1')
   except:
      return False

   mem_actuator=mea.getMemory(id_actuator)
#   verbose(9, fn_name, "mem_actuator=", mem_actuator)
   if not 'msg' in mem_actuator or mem_actuator['msg']==False:
      return True

   now=int(round(time() * 1000))
   if 'chrono' in mem_actuator and mem_actuator['chrono'] <> False:
      if now -  mem_actuator['chrono'] < 5000:  
         if s.find(u"\r\n> ") >=0:
            mea.sendSerialData(data['fd'], bytearray(mem_actuator['msg']+"\r\n"+chr(26)))
            mem_actuator['msg']==False
            mem_actuator['chrono']=False
      else:
         mem_actuator['chrono']=False
         mem_actuator['msg']==False
def mea_xplCmndMsg(data):
   fn_name=sys._getframe().f_code.co_name
   try:
      id_sensor=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return 0

   mem=mea.getMemory(id_sensor)

   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   if x["schema"]=="sensor.request":
      try:
         xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
         mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
         if body["request"]=="current":
            mea_utils.xplMsgAddValue(xplMsg,"current",mem["current"])
         elif body["request"]=="last":
            mea_utils.xplMsgAddValue(xplMsg,"last",mem["last"])
         else:
            verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
            return False
         mea_utils.xplMsgAddValue(xplMsg,"type","input")
         mea.xplSendMsg(xplMsg)
         return True
      except:
         verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
         return False
   return False
Exemplo n.º 8
0
def mea_init(data):
   fn_name=sys._getframe().f_code.co_name
   
   verbose(9,"INFO  (",fn_name,") - lancement mea_init")
   
   if "interface_parameters" in data:
      mem={}
      try:
         mem=mea.getMemory(data["interface_id"])
      except:
         verbose(2, "ERROR (", fn_name, ") - can't acces share memory")
         return False
      
      paramsList=mea_utils.parseKeyValueDatasToList(data["interface_parameters"], ",", ":")
      if paramsList != None:
         for i in paramsList:
            numVal=-1;
            alphaVal="";
            
            if i[0][0] !="@":
               verbose (3, "ERROR (", fn_name, ") - syntaxe error :", i[0], "not an AT command, skipped")
               continue
            
            if i[1]!=None:
               if i[1][0:2]=="0x":
                  try:
                     numVal=int(i[1],16)
                  except:
                     alphaVal=i[1]
               else:
                  try:
                     numVal=int(i[1],10)
                  except:
                     alphaVal=i[1]
               # commande AT ?
               if len(i[0])==3:
                  if numVal>=0: # commande at avec parametre numerique
                     ret=mea.sendXbeeCmd(data["ID_XBEE"], -1, -1, i[0][1:3].upper(), numVal);
                     if ret == 0:
                        verbose(5, "WARNING (", fn_name, ") - Transmission error for", i[0], "= ", numVal)
                  else: # commande at avec parametre alpha-numerique
                     ret=mea.sendXbeeCmd(data["ID_XBEE"], -1, -1, i[0][1:3].upper(), alphaVal);
                     if ret == 0:
                        verbose(5, "WARNING (", fn_name, ") - Transmission error for", i[0], "= ", alphaVal)
               else:
                  verbose(5, "WARNING (", fn_name, ") - syntaxe error :", i[0], "not an at cmnd, skip")
            else:
               if len(i[0])==3: # commande at sans parametre
                  ret=mea.sendXbeeCmd(data["ID_XBEE"], -1, -1, i[0][1:3].upper(), "");
                  if ret == 0:
                     verbose(3, "ERROR (", fn_name, ") - Transmission error for", i[0], "= ", numVal)
         return True
      
      else:
         return False
   else:
      return False
Exemplo n.º 9
0
def mea_xplCmndMsg(data):

    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    verbose(9, "DEBUG (", fn_name, ") data = ", data)

    try:
        id_actuator = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
        api_key = data["api_key"]

    except:
        verbose(2, "ERROR (", fn_name, ") - parameters error")
        return False

    mem_actuator = mea.getMemory(id_actuator)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    x = data["xplmsg"]
    body = x["body"]

    target = "*"
    if "source" in x:
        target = x["source"]

    if x["schema"] == "control.basic":
        try:
            cmnd = params["cmnd"]
        except:
            verbose(2, "ERROR (", fn_name, ") - no cmnd")
            return False

        _cmnd = [cmnd]
        p = subprocess.Popen(_cmnd)
Exemplo n.º 10
0
def mea_xplCmndMsg(data):

   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

   verbose(9, "DEBUG (", fn_name, ") data = ", data)

   try:
      id_actuator=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   try:
      device_name=data["device_name"]
      interface_id=data["interface_id"]
      parameters=data["device_parameters"]
      parameters=parameters.strip().lower()
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
      typeoftype=data["typeoftype"]
      api_key=data["api_key"]

   except:
      verbose(2, "ERROR (", fn_name, ") - parameters error")
      return False

   mem_actuator=mea.getMemory(id_actuator)
   mem_interface=mea.getMemory("interface"+str(interface_id))

   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   if x["schema"]=="control.basic":
      try:
         cmnd=params["cmnd"];
      except:
         verbose(2, "ERROR (", fn_name, ") - no cmnd")
         return False

      _cmnd=[cmnd]
      p = subprocess.Popen(_cmnd)
Exemplo n.º 11
0
def mea_xplCmndMsg(data):
    fn_name = str(sys._getframe().f_code.co_name) + "/" + __name__

    verbose(9, fn_name, " data=", data)

    try:
        id_actuator = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    mem_actuator = mea.getMemory(id_actuator)
    verbose(9, fn_name, " mem_actuator=", mem_actuator)

    # premier passage, pas encore de msg
    if not 'chrono' in mem_actuator or not 'msg' in mem_actuator:
        mem_actuator['chrono'] = False
        mem_actuator['msg'] = False

    # le dernier message n'a pas encore été envoyé après 5 secondes
    if mem_actuator['chrono'] != False:
        now = int(round(time() * 1000))
        if now - mem_actuator['chrono'] > 5000:
            mem_actuator['chrono'] = False
            mem_actuator['msg'] = False

    if mem_actuator['msg'] != False and mem_actuator[
            'chrono'] != False:  # un sms est déjà en cours d'envoi, on ne peut traiter qu'un seul à la fois
        return False

    # récupération des données xpl
    try:
        x = data["xplmsg"]
        body = x["body"]
        schema = x["schema"]
    except:
        return False

    if schema == "sendmsg.basic":
        try:
            msg = str(body["body"])
            to = str(body["to"])
        except:
            verbose(2, "ERROR - (", fn_name, ") : bad data")
            return False

        mea.sendSerialData(data['fd'], bytearray("AT+CMGS=\"" + to + "\"\r\n"))
        mem_actuator['msg'] = msg
        mem_actuator['chrono'] = int(round(time() * 1000))

        return True
    else:
        return False
    return False
Exemplo n.º 12
0
def mea_xplCmndMsg(data):
   fn_name=str(sys._getframe().f_code.co_name) + "/" + __name__

   verbose(9, fn_name," data=",data)

   try:
      id_actuator=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return False

   mem_actuator=mea.getMemory(id_actuator)
   verbose(9, fn_name," mem_actuator=",mem_actuator)

   # premier passage, pas encore de msg
   if not 'chrono' in mem_actuator or not 'msg' in mem_actuator: 
      mem_actuator['chrono']=False
      mem_actuator['msg']=False


   # le dernier message n'a pas encore été envoyé après 5 secondes
   if mem_actuator['chrono']<>False:
      now=int(round(time() * 1000))
      if now - mem_actuator['chrono'] > 5000:
         mem_actuator['chrono']=False
         mem_actuator['msg']=False

   if mem_actuator['msg']!=False and mem_actuator['chrono']!=False: # un sms est déjà en cours d'envoi, on ne peut traiter qu'un seul à la fois
      return False

   # récupération des données xpl
   try:
      x=data["xplmsg"]
      body=x["body"]
      schema=x["schema"]
   except:
      return False

   if schema=="sendmsg.basic":
      try:
         msg=str(body["body"])
         to=str(body["to"])
      except:
         verbose(2, "ERROR - (", fn_name, ") : bad data")
         return False

      mea.sendSerialData(data['fd'], bytearray("AT+CMGS=\""+to+"\"\r\n"))
      mem_actuator['msg']= msg
      mem_actuator['chrono']=int(round(time() * 1000))

      return True
   else:
      return False
   return False
Exemplo n.º 13
0
def mea_init(data):
    fn_name = sys._getframe().f_code.co_name

    verbose(9, "INFO  (", fn_name, ") - lancement mea_init")

    try:
        interface_id = data["interface_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_interface = mea.getMemory("interface_" + str(interface_id))

    return {"status": True, "msg": "un texte"}
Exemplo n.º 14
0
def mea_dataFromSensor(data):
   fn_name=sys._getframe().f_code.co_name

   try:
      id_sensor=data["device_id"]
      verbose(1, "DEBUG (", fn_name, ") - id_sensor=", id_sensor)
      packet=data["data"]
      l_packet=data["l_data"]
      parameters=data["device_parameters"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem=mea.getMemory(id_sensor)
   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   current=""
   try:
      device=paramsDict["xpldevice"];
   except:
      device=-1;

   if packet[4]==1: # ENOCEAN_RADIO_ERP1
      if packet[6]==0xD2:
         if (packet[7] & 0b00001111) == 4: # reception packet status
            try:
               if (paramsDict["channel"]=="A" and (packet[8] & 0b00011111) == 0) or (paramsDict["channel"]=="B" and (packet[8] & 0b00011111) == 1): 
                  if (packet[9] & 0b01111111) == 0:
                     current='low'
                  else:
                     current='high'
            except:
               return False 

            if current != "":
               try:
                  mem["last"]=mem["current"]
               except:
                  mem["last"]=False
               mem["current"]=current

               xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
               mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
               mea_utils.xplMsgAddValue(xplMsg,"current", mem["current"])
               mea_utils.xplMsgAddValue(xplMsg,"type", "input")
               mea_utils.xplMsgAddValue(xplMsg,"last", mem["last"])
               mea.xplSendMsg(xplMsg)

               return True
   return False
Exemplo n.º 15
0
def mea_dataFromSensor(data):
   fn_name=sys._getframe().f_code.co_name

   try:
      id_sensor=data["device_id"]
      verbose(1, "DEBUG (", fn_name, ") - id_sensor=", id_sensor)
      packet=data["data"]
      l_packet=data["l_data"]
      parameters=data["device_parameters"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem=mea.getMemory(id_sensor)
   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   current=""
   try:
      device=paramsDict["xpldevice"];
   except:
      device=-1;

   if packet[4]==1: # ENOCEAN_RADIO_ERP1
      if packet[6]==0xD2:
         if (packet[7] & 0b00001111) == 4: # reception packet status
            try:
               if (paramsDict["channel"]=="A" and (packet[8] & 0b00011111) == 0) or (paramsDict["channel"]=="B" and (packet[8] & 0b00011111) == 1): 
                  if (packet[9] & 0b01111111) == 0:
                     current='low'
                  else:
                     current='high'
            except:
               return False 

            if current != "":
               try:
                  mem["last"]=mem["current"]
               except:
                  mem["last"]=False
               mem["current"]=current

               xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
               mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
               mea_utils.xplMsgAddValue(xplMsg,"current", mem["current"])
               mea_utils.xplMsgAddValue(xplMsg,"type", "input")
               mea_utils.xplMsgAddValue(xplMsg,"last", mem["last"])
               mea.xplSendMsg(xplMsg)

               return True
   return False
Exemplo n.º 16
0
def mea_init(data):
   fn_name=sys._getframe().f_code.co_name

   verbose(9,"INFO  (", fn_name, ") - lancement mea_init")

   try:
      interface_id=data["interface_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem_interface=mea.getMemory("interface_"+str(interface_id))

   return True
Exemplo n.º 17
0
def mea_init(data):
   fn_name=sys._getframe().f_code.co_name

   verbose(9,"INFO  (", fn_name, ") - lancement mea_init")

   try:
      interface_id=data["interface_id"]
      api_key=data["api_key"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem_interface=mea.getMemory("interface"+str(interface_id))

   return init_devices(api_key, mea_getInterface(interface_id))
Exemplo n.º 18
0
def mea_updateDevices(data):
   fn_name= __name__ + "/" + str(sys._getframe().f_code.co_name)

   verbose(9, data)
   try:
      interface_id=data["interface_id"]
      api_key=data["api_key"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem_interface=mea.getMemory("interface"+str(interface_id))

   retour=True

   return retour
Exemplo n.º 19
0
def mea_init(data):
    fn_name = sys._getframe().f_code.co_name

    verbose(9, "INFO  (", fn_name, ") - lancement mea_init v2")

    try:
        interface_id = data["interface_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_interface = mea.getMemory("interface" + str(interface_id))
    for i in range(0, 10):
        mem_interface[i] = {}

    return True
Exemplo n.º 20
0
def mea_xplCmndMsg(data):
    fn_name = sys._getframe().f_code.co_name
    try:
        id_sensor = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return 0

    mem = mea.getMemory(id_sensor)

    x = data["xplmsg"]
    body = x["body"]

    target = "*"
    if "source" in x:
        target = x["source"]

    if x["schema"] == "sensor.request":
        try:
            xplMsg = mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor",
                                         "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device",
                                     data["device_name"].lower())
            if body["request"] == "current":
                mea_utils.xplMsgAddValue(xplMsg, "current", mem["current"])
            elif body["request"] == "last":
                mea_utils.xplMsgAddValue(xplMsg, "last", mem["last"])
            else:
                verbose(2, "ERROR (", fn_name, ") - invalid request (",
                        body["request"], ")")
                return False
            mea_utils.xplMsgAddValue(xplMsg, "type", "input")
        except:
            verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
            return False

        mea.xplSendMsg(xplMsg)
        return True

    return False
def mea_xplCmndMsg(data):
   fn_name=str(sys._getframe().f_code.co_name) + "/" + __name__

   # récupération des données xpl
   try:
      x=data["xplmsg"]
      body=x["body"]
      schema=x["schema"]
   except:
      return False

   try:
      id_sensor=data["device_id"]
   except:
      verbose(2, "ERROR - (", fn_name, ") : no device id")
      return False
   mem=mea.getMemory(id_sensor)

   if schema=="sensor.request":
      target="*"
      if "source" in x:
         target=x["source"]

      try:
         value=mem[body['request']]
      except:
         verbose(2, "ERROR - (", fn_name, ") : ", body['request'], " data not found")
         return False

      xplMsg=mea_utils.xplMsgNew('me', target, "xpl-stat", "sensor", "basic")
      mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
      mea_utils.xplMsgAddValue(xplMsg, body['request'], value)
      mea.xplSendMsg(xplMsg)
      return True

   return False
Exemplo n.º 22
0
def mea_xplCmndMsg(data):
   fn_name=str(sys._getframe().f_code.co_name) + "/" + __name__

   # récupération des données xpl
   try:
      x=data["xplmsg"]
      body=x["body"]
      schema=x["schema"]
   except:
      return False

   try:
      id_sensor=data["device_id"]
   except:
      verbose(2, "ERROR - (", fn_name, ") : no device id")
      return False
   mem=mea.getMemory(id_sensor)

   if schema=="sensor.request":
      target="*"
      if "source" in x:
         target=x["source"]

      try:
         value=mem[body['request']]
      except:
         verbose(2, "ERROR - (", fn_name, ") : ", body['request'], " data not found")
         return False

      xplMsg=mea_utils.xplMsgNew('me', target, "xpl-stat", "sensor", "basic")
      mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
      mea_utils.xplMsgAddValue(xplMsg, body['request'], value)
      mea.xplSendMsg(xplMsg)
      return True

   return False
Exemplo n.º 23
0
def mea_dataFromSensor(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    #   verbose(9, fn_name, "data=", data)
    try:
        id_actuator = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        serial_data = data["data"]
    except:
        return False
    try:
        s = serial_data.decode('latin-1')
    except:
        return False

    mem_actuator = mea.getMemory(id_actuator)
    #   verbose(9, fn_name, "mem_actuator=", mem_actuator)
    if not 'msg' in mem_actuator or mem_actuator['msg'] == False:
        return True

    now = int(round(time() * 1000))
    if 'chrono' in mem_actuator and mem_actuator['chrono'] != False:
        if now - mem_actuator['chrono'] < 5000:
            if s.find(u"\r\n> ") >= 0:
                mea.sendSerialData(
                    data['fd'],
                    bytearray(mem_actuator['msg'] + "\r\n" + chr(26)))
                mem_actuator['msg'] == False
                mem_actuator['chrono'] = False
        else:
            mem_actuator['chrono'] = False
            mem_actuator['msg'] == False
Exemplo n.º 24
0
def mea_dataFromSensor(data):
    xplMsg = {}
    try:
        id_type = data["device_type_id"]
        id_sensor = data["device_id"]
        cmd = data["cmd"]
    except:
        verbose(2, "ERROR - (mea_dataFromSensor) : data not found")
        return False

    verbose(9, "INFO  (mea_dataFromSensor) : data from ", id_sensor)

    mem = mea.getMemory(id_sensor)

    if debug == 1:
        verbose(9, "INFO - (mea_dataFromSensor) : ", mem)

    # voir http://www.tutorialspoint.com/python/python_reg_expressions.htm pour match
    x = re.match("^\s*<(.*)>\s*$", cmd[12:-2])
    if (x != None):
        t = x.group(1)
        list = t.split(';')
    else:
        verbose(5, "WARNING - (mea_dataFromSensor) : data error (", cmd[12:-2],
                ")")
        return False

    for i in list:
        l2 = i.split('=')

        # traitement Humidite
        if id_type == 2000 and l2[0] == 'H':
            humidite = float(l2[1])
            last_h = 0
            try:
                last_h = mem["current_h"]
                mem["last_h"] = mem["current_h"]
            except:
                pass
            mem["current_h"] = humidite
            verbose(9, "INFO  (mea_dataFromSensor) : humidite =", humidite,
                    "%")

            if last_h != humidite:
                current = humidite
                type = "humidity"
                unit = 5
                last = last_h
            else:
                return True

        # traitement temperature
        elif id_type == 2001 and l2[0] == 'T':
            temperature = float(l2[1])
            last_t = 0
            try:
                last_t = mem["current_t"]
                mem["last_t"] = mem["current_t"]
            except:
                pass
            mem["current_t"] = temperature
            verbose(9, "INFO  (mea_dataFromSensor) : temperature =",
                    temperature, "C")

            if last_t != temperature:
                current = temperature
                unit = 3
                type = "temp"
                last = last_t
            else:
                return True

        # traitement niveau piles
        elif id_type == 2002 and l2[0] == 'P':
            pile = float(l2[1])
            last_p = 0
            try:
                last_p = mem["current_p"]
                mem["last_p"] = mem["current_p"]
            except:
                pass
            mem["current_p"] = pile
            verbose(9, "INFO  (mea_dataFromSensor) : Pile =", pile, "V")

            if last_p != pile:
                current = pile
                unit = 4
                type = "volt"
                last = last_p
            else:
                return True

        else:
            continue

        mea.addDataToSensorsValuesTable(id_sensor, current, unit, 0, "")

        xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
        mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg, "current", current)
        mea_utils.xplMsgAddValue(xplMsg, "type", type)
        mea_utils.xplMsgAddValue(xplMsg, "last", last)
        mea.xplSendMsg(xplMsg)

    return True
Exemplo n.º 25
0
def mea_xplCmndMsg(data):

    try:
        x = data["xplmsg"]
        body = x["body"]
    except:
        return False

    try:
        if x["schema"] != "sensor.request":
            return False
    except:
        return False

    try:
        id_sensor = data["device_id"]
        id_type = data["device_type_id"]
    except:
        verbose(2, "ERROR - (mea_xplCmndMsg) : data not found")
        return False

    target = "*"
    if "source" in x:
        target = x["source"]

    mem = mea.getMemory(id_sensor)

    if body["request"] == "current":
        try:
            if id_type == 2000:
                type = "humidity"
                current = mem["current_h"]
            elif id_type == 2001:
                type = "temperature"
                current = mem["current_t"]
            elif id_type == 2002:
                type = "voltage"
                current = mem["current_p"]
            else:
                return False
        except:
            return False

        xplMsg = mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor",
                                     "basic")
        mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg, "current", current)
        mea_utils.xplMsgAddValue(xplMsg, "type", type)
        mea.xplSendMsg(xplMsg)
        return True

    elif body["request"] == "last":
        try:
            if id_type == 2000:
                type = "humidity"
                last = mem["last_h"]
            elif id_type == 2001:
                type = "temperature"
                last = mem["last_t"]
            elif id_type == 2002:
                type = "voltage"
                last = mem["last_p"]
            else:
                return False
        except:
            return False

        xplMsg = mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor",
                                     "basic")
        mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg, "last", last)
        mea_utils.xplMsgAddValue(xplMsg, "type", type)
        mea.xplSendMsg(xplMsg)
        return True

    else:
        return False
Exemplo n.º 26
0
def mea_xplCmndMsg(data):
   fn_name=sys._getframe().f_code.co_name

   try:
      id_sensor=data["device_id"]
      parameters=data["device_parameters"]
      api_key=data["api_key"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return 0

   mem=mea.getMemory(id_sensor)

   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   channel = -1;
   current = -1;
   if x["schema"]=="control.basic":
     try:
        if body["type"] == "output":
           if body["current"]=="high":
              current = 100;
           elif body["current"]=="low":
              current = 0; 

           if paramsDict["channel"]=="A":
              channel = 0;
           elif paramsDict["channel"]=="B":
              channel = 1;

           if channel <> -1 and current <> -1:
              buf=bytearray();
              buf.append(0x01)
              buf.append(channel & 0b11111)
              buf.append(current & 0b1111111)

              mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)

     except Exception as e:
        verbose(2, "ERROR (", fn_name, ") - can't create enocean packet ", str(e))
        return False
 
   elif x["schema"]=="sensor.request":
      try:
         xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
         mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
         if body["request"]=="current":
            mea_utils.xplMsgAddValue(xplMsg,"current",mem["current"])
         elif body["request"]=="last":
            mea_utils.xplMsgAddValue(xplMsg,"last",mem["last"])
         else:
            verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
            return False
         mea_utils.xplMsgAddValue(xplMsg,"type","input")
      except:
         verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
         return False

      mea.xplSendMsg(xplMsg)
      return True

   return False
Exemplo n.º 27
0
def mea_serialDataPre(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    verbose(9, data)

    try:
        serial_data = data["data"]
        interface_id = data["interface_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_interface = mea.getMemory("interface" + str(interface_id))

    try:
        s = serial_data.decode("latin-1")
    except:
        return False

    for i in range(0, 10):
        mem_interface[i]["sendFlag"] = False

    retour = False
    if s.find(u"CMT: ") >= 0:  # un sms dans le buffer ?
        retour = True  # oui, dans tous les cas on passera le buffer on passera le buffer

    if s.find("\r\n> ") >= 0:
        retour = True  # oui, dans tous les cas on passera le buffer on passera le buffer

    while len(s) > 0:
        ptrStart = s.find(u"$$")
        if ptrStart < 0:
            break
        ptrStart = ptrStart + 2
        ptrEnd = s[ptrStart:].find(u"$$")
        if ptrEnd < 0:
            break
        info = s[ptrStart : ptrStart + ptrEnd]

        # niveau du signal radio
        if info.find(u"SIG=") == 0:
            sig = info[4:]
            try:
                sig = float(sig)
                verbose(9, "INFO  SIM900 SIGNAL LEVEL=", sig)
                mem_interface["siglvl"] = sig
            except:
                pass
        else:
            # retour d'I/O
            a = info.split(";")
            for e in a:
                if len(e) <= 0:
                    continue
                e = e.lower()
                if e[0] != "l" and e[0] != "p" and e[0] != "a":
                    continue
                type = e[0]
                if e[1] != "/":
                    continue
                if e[2] < "0" or e[2] > "9":
                    continue
                pinNum = int(e[2])
                if e[3] != "=":
                    continue
                value = e[4:]

                if value == "h" or value == "l" or value.isdigit():
                    if value == "h":
                        value = 1
                        _value = "high"
                    elif value == "l":
                        value = 0
                        _value = "low"
                    else:
                        _value = value
                        value = int(value)

                    mem_interface[pinNum]["current"] = int(value)
                    mem_interface[pinNum]["sendFlag"] = True
                    retour = True

                else:
                    continue

        # on recommence avec la suite de la chaine
        s = s[ptrStart + ptrEnd + 2 :]

    return retour
Exemplo n.º 28
0
def mea_commissionningRequest(data):
    fn_name = sys._getframe().f_code.co_name

    if "interface_parameters" in data:
        mem = {}
        try:
            mem = mea.getMemory(data["interface_id"])
        except:
            verbose(2, "ERROR (", fn_name, ") - can't acces share memory")
            return False

        sample_set = False
        paramsList = mea_utils.parseKeyValueDatasToList(
            data["interface_parameters"], ",", ":")
        if paramsList != None:
            for i in paramsList:
                numVal = -1
                alphaVal = ""
                if i[0][0] != "#" and i[0][0] != "@":
                    verbose(3, "ERROR (", fn_name, ") - syntaxe error :", i[0],
                            "not a command, skipped")
                    continue

                if i[1] != None:
                    if i[1][0:2] == "0x":
                        try:
                            numVal = int(i[1], 16)
                        except:
                            alphaVal = i[1]
                    elif i[1][0] == "$":
                        (numVal, alphaVal) = getInternalVarValue(data, i[1])
                    else:
                        try:
                            numVal = int(i[1], 10)
                        except:
                            alphaVal = i[1]
                    # commande AT ?
                    if i[0][0] == "@":
                        if len(i[0]) == 3:
                            if numVal >= 0:
                                ret = mea.sendXbeeCmd(data["ID_XBEE"],
                                                      data["ADDR_H"],
                                                      data["ADDR_L"],
                                                      i[0][1:3].upper(),
                                                      numVal)
                                if ret == 0:
                                    verbose(5, "WARNING (", fn_name,
                                            ") - Transmission error for", i[0],
                                            "= ", numVal)
                            else:
                                ret = mea.sendXbeeCmd(data["ID_XBEE"],
                                                      data["ADDR_H"],
                                                      data["ADDR_L"],
                                                      i[0][1:3].upper(),
                                                      alphaVal)
                                if ret == 0:
                                    verbose(5, "WARNING (", fn_name,
                                            ") - Transmission error for", i[0],
                                            "= ", alphaVal)
                        else:
                            verbose(9, "WARNING (", fn_name,
                                    ") - syntaxe error :", i[0],
                                    "not an at cmnd, skip")
                        continue

                    # commande special ?
                    if i[0][0:2] == "#d":
                        ret = config_IO(data, i[0], alphaVal, mem)
                        continue

                    if i[0] == "#set_dhdl":
                        ret = config_DHDL(data, alphaVal)
                        if ret == -1:
                            verbose(5, "WARNING (", fn_name,
                                    ") - value error :", i[1],
                                    "not an xbee adress, skip")
                        continue

                    if i[0] == "#set_sleep":
                        ret = config_sleep(data, numVal)
                        continue

                    if i[0] == "#set_name":
                        ret = config_name(data, alphaVal)
                        if ret == -1:
                            verbose(5, "WARNING (", fn_name,
                                    ") - value error :", i[1],
                                    "not an xbee adress, skip")
                        continue

                    if i[0] == "#set_sample":
                        sample_set = True
                        config_sample(data, numVal)
                        continue

                else:
                    if len(i[0]) == 3:
                        # ret=mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], i[0][1:3].upper(), "");
                        ret = mea.interfaceAPI(api_key, "sendXbeeCmd",
                                               data["ADDR_H"], data["ADDR_L"],
                                               bytes(i[0][1:3].upper()), "")
                        if ret == 0:
                            verbose(3, "ERROR (", fn_name,
                                    ") - Transmission error for", i[0], "= ",
                                    numVal)
            enable_change_detection(data, mem)
            if sample_set == False:
                enable_sample(data, mem)
            return True

        else:
            return False
    else:
        return False
Exemplo n.º 29
0
def mea_xplCmndMsg(data):
   fn_name=sys._getframe().f_code.co_name

   print data

   try:
      id_sensor=data["device_id"]
      parameters=data["device_parameters"]
#      id_driver=data["driver_id"]
      api_key=data["api_key"]

   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return 0

   mem=mea.getMemory(id_sensor)

   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   channel = -1;
   current = -1;
   if x["schema"]=="control.basic":
     try:
        if body["type"] == "output":
           if body["current"]=="high":
              current = 100;
           elif body["current"]=="low":
              current = 0; 

           if paramsDict["channel"]=="A":
              channel = 0;
           elif paramsDict["channel"]=="B":
              channel = 1;

           if channel <> -1 and current <> -1:
              buf=bytearray();
              buf.append(0x01)
              buf.append(channel & 0b11111)
              buf.append(current & 0b1111111)

#              mea.sendEnoceanRadioErp1Packet(data["ID_ENOCEAN"], 0xD2, 0, data["ENOCEAN_ADDR"], buf)
#              mea.interfaceAPI(id_driver, api_key, "sendEnoceanRadioErp1Packet", data["ID_ENOCEAN"], 0xD2, 0, data["ENOCEAN_ADDR"], buf)
#              mea.interfaceAPI(id_driver, api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
              mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
     except Exception as e:
        verbose(2, "ERROR (", fn_name, ") - can't create enocean packet ", str(e))
        return False
 
   elif x["schema"]=="sensor.request":
      try:
         xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
         mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
         if body["request"]=="current":
            mea_utils.xplMsgAddValue(xplMsg,"current",mem["current"])
         elif body["request"]=="last":
            mea_utils.xplMsgAddValue(xplMsg,"last",mem["last"])
         else:
            verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
            return False
         mea_utils.xplMsgAddValue(xplMsg,"type","input")
      except:
         verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
         return False

      mea.xplSendMsg(xplMsg)
      return True

   return False
Exemplo n.º 30
0
def mea_dataFromSensor(data):
    xplMsg = {}
    try:
        id_type=data["device_type_id"]
        id_sensor=data["device_id"]
        cmd=data["cmd"]
    except:
        verbose(2, "ERROR - (mea_dataFromSensor) : data not found")
        return False

    verbose(9, "INFO  (mea_dataFromSensor) : data from ", id_sensor)

    mem=mea.getMemory(id_sensor)

    if debug == 1:
        verbose(9, "INFO - (mea_dataFromSensor) : ", mem)

    # voir http://www.tutorialspoint.com/python/python_reg_expressions.htm pour match
    x=re.match("^\s*<(.*)>\s*$",cmd[12:-2])
    if(x!=None):
        t=x.group(1)
        list=t.split(';')
    else:
        verbose(5, "WARNING - (mea_dataFromSensor) : data error (", cmd[12:-2], ")")
        return False

    for i in list:
        l2=i.split('=')
        
        # traitement Humidite
        if id_type == 2000 and l2[0] == 'H':
            humidite = float(l2[1])
            last_h=0
            try:
                last_h=mem["current_h"]
                mem["last_h"]=mem["current_h"]
            except:
                pass
            mem["current_h"]=humidite
            verbose(9, "INFO  (mea_dataFromSensor) : humidite =", humidite, "%")
        
            if last_h != humidite:
                current=humidite
                type="humidity"
                unit=5
                last=last_h
            else:
                return True

        # traitement temperature
        elif id_type == 2001 and l2[0] == 'T':
            temperature = float(l2[1])
            last_t=0
            try:
                last_t=mem["current_t"]
                mem["last_t"]=mem["current_t"]
            except:
                pass
            mem["current_t"]=temperature
            verbose(9, "INFO  (mea_dataFromSensor) : temperature =", temperature, "C")

            if last_t != temperature:
                current=temperature
                unit=3
                type="temp"
                last=last_t
            else:
               return True

        # traitement niveau piles
        elif id_type == 2002 and l2[0] == 'P':
            pile = float(l2[1])
            last_p=0
            try:
                last_p=mem["current_p"]
                mem["last_p"]=mem["current_p"]
            except:
                pass
            mem["current_p"]=pile
            verbose(9, "INFO  (mea_dataFromSensor) : Pile =", pile, "V")

            if last_p != pile:
                current=pile
                unit=4
                type="volt"
                last=last_p
            else:
                return True
            
        else:
            continue

        mea.addDataToSensorsValuesTable(id_sensor,current,unit,0,"")
        
        xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
        mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg,"current",current)
        mea_utils.xplMsgAddValue(xplMsg,"type",type)
        mea_utils.xplMsgAddValue(xplMsg,"last",last)
        mea.xplSendMsg(xplMsg)

    return True
Exemplo n.º 31
0
def mea_serialDataPre(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    verbose(9, data)

    try:
        serial_data = data["data"]
        interface_id = data["interface_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_interface = mea.getMemory("interface" + str(interface_id))

    try:
        s = serial_data.decode('latin-1')
    except:
        return False

    for i in range(0, 10):
        mem_interface[i]["sendFlag"] = False

    retour = False
    if s.find(u"CMT: ") >= 0:  # un sms dans le buffer ?
        retour = True  # oui, dans tous les cas on passera le buffer on passera le buffer

    if s.find("\r\n> ") >= 0:
        retour = True  # oui, dans tous les cas on passera le buffer on passera le buffer

    while len(s) > 0:
        ptrStart = s.find(u"$$")
        if ptrStart < 0:
            break
        ptrStart = ptrStart + 2
        ptrEnd = s[ptrStart:].find(u"$$")
        if ptrEnd < 0:
            break
        info = s[ptrStart:ptrStart + ptrEnd]

        # niveau du signal radio
        if info.find(u"SIG=") == 0:
            sig = info[4:]
            try:
                sig = float(sig)
                verbose(9, "INFO  SIM900 SIGNAL LEVEL=", sig)
                mem_interface['siglvl'] = sig
            except:
                pass
        else:
            # retour d'I/O
            a = info.split(";")
            for e in a:
                if len(e) <= 0:
                    continue
                e = e.lower()
                if e[0] != 'l' and e[0] != 'p' and e[0] != 'a':
                    continue
                type = e[0]
                if e[1] != "/":
                    continue
                if e[2] < '0' or e[2] > '9':
                    continue
                pinNum = int(e[2])
                if e[3] != '=':
                    continue
                value = e[4:]

                if value == 'h' or value == 'l' or value.isdigit():
                    if value == 'h':
                        value = 1
                        _value = 'high'
                    elif value == 'l':
                        value = 0
                        _value = 'low'
                    else:
                        _value = value
                        value = int(value)

                    mem_interface[pinNum]["current"] = int(value)
                    mem_interface[pinNum]["sendFlag"] = True
                    retour = True

                else:
                    continue

        # on recommence avec la suite de la chaine
        s = s[ptrStart + ptrEnd + 2:]

    return retour
Exemplo n.º 32
0
def mea_xplCmndMsg(data):
    
    try:
        x=data["xplmsg"]
        body=x["body"]
    except:
        return False

    try:
        if x["schema"]!="sensor.request":
           return False
    except:
        return False

    try:
        id_sensor=data["device_id"]
        id_type=data["device_type_id"]
    except:
        verbose(2, "ERROR - (mea_xplCmndMsg) : data not found")
        return False

    target="*"
    if "source" in x:
        target=x["source"]

    mem=mea.getMemory(id_sensor)

    if body["request"]=="current":
        try:
            if id_type==2000:
                type="humidity"
                current=mem["current_h"]
            elif id_type==2001:
                type="temperature"
                current=mem["current_t"]
            elif id_type==2002:
                type="voltage"
                current=mem["current_p"]
            else:
                return False
        except:
            return False

        xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
        mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg,"current",current)
        mea_utils.xplMsgAddValue(xplMsg,"type",type)
        mea.xplSendMsg(xplMsg)
        return True

    elif body["request"]=="last":
        try:
            if id_type==2000:
                type="humidity"
                last=mem["last_h"]
            elif id_type==2001:
                type="temperature"
                last=mem["last_t"]
            elif id_type==2002:
                type="voltage"
                last=mem["last_p"]
            else:
                return False
        except:
            return False

        xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
        mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"])
        mea_utils.xplMsgAddValue(xplMsg,"last",last)
        mea_utils.xplMsgAddValue(xplMsg,"type",type)
        mea.xplSendMsg(xplMsg)
        return True

    else:
        return False
Exemplo n.º 33
0
def mea_commissionningRequest(data):
   fn_name=sys._getframe().f_code.co_name
   
   if "interface_parameters" in data:
      mem={}
      try:
         mem=mea.getMemory(data["interface_id"])
      except:
         verbose(2, "ERROR (", fn_name, ") - can't acces share memory")
         return False
      
      sample_set=False
      paramsList=mea_utils.parseKeyValueDatasToList(data["interface_parameters"], ",", ":")
      if paramsList != None:
         for i in paramsList:
            numVal=-1;
            alphaVal="";
            if i[0][0] != "#" and i[0][0] !="@":
               verbose (3, "ERROR (", fn_name, ") - syntaxe error :", i[0], "not a command, skipped")
               continue
            
            if i[1]!=None:
               if i[1][0:2]=="0x":
                  try:
                     numVal=int(i[1],16)
                  except:
                     alphaVal=i[1]
               elif i[1][0]=="$":
                  (numVal,alphaVal)=getInternalVarValue(data, i[1])
               else:
                  try:
                     numVal=int(i[1],10)
                  except:
                     alphaVal=i[1]
               # commande AT ?
               if i[0][0] == "@":
                  if len(i[0])==3:
                     if numVal>=0:
                        ret=mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], i[0][1:3].upper(), numVal);
                        if ret == 0:
                           verbose(5, "WARNING (", fn_name, ") - Transmission error for", i[0], "= ", numVal)
                     else:
                        ret=mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], i[0][1:3].upper(), alphaVal);
                        if ret == 0:
                           verbose(5, "WARNING (", fn_name, ") - Transmission error for", i[0], "= ", alphaVal)
                  else:
                     verbose(9, "WARNING (", fn_name, ") - syntaxe error :", i[0], "not an at cmnd, skip")
                  continue
               
               # commande special ?
               if i[0][0:2]=="#d":
                  ret=config_IO(data, i[0], alphaVal, mem)
                  continue
               
               if i[0] == "#set_dhdl":
                  ret=config_DHDL(data,alphaVal)
                  if ret==-1:
                     verbose(5, "WARNING (", fn_name, ") - value error :", i[1], "not an xbee adress, skip")
                  continue
               
               if i[0] == "#set_sleep":
                  ret=config_sleep(data,numVal)
                  continue
               
               if i[0] == "#set_name":
                  ret=config_name(data, alphaVal)
                  if ret==-1:
                     verbose(5, "WARNING (", fn_name, ") - value error :", i[1], "not an xbee adress, skip")
                  continue
               
               
               if i[0] == "#set_sample":
                  sample_set=True
                  config_sample(data,numVal)
                  continue
            
            else:
               if len(i[0])==3:
                  ret=mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], i[0][1:3].upper(), "");
                  if ret == 0:
                     verbose(3, "ERROR (", fn_name, ") - Transmission error for", i[0], "= ", numVal)
         enable_change_detection(data,mem)
         if sample_set==False:
            enable_sample(data,mem)
         return True
      
      else:
         return False
   else:
      return False
Exemplo n.º 34
0
def mea_dataFromSensor(data):
   fn_name=sys._getframe().f_code.co_name
   xplMsg = {}
   
   try:
      id_sensor=data["device_id"]
      cmd_data=data["cmd_data"]
      l_cmd_data=data["l_cmd_data"]
      data_type=data["data_type"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False
   
   mem=mea.getMemory(id_sensor)
   
   if data_type==0x92:
      mem["iodata"]=parseIOData(cmd_data, l_cmd_data)
      
      paramsDict=mea_utils.parseKeyValueDatasToDictionary(data["device_parameters"], ",", ":")
      
      if "pin" in paramsDict:
         pin=paramsDict["pin"]
      else:
         return False
      
      if "sensor_type" in paramsDict:
         type=paramsDict["sensor_type"]
      else:
         type="generic"
      
      current_key=pin+"_current"
      last_key=pin+"_last"
      
      if pin in mem["iodata"].lower():
         val=mem["iodata"][pin]
         last_val=0
         
         try:
            mem[last_key]=mem[current_key]
         except:
            mem[last_key]=0
         
         strVal=""
         if pin[0]=="d":
            if val==1:
               mem[current_key]="high"
            else:
               mem[current_key]="low"
            logval=val
         else:
            if "compute" in paramsDict:
               x=val
               y=eval(paramsDict["compute"])
               logval=round(y,2)
            else:
               logval=val
            mem[current_key]=logval

         if mem[current_key] != mem[last_key]:
            if "log" in paramsDict and paramsDict["log"].lower()=="yes":
               if "unit" in paramsDict:
                  unit=int(paramsDict["unit"])
               else:
                  unit=0
               mea.addDataToSensorsValuesTable(id_sensor,logval,unit,val,"")

            xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
            mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
            mea_utils.xplMsgAddValue(xplMsg,"current", mem[current_key])
            mea_utils.xplMsgAddValue(xplMsg,"type", type)
            mea_utils.xplMsgAddValue(xplMsg,"last",mem[last_key])
            mea.xplSendMsg(xplMsg)

            return True

   return False
def mea_dataFromSensor(data):
   fn_name=str(sys._getframe().f_code.co_name) + "/" + __name__

   parameters=False
   try:
       id_sensor=data["device_id"]
       device=data["device_name"]
       serial_data=data["data"]
       l_serial_data=data["l_data"]
       toDbFlag=data["todbflag"]
#       parameters=data["device_parameters"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem=mea.getMemory(id_sensor)

   # récupération des paramétres
   if parameters <> False:
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   # faire ce qu'il faut ici avec les parametres

   # conversion des données si nécessaire
   # récupération des données dans une chaine de caractères unicode
   s=serial_data.decode('latin-1')

   # traitement des données
   # récupère (ou pas) un SMS dans les données
   sms=mea_getSMS(s)
   if sms[0] == False:
      if sms[1] == 1:
         verbose(2, "ERROR (", fn_name, ") - incomplete SMS data")
      else:
         verbose(9, "DEBUG (", fn_name, ") - not a SMS")
      return False

   # analyse des données
   alarm=_analyseData(sms[1])
   if alarm[0] == False:
      verbose(9, "DEBUG (", fn_name, ") - not an EPG message : ", alarm[1])
      return False
   verbose(9, alarm)

   # vérification validité
   try:
      last_date = datetime.strptime( mem['date']+"-"+ mem['time'], '%d/%m/%Y-%H:%M:%S')
   except:
      last_date = datetime.fromtimestamp(0);

   try:
      current_date = datetime.strptime( alarm[2]+"-"+ alarm[3], '%d/%m/%Y-%H:%M:%S')
   except:
      verbose(9, "ERROR (", fn_name, ") - EPG message date and time error : ", alarm[2]+"-"+alarm[3]+" ?")
      return False

   if current_date < last_date:
      verbose(9, "ERROR (", fn_name, ") - older EPG message than previous received")
      return False

   now = datetime.now()
   d = (now - current_date).total_seconds() / 60;
   verbose (9, d)
   if d > 15:
      verbose(9, "ERROR (", fn_name, ") - too old EPG message")
      return False

   # memorisation des données
   try:
      mem['last']=mem['current']
   except:
      mem['last']=-1
   mem['current']=alarm[0]

   if alarm[1]==False:
      who="";
   else:
      who=str(alarm[1])
   mem['who']=who
   mem['date']=str(alarm[2])
   mem['time']=str(alarm[3])

   mea.addDataToSensorsValuesTable(id_sensor,mem['current'],0,0,who)

   # emission XPL
   xplMsg=mea_utils.xplMsgNew('me', "*", "xpl-trig", "sensor", "basic")
   mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
   mea_utils.xplMsgAddValue(xplMsg, 'current', mem['current'])
   mea.xplSendMsg(xplMsg)

   return True
Exemplo n.º 36
0
def mea_xplCmndMsg(data):
    fn_name = sys._getframe().f_code.co_name

    try:
        id_sensor = data["device_id"]
        parameters = data["device_parameters"]
        typeoftype = data["typeoftype"]
        api_key = data["api_key"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return 0

    mem = mea.getMemory(id_sensor)

    paramsDict = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

    x = data["xplmsg"]
    body = x["body"]

    target = "*"
    if "source" in x:
        target = x["source"]

    channel = -1
    current = -1
    if x["schema"] == "control.basic" and typeoftype == 1:
        try:
            if body["type"] == "output":
                if body["current"] == "high":
                    current = 100
                elif body["current"] == "low":
                    current = 0

                if current <> -1:
                    channel = ord(paramsDict["channel"][0]) - ord('A')
                    buf = bytearray()
                    buf.append(0x01)
                    buf.append(channel & 0b11111)
                    buf.append(current & 0b1111111)

                    mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet",
                                     0xD2, 0, data["ENOCEAN_ADDR"], buf)

                    try:
                        if paramsDict["force_status"] == "yes":
                            channel = ord(paramsDict["channel"][0]) - ord('A')
                            buf = bytearray()
                            buf.append(0x03)
                            buf.append(channel & 0b11111)
                            mea.interfaceAPI(api_key,
                                             "sendEnoceanRadioErp1Packet",
                                             0xD2, 0, data["ENOCEAN_ADDR"],
                                             buf)
                    except Exception as e:
                        verbose(2, "ERROR (", fn_name,
                                ") - can't query device: ", str(e))
                        pass

        except Exception as e:
            verbose(2, "ERROR (", fn_name,
                    ") - can't create/send enocean packet: ", str(e))
            return False

    elif x["schema"] == "sensor.request" and typeoftype == 0:
        if body["request"] == "current":
            try:
                buf = bytearray()
                channel = ord(paramsDict["channel"][0]) - ord('A')
                buf.append(0x03)
                buf.append(channel & 0b11111)
                mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet", 0xD2,
                                 0, data["ENOCEAN_ADDR"], buf)
            except Exception as e:
                verbose(2, "ERROR (", fn_name, ") - can't query device: ",
                        str(e))
                return False

        else:
            verbose(2, "ERROR (", fn_name, ") - invalid request (",
                    body["request"], ")")
            return False

        return True

    return False
Exemplo n.º 37
0
def mea_dataFromSensor(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    #   verbose(9, "DEBUG (", fn_name, ") data = ", data)

    try:
        device_id = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_device = mea.getMemory(device_id)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    # validation du parametre
    pin = 0
    try:
        pin = params["pin"]
    except:
        verbose(2, "ERROR (", fn_name, ") - ", device_name,
                " parameters error : no PIN defined")
        return False

    if len(pin) != 2:
        verbose(2, "ERROR (", fn_name, ") - ", device_name,
                " PIN format error")
        return False

    if pin[0] != 'l' and pin[0] != 'a':
        verbose(2, "ERROR (", fn_name, ") - ", device_name, " PIN type error")
        return Flase
    else:
        pinType = pin[0]

    if pin[1] < '0' or pin[1] > '9':
        verbose(2, "ERROR (", fn_name, ") - ", device_name,
                " PIN number error")
        return False
    else:
        pinNum = int(pin[1])

    # on va traiter les données prémachées par mea_serialDataPre
    if "sendFlag" in mem_interface[pinNum] and mem_interface[pinNum][
            "sendFlag"] == True:
        if "current" in mem_interface[pinNum]:
            current_value = mem_interface[pinNum]["current"]
            if pinType == 'l':
                if mem_interface[pinNum]["current"] == 0:
                    current_value = "low"
                else:
                    current_value = "high"

            mea.addDataToSensorsValuesTable(device_id,
                                            mem_interface[pinNum]["current"],
                                            0, 0, "")

            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor",
                                         "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", current_value)
            mea.xplSendMsg(xplMsg)
        return True
    return False
Exemplo n.º 38
0
def mea_dataFromSensor(data):
    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    #   verbose(9, "DEBUG (", fn_name, ") data = ", data)

    try:
        device_id = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem_device = mea.getMemory(device_id)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    # validation du parametre
    pin = 0
    try:
        pin = params["pin"]
    except:
        verbose(2, "ERROR (", fn_name, ") - ", device_name, " parameters error : no PIN defined")
        return False

    if len(pin) != 2:
        verbose(2, "ERROR (", fn_name, ") - ", device_name, " PIN format error")
        return False

    if pin[0] != "l" and pin[0] != "a":
        verbose(2, "ERROR (", fn_name, ") - ", device_name, " PIN type error")
        return Flase
    else:
        pinType = pin[0]

    if pin[1] < "0" or pin[1] > "9":
        verbose(2, "ERROR (", fn_name, ") - ", device_name, " PIN number error")
        return False
    else:
        pinNum = int(pin[1])

    # on va traiter les données prémachées par mea_serialDataPre
    if "sendFlag" in mem_interface[pinNum] and mem_interface[pinNum]["sendFlag"] == True:
        if "current" in mem_interface[pinNum]:
            current_value = mem_interface[pinNum]["current"]
            if pinType == "l":
                if mem_interface[pinNum]["current"] == 0:
                    current_value = "low"
                else:
                    current_value = "high"

            mea.addDataToSensorsValuesTable(device_id, mem_interface[pinNum]["current"], 0, 0, "")

            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", current_value)
            mea.xplSendMsg(xplMsg)
        return True
    return False
def mea_dataFromSensor(data):
   fn_name=sys._getframe().f_code.co_name

   try:
      id_sensor=data["device_id"]
      verbose(1, "DEBUG (", fn_name, ") - id_sensor=", id_sensor)
      packet=data["data"]
      l_packet=data["l_data"]
      parameters=data["device_parameters"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem=mea.getMemory(id_sensor)
   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   device1=0
   device2=0
   try:
      device=paramsDict["xpldevice"];
   except:
      device=-1;

   if packet[4]==1: # ENOCEAN_RADIO_ERP1
      if packet[6]==0xF6:
         t21 = (packet[12] & 0b00100000) >> 5
         nu =  (packet[12] & 0b00010000) >> 4
         
         if t21 == 1:
            if nu == 1:
               button1Num = (packet[7] & 0b11100000) >> 5
               button2Num = -1;
               action   = (packet[7] & 0b00010000) >> 4
               if packet[7] & 0b00000001:
                  button2Num=(packet[7] & 0b00001110) >> 1
               current=""
               try:
                  if paramsDict["channel"]=="A" and action == 1:
                     if (button1Num == 0 or button2Num == 0):
                        current="high"
                     elif (button1Num == 1 or button2Num == 1):
                        current="low"

                  if paramsDict["channel"]=="B" and action == 1:
                     if (button1Num == 2 or button2Num == 2):
                        current="high"
                     elif (button1Num == 3 or button2Num == 3):
                        current="low"
               except:
                  return False

               if current != "":
                  try:
                     mem["last"]=mem["current"]
                  except:
                     mem["last"]=False
                  mem["current"]=current

                  mem["button1"]=button1Num
                  mem["button2"]=button2Num

                  internal=-1
                  if(device!=-1):
                     try:
                        internal=int(paramsDict["internal"])
                     except:
                        internal=0
                     broadcastXplDirectControlBasic(internal, paramsDict["channel"], button1Num, button2Num, device);

                  xplMsg=mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
                  mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
                  mea_utils.xplMsgAddValue(xplMsg,"current", mem["current"])
                  mea_utils.xplMsgAddValue(xplMsg,"type", "input")
                  mea_utils.xplMsgAddValue(xplMsg,"last",mem["last"])
                  mea.xplSendMsg(xplMsg)
                  return True
#            else: # bouton relache
#               if mem["button1"] != -1:
#                  verbose(2, "Relachement de : ", mem["button1"])
#               if mem["button2"] != -1:
#                  verbose(2, "Relachement de : ", mem["button2"])
#               mem["button1"]=-1
#               mem["button2"]=-1
#               verbose(2,"Nb boutons appuyes = ", (packet[7] & 0b11100000) >> 5)
#               verbose(2,"Energy bow = ", (packet[7] & 0b00010000) >> 4)
#               return True
   return False
Exemplo n.º 40
0
def mea_xplCmndMsg(data):

    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    try:
        id_actuator = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]

    except:
        verbose(2, "ERROR (", fn_name, ") - parameters error")
        return False

    mem_actuator = mea.getMemory(id_actuator)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    # validation du parametre
    pin = 0
    if "pin" in params:
        pin = params["pin"]
    else:
        verbose(9, "DEBUG (", fn_name, ") - parameters error : no pin")
        return False

    if len(pin) != 2:
        verbose(2, "ERROR (", fn_name, ") - PIN parameter error")
        return False

    if pin[0] != "l" and pin[0] != "a":
        verbose(2, "ERROR (", fn_name, ") - PIN type error")
        return False
    else:
        pinType = pin[0]

    if pin[1] < "0" or pin[1] > "9":
        verbose(2, "ERROR (", fn_name, ") - PIN id error")
        return False
    else:
        pinNum = int(pin[1])

    # validation du message xpl
    try:
        x = data["xplmsg"]
        schema = x["schema"]
        msgtype = x["msgtype"]
        body = x["body"]
        device = body["device"]
    except:
        verbose(2, "ERROR (", fn_name, ") - no or incomplet xpl message error")
        return False

    if msgtype != "xpl-cmnd":
        verbose(9, data)
        return False

    current = False
    request = False
    if "current" in body:
        current = body["current"]
    elif "request" in body:
        request = body["request"]
    else:
        verbose(2, "ERROR (", fn_name, ') - no "current" or "request" in message body')
        return False

    # préparation de la commande
    _cmnd = str(pinNum) + ","

    if schema == "control.basic" and typeoftype == 1:
        if current == False:
            verbose(2, "ERROR (", fn_name, ') - no "current" in message body')
            return False
        try:
            type = body["type"]
        except:
            verbose(2, "ERROR (", fn_name, ') - no "type" in message body')
            return False

        if pinNum == 0 or pinNum == 3:
            verbose(2, "ERROR (", fn_name, ") - PIN 0 and 3 are input only")
            return False

        if type == "output" and pinType == "l":
            if current == "pulse":
                if "data1" in body:
                    data1 = body["data1"]
                    if not data1.isdigit():
                        verbose(2, "ERROR (", fn_name, ") - data1 not numeric value")
                        return False
                    data1 = int(data1)
                else:
                    data1 = 200

                _cmnd = _cmnd + "P," + str(data1)
            elif current == "high" or (current.isdigit() and int(current) == 1):
                _cmnd = _cmnd + "L,H"
            elif current == "low" or (current.isdigit() and int(current) == 0):
                _cmnd = _cmnd + "L,L"

        elif type == "variable" and pinType == "a":
            if pinNum != 1 and pinNum != 2:
                verbose(2, "ERROR (", fn_name, ") - Analog output(PWM) only available on pin 1 and 2")
                return False
            else:
                value = 0
                if "current" in mem_interface[pinNum]:
                    value = mem_interface[pinNum]["current"]

                if current == "dec":
                    value = value - 1
                elif current == "inc":
                    value = value + 1
                elif current[0] == "-" or current[0] == "+":
                    if current[1:].isdigit():
                        value = int(current)
                    else:
                        verbose(2, "ERROR (", fn_name, ") - analog value error (", current, ")")
                        return False
                elif current.isdigit():
                    value = int(current)
                else:
                    verbose(2, "ERROR (", fn_name, ") - analog value error (", current, ")")
                    return False

                if value < 0:
                    value = 0
                if value > 255:
                    value = 255
                _cmnd = _cmnd + "A," + str(value)
        else:
            verbose(2, "ERROR (", fn_name, ") - xpl command error")
            return False

    elif schema == "sensor.basic":
        if request == False:
            verbose(2, "ERROR (", fn_name, ') - no "request" in message body')
            return False
        if request != "current":
            verbose(2, "ERROR (", fn_name, ") - xpl error request!=current")
            return False
        if typeoftype == 0:
            if pinType == "a" and pinNum < 4:
                verbose(2, "ERROR (", fn_name, ") - Analog input only available on pin 4 to pin 9")
                return False
            _cmnd = _cmnd + pinType.upper() + ",G"
        else:
            _cmnd = False
            # interrogation de l'état d'une sortie, on récupére de l'info aux niveaux de l'interface si dispo
            if not "current" in mem_interface[pinNum]:
                return False
            current_value = mem_interface[pinNum]["current"]
            if pinType == "l":
                if current_value == 0:
                    current_value = "low"
                else:
                    current_value = "high"
            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor", "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", current_value)
            mea.xplSendMsg(xplMsg)
            return True
    else:
        verbose(9, data)
        verbose(2, "ERROR (", fn_name, ") - xpl schema incompatible with sensor/actuator (", schema, ")")
        return False

    if _cmnd != False:
        cmnd = "~~~~CMD:##" + _cmnd + "##\r\nEND\r\n"
        #      verbose(9, cmnd)
        mea.sendSerialData(data["fd"], bytearray(cmnd))

    return True
Exemplo n.º 41
0
def mea_dataFromSensor(data):
   fn_name=str(sys._getframe().f_code.co_name) + "/" + __name__

   parameters=False
   try:
       id_sensor=data["device_id"]
       device=data["device_name"]
       serial_data=data["data"]
       l_serial_data=data["l_data"]
       toDbFlag=data["todbflag"]
#       parameters=data["device_parameters"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return False

   mem=mea.getMemory(id_sensor)

   # récupération des paramétres
   if parameters <> False:
      params=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   # faire ce qu'il faut ici avec les parametres

   # conversion des données si nécessaire
   # récupération des données dans une chaine de caractères unicode
   s=serial_data.decode('latin-1')

   # traitement des données
   # récupère (ou pas) un SMS dans les données
   sms=mea_getSMS(s)
   if sms[0] == False:
      if sms[1] == 1:
         verbose(2, "ERROR (", fn_name, ") - incomplete SMS data")
      else:
         verbose(9, "DEBUG (", fn_name, ") - not a SMS")
      return False

   # analyse des données
   alarm=_analyseData(sms[1])
   if alarm[0] == False:
      verbose(9, "DEBUG (", fn_name, ") - not an EPG message : ", alarm[1])
      return False
   verbose(9, alarm)

   # vérification validité
   try:
      last_date = datetime.strptime( mem['date']+"-"+ mem['time'], '%d/%m/%Y-%H:%M:%S')
   except:
      last_date = datetime.fromtimestamp(0);

   try:
      current_date = datetime.strptime( alarm[2]+"-"+ alarm[3], '%d/%m/%Y-%H:%M:%S')
   except:
      verbose(9, "ERROR (", fn_name, ") - EPG message date and time error : ", alarm[2]+"-"+alarm[3]+" ?")
      return False

   if current_date < last_date:
      verbose(9, "ERROR (", fn_name, ") - older EPG message than previous received")
      return False

   now = datetime.now()
   d = (now - current_date).total_seconds() / 60;
   verbose (9, d)
   if d > 15:
      verbose(9, "ERROR (", fn_name, ") - too old EPG message")
      return False

   # memorisation des données
   try:
      mem['last']=mem['current']
   except:
      mem['last']=-1
   mem['current']=alarm[0]

   if alarm[1]==False:
      who="";
   else:
      who=str(alarm[1])
   mem['who']=who
   mem['date']=str(alarm[2])
   mem['time']=str(alarm[3])

   mea.addDataToSensorsValuesTable(id_sensor,mem['current'],0,0,who)

   # emission XPL
   xplMsg=mea_utils.xplMsgNew('me', "*", "xpl-trig", "sensor", "basic")
   mea_utils.xplMsgAddValue(xplMsg, "device", data["device_name"])
   mea_utils.xplMsgAddValue(xplMsg, 'current', mem['current'])
   mea.xplSendMsg(xplMsg)

   return True
Exemplo n.º 42
0
def mea_xplCmndMsg(data):

    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    verbose(9, "DEBUG (", fn_name, ") data = ", data)

    try:
        id_device = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]
        api_key = data["api_key"]
    except:
        verbose(2, "ERROR (", fn_name, ") - parameters error")
        return False

    mem_device = mea.getMemory(id_device)
    mem_interface = mea.getMemory("interface" + str(interface_id))
    x = data["xplmsg"]
    body = x["body"]

    target = "*"
    if "source" in x:
        target = x["source"]

    if x["msgtype"] != 'xpl-cmnd':
        return False

    if x["schema"] == "sensor.request":
        if "request" in body:
            if body["request"] == "current":
                mea.interfaceAPI(api_key, "mea_writeData",
                                 "[[[" + device_name + "?current]]]\n")
                return True
        return False

    elif x["schema"] == "control.basic":
        if typeoftype != 1:
            verbose(2, "ERROR (", fn_name,
                    ") - device (" + devicename + ") is not an output")
            return False
        if not "current" in body:
            verbose(2, "ERROR (", fn_name, ") - no current in body")
            return False
        v = body["current"].lower()
        try:
            f = float(v)
        except:
            if v in ["on", "off", "high", "low", "true", "false"]:
                f = v
            else:
                verbose(2, "ERROR (", fn_name,
                        ") - invalid current (" + v + ") value")
                return False
        mea.interfaceAPI(api_key, "mea_writeData",
                         "[[[" + device_name + "=" + str(f) + "]]]\n")
        return True
    return False
Exemplo n.º 43
0
def mea_xplCmndMsg(data):
    fn_name = sys._getframe().f_code.co_name
    try:
        id_sensor = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return 0

    mem = mea.getMemory(id_sensor)

    paramsDict = mea_utils.parseKeyValueDatasToDictionary(
        data["device_parameters"], ",", ":")

    if "pin" in paramsDict:
        pin = paramsDict["pin"].lower()
    else:
        return False

    if "sensor_type" in paramsDict:
        type = paramsDict["sensor_type"]
    else:
        type = "generic"

    x = data["xplmsg"]
    body = x["body"]

    target = "*"
    if "source" in x:
        target = x["source"]

    if x["schema"] == "sensor.request":
        current_key = pin + "_current"
        last_key = pin + "_last"
        if body["type"] == type:
            try:
                xplMsg = mea_utils.xplMsgNew("me", target, "xpl-stat",
                                             "sensor", "basic")
                mea_utils.xplMsgAddValue(xplMsg, "device",
                                         data["device_name"].lower())
                if body["request"] == "current":
                    mea_utils.xplMsgAddValue(xplMsg, "current",
                                             mem[current_key])
                elif body["request"] == "last":
                    mea_utils.xplMsgAddValue(xplMsg, "last", mem[last_key])
                else:
                    verbose(2, "ERROR (", fn_name, ") - invalid request (",
                            body["request"], ")")
                    return False
                mea_utils.xplMsgAddValue(xplMsg, "type", type)
            except:
                verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
                return False
        else:
            verbose(2, "ERROR (", fn_name, ") - invalid type (", body["type"],
                    ")")
            return False

        mea.xplSendMsg(xplMsg)
        return True

    elif x["schema"] == "control.basic":
        if body["type"] == "output":
            if body["current"].lower() == "low":
                mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"],
                                data["ADDR_L"], pin, 4)
                mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"],
                                data["ADDR_L"], "AC", "")
                return True
            elif body["current"].lower() == "high":
                mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"],
                                data["ADDR_L"], pin, 5)
                mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"],
                                data["ADDR_L"], "AC", "")
                return True
            else:
                return False
        else:
            verbose(2, "ERROR (", fn_name, ") - invalid request (",
                    body["request"], ")")
            return False
    else:
        verbose(2, "ERROR (", fn_name, ") - invalid schema (", x["schema"],
                ")")
        return False
Exemplo n.º 44
0
def mea_dataFromSensor(data):
    fn_name = sys._getframe().f_code.co_name

    try:
        id_sensor = data["device_id"]
        verbose(1, "DEBUG (", fn_name, ") - id_sensor=", id_sensor)
        packet = data["data"]
        l_packet = data["l_data"]
        parameters = data["device_parameters"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem = mea.getMemory(id_sensor)
    paramsDict = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

    device1 = 0
    device2 = 0
    try:
        device = paramsDict["xpldevice"]
    except:
        device = -1

    if packet[4] == 1:  # ENOCEAN_RADIO_ERP1
        if packet[6] == 0xF6:
            t21 = (packet[12] & 0b00100000) >> 5
            nu = (packet[12] & 0b00010000) >> 4

            if t21 == 1:
                if nu == 1:
                    button1Num = (packet[7] & 0b11100000) >> 5
                    button2Num = -1
                    action = (packet[7] & 0b00010000) >> 4
                    if packet[7] & 0b00000001:
                        button2Num = (packet[7] & 0b00001110) >> 1
                    current = ""
                    try:
                        if paramsDict["channel"] == "A" and action == 1:
                            if (button1Num == 0 or button2Num == 0):
                                current = "high"
                            elif (button1Num == 1 or button2Num == 1):
                                current = "low"

                        if paramsDict["channel"] == "B" and action == 1:
                            if (button1Num == 2 or button2Num == 2):
                                current = "high"
                            elif (button1Num == 3 or button2Num == 3):
                                current = "low"
                    except:
                        return False

                    if current != "":
                        try:
                            mem["last"] = mem["current"]
                        except:
                            mem["last"] = False
                        mem["current"] = current

                        mem["button1"] = button1Num
                        mem["button2"] = button2Num

                        internal = -1
                        if (device != -1):
                            try:
                                internal = int(paramsDict["internal"])
                            except:
                                internal = 0
                            broadcastXplDirectControlBasic(
                                internal, paramsDict["channel"], button1Num,
                                button2Num, device)

                        xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig",
                                                     "sensor", "basic")
                        mea_utils.xplMsgAddValue(xplMsg, "device",
                                                 data["device_name"].lower())
                        mea_utils.xplMsgAddValue(xplMsg, "current",
                                                 mem["current"])
                        mea_utils.xplMsgAddValue(xplMsg, "type", "input")
                        mea_utils.xplMsgAddValue(xplMsg, "last", mem["last"])
                        mea.xplSendMsg(xplMsg)
                        return True


#            else: # bouton relache
#               if mem["button1"] != -1:
#                  verbose(2, "Relachement de : ", mem["button1"])
#               if mem["button2"] != -1:
#                  verbose(2, "Relachement de : ", mem["button2"])
#               mem["button1"]=-1
#               mem["button2"]=-1
#               verbose(2,"Nb boutons appuyes = ", (packet[7] & 0b11100000) >> 5)
#               verbose(2,"Energy bow = ", (packet[7] & 0b00010000) >> 4)
#               return True
    return False
Exemplo n.º 45
0
def mea_xplCmndMsg(data):

    fn_name = __name__ + "/" + str(sys._getframe().f_code.co_name)

    try:
        id_actuator = data["device_id"]
    except:
        verbose(2, "ERROR (", fn_name, ") - device_id not found")
        return False

    try:
        device_name = data["device_name"]
        interface_id = data["interface_id"]
        parameters = data["device_parameters"]
        parameters = parameters.strip().lower()
        params = mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")
        typeoftype = data["typeoftype"]

    except:
        verbose(2, "ERROR (", fn_name, ") - parameters error")
        return False

    mem_actuator = mea.getMemory(id_actuator)
    mem_interface = mea.getMemory("interface" + str(interface_id))

    # validation du parametre
    pin = 0
    if "pin" in params:
        pin = params["pin"]
    else:
        verbose(9, "DEBUG (", fn_name, ") - parameters error : no pin")
        return False

    if len(pin) != 2:
        verbose(2, "ERROR (", fn_name, ") - PIN parameter error")
        return False

    if pin[0] != 'l' and pin[0] != 'a':
        verbose(2, "ERROR (", fn_name, ") - PIN type error")
        return False
    else:
        pinType = pin[0]

    if pin[1] < '0' or pin[1] > '9':
        verbose(2, "ERROR (", fn_name, ") - PIN id error")
        return False
    else:
        pinNum = int(pin[1])

    # validation du message xpl
    try:
        x = data["xplmsg"]
        schema = x["schema"]
        msgtype = x["msgtype"]
        body = x["body"]
        device = body["device"]
    except:
        verbose(2, "ERROR (", fn_name, ") - no or incomplet xpl message error")
        return False

    if msgtype != "xpl-cmnd":
        verbose(9, data)
        return False

    current = False
    request = False
    if "current" in body:
        current = body["current"]
    elif "request" in body:
        request = body["request"]
    else:
        verbose(2, "ERROR (", fn_name,
                ") - no \"current\" or \"request\" in message body")
        return False

    # préparation de la commande
    _cmnd = str(pinNum) + ","

    if schema == "control.basic" and typeoftype == 1:
        if current == False:
            verbose(2, "ERROR (", fn_name,
                    ") - no \"current\" in message body")
            return False
        try:
            type = body["type"]
        except:
            verbose(2, "ERROR (", fn_name, ") - no \"type\" in message body")
            return False

        if (pinNum == 0 or pinNum == 3):
            verbose(2, "ERROR (", fn_name, ") - PIN 0 and 3 are input only")
            return False

        if type == "output" and pinType == 'l':
            if current == "pulse":
                if "data1" in body:
                    data1 = body["data1"]
                    if not data1.isdigit():
                        verbose(2, "ERROR (", fn_name,
                                ") - data1 not numeric value")
                        return False
                    data1 = int(data1)
                else:
                    data1 = 200

                _cmnd = _cmnd + "P," + str(data1)
            elif current == "high" or (current.isdigit()
                                       and int(current) == 1):
                _cmnd = _cmnd + "L,H"
            elif current == "low" or (current.isdigit() and int(current) == 0):
                _cmnd = _cmnd + "L,L"

        elif type == "variable" and pinType == 'a':
            if pinNum != 1 and pinNum != 2:
                verbose(
                    2, "ERROR (", fn_name,
                    ") - Analog output(PWM) only available on pin 1 and 2")
                return False
            else:
                value = 0
                if 'current' in mem_interface[pinNum]:
                    value = mem_interface[pinNum]['current']

                if current == "dec":
                    value = value - 1
                elif current == "inc":
                    value = value + 1
                elif current[0] == '-' or current[0] == '+':
                    if current[1:].isdigit():
                        value = int(current)
                    else:
                        verbose(2, "ERROR (", fn_name,
                                ") - analog value error (", current, ")")
                        return False
                elif current.isdigit():
                    value = int(current)
                else:
                    verbose(2, "ERROR (", fn_name, ") - analog value error (",
                            current, ")")
                    return False

                if value < 0:
                    value = 0
                if value > 255:
                    value = 255
                _cmnd = _cmnd + "A," + str(value)
        else:
            verbose(2, "ERROR (", fn_name, ") - xpl command error")
            return False

    elif schema == "sensor.basic":
        if request == False:
            verbose(2, "ERROR (", fn_name,
                    ") - no \"request\" in message body")
            return False
        if request != "current":
            verbose(2, "ERROR (", fn_name, ") - xpl error request!=current")
            return False
        if typeoftype == 0:
            if pinType == 'a' and pinNum < 4:
                verbose(2, "ERROR (", fn_name,
                        ") - Analog input only available on pin 4 to pin 9")
                return False
            _cmnd = _cmnd + pinType.upper() + ",G"
        else:
            _cmnd = False
            # interrogation de l'état d'une sortie, on récupére de l'info aux niveaux de l'interface si dispo
            if not "current" in mem_interface[pinNum]:
                return False
            current_value = mem_interface[pinNum]["current"]
            if pinType == 'l':
                if current_value == 0:
                    current_value = "low"
                else:
                    current_value = "high"
            xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor",
                                         "basic")
            mea_utils.xplMsgAddValue(xplMsg, "device", device_name)
            mea_utils.xplMsgAddValue(xplMsg, "current", current_value)
            mea.xplSendMsg(xplMsg)
            return True
    else:
        verbose(9, data)
        verbose(2, "ERROR (", fn_name,
                ") - xpl schema incompatible with sensor/actuator (", schema,
                ")")
        return False

    if _cmnd != False:
        cmnd = "~~~~CMD:##" + _cmnd + "##\r\nEND\r\n"
        #      verbose(9, cmnd)
        mea.sendSerialData(data['fd'], bytearray(cmnd))

    return True
Exemplo n.º 46
0
def mea_dataFromSensor(data):
    fn_name = sys._getframe().f_code.co_name
    xplMsg = {}

    try:
        id_sensor = data["device_id"]
        cmd_data = data["cmd_data"]
        l_cmd_data = data["l_cmd_data"]
        data_type = data["data_type"]
    except:
        verbose(2, "ERROR (", fn_name, ") - invalid data")
        return False

    mem = mea.getMemory(id_sensor)

    if data_type == 0x92:
        mem["iodata"] = parseIOData(cmd_data, l_cmd_data)

        paramsDict = mea_utils.parseKeyValueDatasToDictionary(
            data["device_parameters"], ",", ":")

        if "pin" in paramsDict:
            pin = paramsDict["pin"]
        else:
            return False

        if "sensor_type" in paramsDict:
            type = paramsDict["sensor_type"]
        else:
            type = "generic"

        current_key = pin + "_current"
        last_key = pin + "_last"

        if pin in mem["iodata"].lower():
            val = mem["iodata"][pin]
            last_val = 0

            try:
                mem[last_key] = mem[current_key]
            except:
                mem[last_key] = 0

            strVal = ""
            if pin[0] == "d":
                if val == 1:
                    mem[current_key] = "high"
                else:
                    mem[current_key] = "low"
                logval = val
            else:
                if "compute" in paramsDict:
                    x = val
                    y = eval(paramsDict["compute"])
                    logval = round(y, 2)
                else:
                    logval = val
                mem[current_key] = logval

            if mem[current_key] != mem[last_key]:
                if "log" in paramsDict and paramsDict["log"].lower() == "yes":
                    if "unit" in paramsDict:
                        unit = int(paramsDict["unit"])
                    else:
                        unit = 0
                    mea.addDataToSensorsValuesTable(id_sensor, logval, unit,
                                                    val, "")

                xplMsg = mea_utils.xplMsgNew("me", "*", "xpl-trig", "sensor",
                                             "basic")
                mea_utils.xplMsgAddValue(xplMsg, "device",
                                         data["device_name"].lower())
                mea_utils.xplMsgAddValue(xplMsg, "current", mem[current_key])
                mea_utils.xplMsgAddValue(xplMsg, "type", type)
                mea_utils.xplMsgAddValue(xplMsg, "last", mem[last_key])
                mea.xplSendMsg(xplMsg)

                return True

    return False
Exemplo n.º 47
0
def mea_xplCmndMsg(data):
   fn_name=sys._getframe().f_code.co_name
   try:
      id_sensor=data["device_id"]
   except:
      verbose(2, "ERROR (", fn_name, ") - device_id not found")
      return 0
   
   mem=mea.getMemory(id_sensor)
  
   paramsDict=mea_utils.parseKeyValueDatasToDictionary(data["device_parameters"], ",", ":")
   
   if "pin" in paramsDict:
      pin=paramsDict["pin"].lower()
   else:
      return False
   
   if "sensor_type" in paramsDict:
      type=paramsDict["sensor_type"]
   else:
      type="generic"
   
   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   if x["schema"]=="sensor.request":
      current_key=pin+"_current"
      last_key=pin+"_last"
      if body["type"]==type:
         try:
            xplMsg=mea_utils.xplMsgNew("me", target, "xpl-stat", "sensor", "basic")
            mea_utils.xplMsgAddValue(xplMsg,"device", data["device_name"].lower())
            if body["request"]=="current":
               mea_utils.xplMsgAddValue(xplMsg,"current",mem[current_key])
            elif body["request"]=="last":
               mea_utils.xplMsgAddValue(xplMsg,"last",mem[last_key])
            else:
               verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
               return False
            mea_utils.xplMsgAddValue(xplMsg,"type",type)
         except:
            verbose(2, "ERROR (", fn_name, ") - can't create xpl message")
            return False
      else:
         verbose(2, "ERROR (", fn_name, ") - invalid type (", body["type"],")")
         return False

      mea.xplSendMsg(xplMsg)
      return True

   elif x["schema"]=="control.basic":
      if body["type"]=="output":
         if body["current"].lower()=="low":
            mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], pin, 4);
            mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], "AC", "");
            return True
         elif body["current"].lower()=="high":
            mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], pin, 5);
            mea.sendXbeeCmd(data["ID_XBEE"], data["ADDR_H"], data["ADDR_L"], "AC", "");
            return True
         else:
            return False
      else:
         verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
         return False
   else:
      verbose(2, "ERROR (", fn_name, ") - invalid schema (", x["schema"],")")
      return False
Exemplo n.º 48
0
def mea_init(data):
    fn_name = sys._getframe().f_code.co_name

    verbose(9, "INFO  (", fn_name, ") - lancement mea_init")

    if "interface_parameters" in data:
        mem = {}
        try:
            mem = mea.getMemory(data["interface_id"])
        except:
            verbose(2, "ERROR (", fn_name, ") - can't acces share memory")
            return False

        paramsList = mea_utils.parseKeyValueDatasToList(
            data["interface_parameters"], ",", ":")
        if paramsList != None:
            for i in paramsList:
                numVal = -1
                alphaVal = ""

                if i[0][0] != "@":
                    verbose(3, "ERROR (", fn_name, ") - syntaxe error :", i[0],
                            "not an AT command, skipped")
                    continue

                if i[1] != None:
                    if i[1][0:2] == "0x":
                        try:
                            numVal = int(i[1], 16)
                        except:
                            alphaVal = i[1]
                    else:
                        try:
                            numVal = int(i[1], 10)
                        except:
                            alphaVal = i[1]
                    # commande AT ?
                    if len(i[0]) == 3:
                        if numVal >= 0:  # commande at avec parametre numerique
                            ret = mea.sendXbeeCmd(data["ID_XBEE"], -1, -1,
                                                  i[0][1:3].upper(), numVal)
                            if ret == 0:
                                verbose(5, "WARNING (", fn_name,
                                        ") - Transmission error for", i[0],
                                        "= ", numVal)
                        else:  # commande at avec parametre alpha-numerique
                            ret = mea.sendXbeeCmd(data["ID_XBEE"], -1, -1,
                                                  i[0][1:3].upper(), alphaVal)
                            if ret == 0:
                                verbose(5, "WARNING (", fn_name,
                                        ") - Transmission error for", i[0],
                                        "= ", alphaVal)
                    else:
                        verbose(5, "WARNING (", fn_name, ") - syntaxe error :",
                                i[0], "not an at cmnd, skip")
                else:
                    if len(i[0]) == 3:  # commande at sans parametre
                        ret = mea.sendXbeeCmd(data["ID_XBEE"], -1, -1,
                                              i[0][1:3].upper(), "")
                        if ret == 0:
                            verbose(3, "ERROR (", fn_name,
                                    ") - Transmission error for", i[0], "= ",
                                    numVal)
            return True

        else:
            return False
    else:
        return False
Exemplo n.º 49
0
def mea_xplCmndMsg(data):
   fn_name=sys._getframe().f_code.co_name

   try:
      id_sensor=data["device_id"]
      parameters=data["device_parameters"]
      typeoftype=data["typeoftype"]

#      id_driver=data["driver_id"]
      api_key=data["api_key"]
   except:
      verbose(2, "ERROR (", fn_name, ") - invalid data")
      return 0

#   verbose(1, mea.interfaceAPI(id_driver, api_key, "test"))

   mem=mea.getMemory(id_sensor)

   paramsDict=mea_utils.parseKeyValueDatasToDictionary(parameters, ",", ":")

   x=data["xplmsg"]
   body=x["body"]

   target="*"
   if "source" in x:
      target=x["source"]

   channel = -1;
   current = -1;
   if x["schema"]=="control.basic" and typeoftype == 1:
     try:
        if body["type"] == "output":
           if body["current"]=="high":
              current = 100;
           elif body["current"]=="low":
              current = 0; 

           if current <> -1:
              channel = ord(paramsDict["channel"][0]) - ord('A');
              buf=bytearray()
              buf.append(0x01)
              buf.append(channel & 0b11111)
              buf.append(current & 0b1111111)

#              mea.sendEnoceanRadioErp1Packet(data["ID_ENOCEAN"], 0xD2, 0, data["ENOCEAN_ADDR"], buf)
#              mea.interfaceAPI(id_driver, api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
              mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)

              try:
                 if paramsDict["force_status"]=="yes":
                    channel = ord(paramsDict["channel"][0]) - ord('A');
                    buf=bytearray()
                    buf.append(0x03)
                    buf.append(channel & 0b11111)
#                    mea.sendEnoceanRadioErp1Packet(data["ID_ENOCEAN"], 0xD2, 0, data["ENOCEAN_ADDR"], buf)
#                    mea.interfaceAPI(id_driver, api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
                    mea.interfaceAPI(api_key, "sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
              except Exception as e:
                 verbose(2, "ERROR (", fn_name, ") - can't query device: ", str(e)) 
                 pass

     except Exception as e:
        verbose(2, "ERROR (", fn_name, ") - can't create/send enocean packet: ", str(e))
        return False
 
   elif x["schema"]=="sensor.request" and typeoftype == 0:
      if body["request"]=="current":
         try:
            buf=bytearray()
            channel = ord(paramsDict["channel"][0]) - ord('A');
            buf.append(0x03);
            buf.append(channel & 0b11111);
#            mea.sendEnoceanRadioErp1Packet(data["ID_ENOCEAN"], 0xD2, 0, data["ENOCEAN_ADDR"], buf)
#            mea.interfaceAPI(id_driver, api_key,"sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
            mea.interfaceAPI(api_key,"sendEnoceanRadioErp1Packet", 0xD2, 0, data["ENOCEAN_ADDR"], buf)
         except Exception as e:
            verbose(2, "ERROR (", fn_name, ") - can't query device: ", str(e))
            return False

      else:
         verbose(2, "ERROR (", fn_name, ") - invalid request (", body["request"],")")
         return False

      return True

   return False