Esempio n. 1
0
def Start():
    # Make the "modbus" file as executable
    st = os.stat(EXECUTABLE_FILENAME)
    os.chmod(EXECUTABLE_FILENAME, st.st_mode | stat.S_IEXEC)
    # Loading devices configuration
    lastQuery = {}
    try:
        if Constellation.GetSetting("Devices"):
            for device in json.loads(Constellation.GetSetting("Devices")):
                Constellation.WriteInfo(
                    "Registering '%s' (interval: %d ms)" %
                    (device["Name"], device["RequestInterval"]))
                lastQuery[device["Name"]] = 0
                typeDescriptor = []
                for prop in device["Properties"]:
                    typeDescriptor.append({
                        "Name":
                        prop["Name"],
                        "Type":
                        prop["Type"] if "Type" in prop else "",
                        "Description":
                        prop["Description"] if "Description" in prop else ""
                    })
                Constellation.DescribeStateObjectType(
                    "Modbus.%s" % device["StateObjectTypeName"],
                    "%s's datas" % device["StateObjectTypeName"],
                    typeDescriptor)
            Constellation.DeclarePackageDescriptor()
    except Exception, e:
        Constellation.WriteError(
            "Error while loading the device's configuration : %s" % str(e))
Esempio n. 2
0
def OnStart():

    # Récupération des informations de configuration (clé Twitter)
    if Constellation.GetSetting("twitter_access_token_key") <> None:
        Constellation.WriteInfo("Clés de configurations récupérées : (%s ; %s)" % (Constellation.GetSetting("twitter_access_token_key"), Constellation.GetSetting("twitter_access_token_secret")))
    else:
        #Constellation.RequestSettings()
        Constellation.WriteError("Problèm lors de la configuration du paquet")

    while(True):
        # Informations basiques liées à un compte Twitter :
        basicInformations   = Tw.basicInformations(Constellation.GetSetting("twitter_access_token_key"), Constellation.GetSetting("twitter_access_token_secret"))

        # Vérification de la connexion au serveur Twitter
        try:
            basicInformations.id
        except error:
            Constellation.WriteError("Impossible de se connecter au serveur Twitter...")
        else:
            # Push des données
            Constellation.WriteInfo("Connexion au serveur Twitter : récupération des informations de @%s terminée !" % basicInformations.screen_name)
            Constellation.PushStateObject(basicInformations.screen_name, basicInformations.AsDict(), lifetime = 30)

        time.sleep(30)

    pass
Esempio n. 3
0
def Start():
    sensorType = Constellation.GetSetting("SensorType")
    if sensorType == "DHT11":
        sensor = Adafruit_DHT.DHT11
    elif sensorType == "DHT22":
        sensor = Adafruit_DHT.DHT22
    elif sensorType == "AM2302":
        sensor = Adafruit_DHT.AM2302
    else:
        Constellation.WriteError(
            "Sensor type not supported ! Check your settings")
        return
    sensorPin = int(Constellation.GetSetting("SensorPin"))
    Constellation.WriteInfo("%s on #%d is ready !" % (sensorType, sensorPin))
    lastSend = 0
    while Constellation.IsRunning:
        ts = int(round(time.time()))
        if ts - lastSend >= int(Constellation.GetSetting("Interval")):
            humidity, temperature = Adafruit_DHT.read_retry(sensor, sensorPin)
            if humidity is not None and temperature is not None:
                Constellation.PushStateObject(
                    "Temperature",
                    round(temperature, 2),
                    lifetime=int(Constellation.GetSetting("Interval")) * 2)
                Constellation.PushStateObject(
                    "Humidity",
                    round(humidity, 2),
                    lifetime=int(Constellation.GetSetting("Interval")) * 2)
                lastSend = ts
            else:
                Constellation.WriteError("Failed to get reading")
        time.sleep(1)
def Start():
    # Make the "GetTSL2561" file as executable
    st = os.stat(EXECUTABLE_FILENAME)
    os.chmod(EXECUTABLE_FILENAME, st.st_mode | stat.S_IEXEC)
    # Describe StateObject
    Constellation.DescribeStateObjectType("LightSensor.Lux",
                                          "Lux data informations",
                                          [{
                                              'Name': 'Broadband',
                                              'Type': 'int'
                                          }, {
                                              'Name': 'IR',
                                              'Type': 'int'
                                          }, {
                                              'Name': 'Lux',
                                              'Type': 'int'
                                          }])
    Constellation.DeclarePackageDescriptor()
    # Main loop
    if (bool(Constellation.GetSetting("EnableTSL2561"))):
        Constellation.WriteInfo("LuxSensor is ready !")
    lastSend = 0
    while Constellation.IsRunning:
        if (bool(Constellation.GetSetting("EnableTSL2561"))):
            ts = int(round(time.time()))
            if ts - lastSend >= int(Constellation.GetSetting("Interval")):
                DoMeasure()
                lastSend = ts
        time.sleep(1)
Esempio n. 5
0
def ProcessIncomingCall(call):
    Constellation.WriteInfo(
        "IncomingCall from '%s' (StatusCode: %s - CallID: %s)" %
        (call["Number"], call["StatusCode"], call["CallID"]))
    Constellation.SendMessage(
        Constellation.GetSetting("IncomingEventGroupName"), "IncomingCall",
        call['Number'], Constellation.MessageScope.group)
def DoMeasure():
    # Start process
    process = subprocess.Popen("./" + EXECUTABLE_FILENAME,
                               stdout=subprocess.PIPE)
    # Reading  output
    for line in iter(process.stdout.readline, ''):
        # Parse line
        matchObj = re.match(
            'RC: (\d*)\((.*)\), broadband: (\d*), ir: (\d*), lux: (\d*)', line)
        if matchObj:
            # Reading value
            returnCode = int(matchObj.group(1))
            broadband = int(matchObj.group(3))
            ir = int(matchObj.group(4))
            lux = int(matchObj.group(5))
            # Push StateObject
            if returnCode != 0:
                Constellation.WriteWarn("Unknow return code %s : %s" %
                                        (returnCode, line))
            else:
                Constellation.PushStateObject(
                    "Lux", {
                        "Broadband": broadband,
                        "IR": ir,
                        "Lux": lux
                    },
                    "LightSensor.Lux",
                    lifetime=int(Constellation.GetSetting("Interval")) * 2)
        else:
            Constellation.WriteError("Unable to parse the output: %s" % line)
Esempio n. 7
0
def ProcessIncomingSMS(sms):
    Constellation.WriteInfo("IncomingSMS from '%s' : %s" %
                            (sms["Number"], sms["Text"]))
    Constellation.SendMessage(
        Constellation.GetSetting("IncomingEventGroupName"), "IncomingSMS", {
            'Number': sms['Number'],
            'Text': sms['Text']
        }, Constellation.MessageScope.group)
    sm.DeleteSMS(Location=sms['Location'], Folder=0)
def RCtime(RCpin):
    reading = 0
    GPIO.setup(RCpin, GPIO.OUT)
    GPIO.output(RCpin, GPIO.LOW)
    time.sleep(0.1)
    GPIO.setup(RCpin, GPIO.IN)
    # This takes about 1 millisecond per loop cycle
    while (GPIO.input(RCpin) == GPIO.LOW):
        if (reading > int(Constellation.GetSetting("PhotoResistorMaxValue"))):
            break
        reading += 1
    return reading
Esempio n. 9
0
def ReadModbusRegister(registerAddress, registerCount, slaveId=1):
    '''
    Request input registers from the specified address

    :param int registerAddress: The Data Address of the first register requested
    :param int registerCount: The total number of registers requested
    :param int slaveId: The Slave Address [default: 1]
    :return list:List of register value
    '''
    debug = Constellation.GetSetting("ModbusDebug") == "true"
    # Create command
    cmdLine = [
        "./" + EXECUTABLE_FILENAME,
        str(slaveId),
        Constellation.GetSetting("Port"),
        Constellation.GetSetting("BaudRate"),
        Constellation.GetSetting("PinDE"),
        Constellation.GetSetting("PinRE"),
        str(registerAddress),
        str(registerCount)
    ]
    if debug:
        cmdLine.append("debug")
        Constellation.WriteWarn("Executing command: %s" % cmdLine)
    # Execute command
    with syncLock:
        process = subprocess.Popen(cmdLine, stdout=subprocess.PIPE)
    # Reading output
    result = []
    for line in iter(process.stdout.readline, ''):
        if debug:
            Constellation.WriteWarn(line)
        if not debug or (debug and line.startswith("Result:")):
            result = (line[7:] if debug else line).split(';')
    # Return result
    return map(int, filter(None, result))
def Start():
    GPIO.setmode(GPIO.BCM)
    Constellation.OnExitCallback = OnExit
    lastSend = 0
    currentValue = 0
    count = 0
    if (bool(Constellation.GetSetting("EnablePhotoResistor") == 'true')):
        Constellation.WriteInfo("LightSensor is ready !")
    while Constellation.IsRunning:
        if (bool(Constellation.GetSetting("EnablePhotoResistor") == 'true')):
            currentValue = currentValue + RCtime(
                int(Constellation.GetSetting("PhotoResistorPin")))
            count = count + 1
            ts = int(round(time.time()))
            if ts - lastSend >= int(Constellation.GetSetting("Interval")):
                avg = int(round(currentValue / count))
                Constellation.PushStateObject(
                    "Light",
                    avg,
                    lifetime=int(Constellation.GetSetting("Interval")) * 2)
                currentValue = 0
                count = 0
                lastSend = ts
        time.sleep(1)
Esempio n. 11
0
def OnStart():
    # Register callback on package shutdown
    Constellation.OnExitCallback = OnExit   
    
    # Write log & common properties
    Constellation.WriteInfo("Hi I'm '%s' and I currently running on %s and %s to Constellation" % (Constellation.PackageName, Constellation.SentinelName if not Constellation.IsStandAlone else 'local sandbox', "connected" if Constellation.IsConnected else "disconnected"))
    
    #  GetSetting
    Constellation.WriteInfo("Demo1 = " + str(Constellation.GetSetting("Demo1"))) # If setting not exist, return None !
    
    # Send message without parameter 
    Constellation.SendMessage("DemoPackage", "HelloWorld", [], Constellation.MessageScope.package)    
    # Send message with 2 parameter
    Constellation.SendMessage("DemoPackage", "SendMessage", [ "+33123456789", "Hi" ], Constellation.MessageScope.package)
    # Send message with complex parameter 
    Constellation.SendMessage("DemoPackage", "DemoComplex", { "A": "This is a string", "B": 123, "C": True }, Constellation.MessageScope.package)
    # Send message "MessageCallbackWithComplexeResponse" with "123" as parameter to "Demo" pasckage and write the "A" property of the response
    Constellation.SendMessageWithSaga(lambda response: Constellation.WriteInfo("A=%s" % response.A), "Demo", "MessageCallbackWithComplexResponse", 123)
    
    # Push basic StateObject
    Constellation.PushStateObject("DemoStr", "Demo de seb") # StateObject with "String" as value
    Constellation.PushStateObject("DemoBool", False, lifetime=10) # StateObject with "Bool" as value and a lifetime (10 sec here)
    Constellation.PushStateObject("DemoInt", 123, metadatas={ "DeviceId":"RPi", "Serial":"123" }) # StateObject with "Int" as value and metadatas    
    Constellation.PushStateObject("DemoFloat", 12.45, metadatas={ "DeviceId":"RPi", "Serial":"123" }, lifetime=10) # StateObject with "Float" as value, metadatas and lifetime
    
    # Custom type descriptions
    Constellation.DescribeMessageCallbackType("CredentialInfo", "Credential information", [
        { 'Name':'Username', 'Type':'string', 'Description': 'The username' },
        { 'Name':'Password', 'Type':'string', 'Description': 'The password' },
    ])
    Constellation.DescribeStateObjectType("DemoType", "Demo type", [
        { 'Name':'Sender', 'Type':'string', 'Description': 'The demo' },        
        { 'Name':'Credential', 'Type':'CredentialInfo', 'Description': 'The credential nested demo' }
    ])
    Constellation.DeclarePackageDescriptor()
    
    # Push complex StateObject
    Constellation.PushStateObject("Demo", { "Sender": "DemoPython", "Credential": { "Username": "******", "Password":"******" } }, "DemoType", { "DeviceId": "RPi", "Serial":"123" }) # StateObject with custom type
    
    # WriteInfo, WriteWarn & WriteError
    Constellation.WriteInfo("Hello world from Python !")
    Constellation.WriteWarn("This is a warning !")
    Constellation.WriteError("This is an error !")
    
    # Last StateObjects of the previous instance
    if Constellation.LastStateObjects:
        for so in Constellation.LastStateObjects:
            Constellation.WriteInfo(" + %s @ %s" % (so.Name, so.LastUpdate))
Esempio n. 12
0
def Start():
    global sm
    # Init du GSM
    Constellation.WriteInfo("Initializing GSM")
    sm = gammu.StateMachine()
    sm.ReadConfig(
        Filename=Constellation.GetSetting("GammuConfigurationFilename"))
    sm.Init()
    # Deleting SMS
    DeleteAllSMS()
    # Attach to incoming events
    AttachIncomingEvents()
    # Ready
    Constellation.WriteInfo("GSM package is started")
    while Constellation.IsRunning:
        q = sm.GetSignalQuality()
        Constellation.PushStateObject("SignalQuality", q['SignalPercent'])
        time.sleep(10)
Esempio n. 13
0
def OnStart():
    global inputs
    global outputs
    Constellation.OnExitCallback = OnExit
    # Read the configuration
    mode = None
    try:
        config = json.loads(Constellation.GetSetting("Configuration"))
        if config["PinMode"] == 'BCM':
            mode = GPIO.BCM
        elif config["PinMode"] == 'BOARD':
            mode = GPIO.BOARD
        else:
            Constellation.WriteError(
                "Invalid pin mode. Should be set to BCM or BOARD")
            return
        inputs = config['Inputs']
        outputs = config['Outputs']
    except Exception, e:
        Constellation.WriteError("Error while reading the configuration : %s" %
                                 str(e))
        return
Esempio n. 14
0
                     prop["Type"] if "Type" in prop else "",
                     "Description":
                     prop["Description"] if "Description" in prop else ""
                 })
             Constellation.DescribeStateObjectType(
                 "Modbus.%s" % device["StateObjectTypeName"],
                 "%s's datas" % device["StateObjectTypeName"],
                 typeDescriptor)
         Constellation.DeclarePackageDescriptor()
 except Exception, e:
     Constellation.WriteError(
         "Error while loading the device's configuration : %s" % str(e))
 # Request loop
 while Constellation.IsRunning:
     try:
         if Constellation.GetSetting("Devices"):
             for device in json.loads(Constellation.GetSetting("Devices")):
                 ts = int(round(time.time()))
                 if (ts - lastQuery[device["Name"]]) >= (
                         device["RequestInterval"] / 1000):
                     lastQuery[device["Name"]] = ts
                     try:
                         registers = ReadModbusRegister(
                             device["RegisterAddress"],
                             device["RegistersCount"], device["SlaveID"])
                         result = {}
                         for prop in device["Properties"]:
                             try:
                                 result[prop["Name"]] = eval(
                                     prop["Selector"])
                             except Exception, e: