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
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)
def ButtonAction(data): "Action et description d'un bouton poussoir branché sur un port GPIO du RPi poussé par packet ButtonRPi" Constellation.WriteInfo('Packet ReveilISEN / Callback ButtonAction ; pin = ' + str(data.pin) + ' / event = ' + str(data.event)) global currentDisplay # POSITION BOUTONS # [13]_____[16][19][20]_____[26] BUTTON_FARLEFT = 13 BUTTON_LEFT = 16 BUTTON_HOME = 19 BUTTON_RIGHT = 20 BUTTON_FARRIGHT = 26 # Clics simples if data.event == "clicked": if data.pin == BUTTON_FARLEFT: # Interface précédente currentDisplay = previousDisplay(currentDisplay) toDisplay(currentDisplay) if data.pin == BUTTON_LEFT: # Volume moins Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"TURNDOWN_VOLUME"}) if data.pin == BUTTON_HOME: # Lecture / pause Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"PLAY_PAUSE"}) Constellation.SendMessage(ALARM_PACKAGE, "StopRinging", alarmName) Constellation.WriteInfo("Stop la dernière alarme '%s' " % alarmName) if data.pin == BUTTON_RIGHT: # Volume plus Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"TURNUP_VOLUME"}) if data.pin == BUTTON_FARRIGHT: # Interface suivante currentDisplay = nextDisplay(currentDisplay) toDisplay(currentDisplay) # Clics doubles elif data.event == "doubleclicked": if data.pin == BUTTON_FARLEFT: # Interface précédente currentDisplay = previousDisplay(currentDisplay) toDisplay(currentDisplay) if data.pin == BUTTON_LEFT: # Volume moins Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"TURNDOWN_VOLUME"}) if data.pin == BUTTON_HOME: # Lecture / pause Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"PLAY_PAUSE"}) Constellation.SendMessage(ALARM_PACKAGE, "StopRinging", alarmName) Constellation.WriteInfo("Stop la dernière alarme '%s' " % alarmName) if data.pin == BUTTON_RIGHT: # Volume plus Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"TURNUP_VOLUME"}) if data.pin == BUTTON_FARRIGHT: # Interface suivante currentDisplay = nextDisplay(currentDisplay) toDisplay(currentDisplay) # Clics longs elif data.event == "longpressed": if data.pin == BUTTON_FARLEFT: # Snooze snooze() if data.pin == BUTTON_LEFT: # Titre précédent Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"PREVIOUS_SONG"}) if data.pin == BUTTON_HOME: # Home currentDisplay = 0 toDisplay(currentDisplay) if data.pin == BUTTON_RIGHT: # Titre suivant Constellation.SendMessage(MUSIC_PACKAGE, "MusicControl", {"instruction":"NEXT_SONG"}) if data.pin == BUTTON_FARRIGHT: # Snooze snooze()
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
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
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)
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
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
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)
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
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)
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))
def OnStart(): Constellation.WriteInfo("Démarrage du packet Reveil ISEN...") toDisplay(currentDisplay) pass
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)
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))
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)
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 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...")
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))
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 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)
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))
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))
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))
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")
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)))
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
def AjoutElementIndex(Alias, Path, type): """Procedure ajoutant un element a l'index Parametre : 1 string = le nom avec lequel on veut appeler l'element 1 string = le chemin vers l'element """ Constellation.WriteInfo("on est la ") if str(type) in { 'I', 'i', 'P', 'p', 'Image', 'image', 'picture', 'Picture' }: Constellation.WriteInfo("on est la ") #nouveauChemin = regroupe4ImagesEn1(Alias, Path) Path = nouveauChemin #change le repertoire de travail pour le bureau os.chdir(os.path.expanduser('~') + '\\Desktop\\EHolographerW') #ouvre le fichier d'index en mode ajouter du texte fichier = open('Index.txt', 'a') # écrit un retour a la ligne puis les caracteristique de l'element fichier.write("\n" + Alias + " " + Path) fichier.close()
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)