예제 #1
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)
예제 #2
0
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)
예제 #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)
예제 #4
0
def AttachIncomingEvents():
    # Set callback handler for incoming notifications
    sm.SetIncomingCallback(ProcessIncomingEvent)
    # Enable notifications from incoming SMS
    try:
        sm.SetIncomingSMS()
    except gammu.ERR_NOTSUPPORTED:
        Constellation.WriteWarn('Incoming SMS notification is not supported.')
    # Enable notifications from calls
    try:
        sm.SetIncomingCall()
    except gammu.ERR_NOTSUPPORTED:
        Constellation.WriteWarn(
            'Incoming calls notification is not supported.')
    # Enable notifications from cell broadcast
    try:
        sm.SetIncomingCB()
    except gammu.ERR_NOTSUPPORTED:
        Constellation.WriteWarn('Incoming CB notification is not supported.')
    except gammu.ERR_SOURCENOTAVAILABLE:
        Constellation.WriteWarn(
            'Cell broadcasts support not enabled in Gammu.')
    # Enable notifications for incoming USSD
    try:
        sm.SetIncomingUSSD()
    except gammu.ERR_NOTSUPPORTED:
        Constellation.WriteWarn('Incoming USSD notification is not supported.')
예제 #5
0
def NoParamterWithCustomMessageKey():
    '''
    MessageCallback without parameters and custom key
    This MessageCallback is registered on Constellation as 'MyMethodWithWhithoutParameter'
    '''
    Constellation.WriteInfo(a)
    Constellation.WriteInfo(b)
    Constellation.WriteInfo(c)
예제 #6
0
def nextDisplay(currentDisplay):
    if currentDisplay >= len(displays)-1:
        next = 0
        Constellation.WriteInfo("Next display (1) : " + str(next))
        return 0
    else:
        next = currentDisplay + 1
        Constellation.WriteInfo("Next display (2) : " + str(next))
        return currentDisplay + 1
예제 #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)
예제 #8
0
def previousDisplay(currentDisplay):
    if currentDisplay <= 0:
        next = currentDisplay + 1
        Constellation.WriteInfo("Next display (3) : " + str(next))
        return len(displays) - 1
    else:
        next = currentDisplay + 1
        Constellation.WriteInfo("Next display (4) : " + str(next))
        return currentDisplay - 1
예제 #9
0
def CallVideo(data):
    if int(data) == 1:
        callVideo('CALL', '"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc"', '"D:\\Autre\\Demo.mp4"')

        Constellation.WriteInfo(data)
    if int(data) == 2 : 
        callVideo('CALL', '"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc"', '"D:\\Autre\\Chess.mp4"')

        Constellation.WriteInfo(data)
예제 #10
0
def MessageCallbackWithReturnAndCustomType(credential, context):
    '''
    MC with response (this is a Saga) and use a custom type as parameter (describe in the OnStart method)

    :param CredentialInfo credential: The credential infos
    :return bool:true if user match
    '''
    Constellation.WriteInfo("Sender : %s" % context.Sender.FriendlyName)
    Constellation.WriteInfo("User=%s Password=%s" % (credential.Username, credential.Password))
    return credential.Username == credential.Password
예제 #11
0
def question(token):
    if token == 00000000 - 0000 - 0000 - 0000 - 000000000000:
        Constellation.WriteInfo("token null")
    else:
        Constellation.WriteInfo(token)
        Constellation.WriteInfo("Reception of the first token")
        fichier = open('data.txt', "w")
        fichier.write(token)
        fichier.close()
        return token
예제 #12
0
def ClockUpdated(stateobject):
    global alarmName
    
    Constellation.WriteInfo("Check reveil %s" % stateobject.Name)
    if stateobject.Value.IsRinging == True:
        Constellation.WriteWarn("REVEIL '%s' en action !" % stateobject.Name)
        Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"PLAY_PLAYLIST", "uri":"spotify:user:officiallifeisstrange:playlist:1f5ZzLDTXHTDR8CYIEddpW"})
        #time.sleep(10)
        #Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"PLAY_PAUSE"})
        Constellation.SendMessage(DISPLAY_PACKAGE, "DisplayContent", {"icon":"musique", "text":stateobject.Name,"time":None,"matrix":None})
        alarmName = stateobject.Value.ClockName
예제 #13
0
def MessageCallbackWithReturn(user, password, context):
    '''
    MC with response (this is a Saga)

    :param string user: The username
    :param string password: The password
    :return bool:true if user match
    '''
    Constellation.WriteInfo("Sender : %s" % context.Sender.FriendlyName)
    Constellation.WriteInfo("User=%s Password=%s" % (user, password))
    #Constellation.SendResponse(context, user == password)  # Send response with the static SendResponse method
    #context.SendResponse(user == password)                 # Send response with the SendResponse method on context
    return user == password                                 # Send response for this current context by a simple "return" the value
예제 #14
0
def MultipleParameterCallback(a, b, c):
    '''
    This is a MessageCallback with 3 parameters

    The description can be on several lines and you can also describe the parameters like this:

    :param string a: The 'a' parameter is a string !
    :param int b: An integer parameter
    :param bool c: A boolean and optional parameter with a default value [default:true]
    '''
    Constellation.WriteInfo(a)
    Constellation.WriteInfo(b)
    Constellation.WriteInfo(c)
예제 #15
0
def OnStart():
    #declaration du StateObject
    Constellation.DescribeStateObjectType(
        "Sensors", "StateObject qui récupère données des capteurs ",
        [{
            'Name': 'CO2',
            'Type': 'int',
            'Description': 'Temperature en °C'
        }, {
            'Name': 'Soundlevel',
            'Type': 'int',
            'Description': ' intensite sonore en dB'
        }, {
            'Name': 'Temperature',
            'Type': 'float',
            'Description': 'niveau de co2(en ppm)'
        }, {
            'Name': 'Ledstate',
            'Type': 'bool',
            'Description': 'niveau de co2(en ppm)'
        }])
    #ouverture de port serie

    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"))
    connected = []
    ser = 0
    while len(connected) <= 0 and ser == 0:

        ports_series = serial.tools.list_ports.comports()

        for element in ports_series:
            connected.append(element.device)

        if len(
                connected
        ) > 0:  # on test si plusieurs ports ont été trouvée, si oui on utilise le 1er
            ser = serial.Serial(connected[0], 9600)
    ser.flushInput()

    while 1:
        #on lit le json sorti du port serie
        data = ser.readline()
        #on lui explique que c'est un json
        pushMe = json.loads(data)
        #Et on l'envoi a constellation
        Constellation.PushStateObject("Sensors", pushMe)
        time.sleep(1)
예제 #16
0
def MultipleParameterCallbackWithContext(a, b, c, context):
    '''
    This is a MessageCallback with 3 parameters and a context

    The description can be on several lines and you can also describe the parameters like this:

    :param string a: The 'a' parameter is a string !
    :param int b: An integer and optional parameter [default:10]
    :param bool c: A boolean and optional parameter with a default value [default:true]
    '''
    Constellation.WriteInfo("Sender : %s" % context.Sender.FriendlyName)
    Constellation.WriteInfo(a)
    Constellation.WriteInfo(b)
    Constellation.WriteInfo(c)
예제 #17
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
예제 #18
0
def OnStart():

    Constellation.WriteInfo("Démarrage du packet Reveil ISEN...")

    toDisplay(currentDisplay)
    
    pass
예제 #19
0
def OnStart():
    #State Object
    Constellation.PushStateObject("Holographer", {"Sender": "Holographer"},
                                  "Info", {
                                      "Device_Id": "RPi",
                                      "Etat du package": "lancé"
                                  })
예제 #20
0
def SendMessage(number, text):
    "Sends a text message to a specifed number"
    # Composition du SMS
    message = {'Text': text, 'SMSC': {'Location': 1}, 'Number': number}
    # Envoi
    Constellation.WriteInfo("Sending '%s' to %s" % (text, number))
    sm.SendSMS(message)
예제 #21
0
def onButtonEvent(button, event):

    if event == BUTTON_LONGPRESSED:
        Constellation.SendMessage("ConstellationReveilISEN", "ButtonAction", {
            "pin": button.buttonPin,
            "event": "longpressed"
        }, Constellation.MessageScope.package)
    elif event == BUTTON_CLICKED:
        Constellation.SendMessage("ConstellationReveilISEN", "ButtonAction", {
            "pin": button.buttonPin,
            "event": "clicked"
        }, Constellation.MessageScope.package)
    elif event == BUTTON_DOUBLECLICKED:
        Constellation.SendMessage("ConstellationReveilISEN", "ButtonAction", {
            "pin": button.buttonPin,
            "event": "doubleclicked"
        }, Constellation.MessageScope.package)
def OnStart():
    global strip
    strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA,
                              LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL,
                              LED_STRIP)
    strip.begin()

    Constellation.WriteInfo("Démarrage du packet AffichageLED...")
예제 #23
0
def OnStart():
    # Register callback on package shutdown
    Constellation.OnExitCallback = OnExit

    # Last StateObjects of the previous instance
    if Constellation.LastStateObjects:
        for so in Constellation.LastStateObjects:
            Constellation.WriteInfo(" + %s @ %s" % (so.Name, so.LastUpdate))
예제 #24
0
def WeatherUpdated(stateobject):
    global weatherForecastIO
    weatherForecastIO = stateobject.Value.currently

    # Si l'on se trouve sur l'écran du module, on update en live:
    if(displays[currentDisplay] == displayWeather):
        toDisplay(currentDisplay)
    
    Constellation.WriteInfo("Affichage température %s : %f°C (icone : %s)" % (stateobject.Name, stateobject.Value.currently.temperature, stateobject.Value.currently.icon))
예제 #25
0
def onEventDetect(channel):
    input = [i for i in inputs if i['Pin'] == channel]
    if any(input):
        Constellation.PushStateObject(input[0]['Name'],
                                      bool(GPIO.input(input[0]['Pin'])),
                                      metadatas={
                                          "Mode": "Input",
                                          "Pin": input[0]['Pin']
                                      })
예제 #26
0
def TwitterUpdated(stateobject):
    global twitterSO
    twitterSO   = stateobject.Value
    
    # Si l'on se trouve sur l'écran du module, on update en live:
    if(displays[currentDisplay] == displayTwitter):
        toDisplay(currentDisplay)

    Constellation.WriteInfo("Affichage de Twitter @%s : %i" % (stateobject.Name, stateobject.Value.followers_count))
예제 #27
0
def MusicUpdated(stateobject):
    global musicSO
    musicSO   = stateobject.Value
    
    # Si l'on se trouve sur l'écran du module, on update en live:
    if(displays[currentDisplay] == displayMusic):
        toDisplay(currentDisplay)

    Constellation.WriteInfo("Affichage du titre de la musique %s" % (stateobject.Value))
예제 #28
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)
예제 #29
0
def MAJPlateau(caseDeDepart, caseDarrivee):
    "Bouton qui génère le plateau suivant à partir de 2 integer - mettre 0, 0 pour générer le plateau initial"

    global IdProcI

    Constellation.WriteInfo("MAJ du plateau lancee | [case de depart = " +
                            str(caseDeDepart) + " | case d'arrivee = " +
                            str(caseDarrivee) + "]")

    global listeDesPieces
    global cheminIdImage
    global cheminScriptImage

    if ((caseDeDepart == 0) and (caseDarrivee == 0)):
        #Creation du plateau de départ quand on est en cours de jeu
        Constellation.WriteInfo("Initialisation du plateau")
        listeDesPieces = FICP.creePlateauHolographique(nomImage, [], 0, 0)

        #Fermeture d'une eventuelle image
        if (IdProcI):
            os.system("kill " + str(IdProcI))

        #Affichage de l'image
        IdProcI = SR.showImage(cheminScriptImage)

        Constellation.WriteInfo("Génération du plateau terminée")

    else:
        #Mise A Jour (MAJ) de la position des pieces sur le plateau
        listeDesPieces = FICP.creePlateauHolographique(nomImage,
                                                       listeDesPieces,
                                                       caseDeDepart,
                                                       caseDarrivee)

        #Fermeture d'une eventuelle image
        if (IdProcI):
            os.system("kill " + str(IdProcI))

        #Affichage de l'image
        IdProcI = SR.showImage(cheminScriptImage)

        Constellation.WriteInfo("Maj plateau terminée")
예제 #30
0
def ProcessIncomingEvent(sm, type, data):
    # type of action, one of Call, SMS, CB, USSD
    if type == "SMS":
        smss = sm.GetSMS(data["Folder"], data["Location"])
        for sms in smss:
            ProcessIncomingSMS(sms)
    elif type == "Call":
        ProcessIncomingCall(data)
    else:
        Constellation.WriteInfo("Received incoming event type %s, data: %s" %
                                (type, str(data)))