f = open("/sys/class/leds/igt30::usr" + str(i) + "/brightness", "w") f.write("1") f.close() # dependently of request method we send different data back def on_server_side_rpc_request(request_id, request_body): print(request_id, request_body) if request_body["method"] == "sendCommand": print(2) client.send_rpc_reply(request_id, {"CPU percent": psutil.cpu_percent()}) elif request_body["method"] == "getValue": client.send_rpc_reply(request_id, {"value": 0}) elif request_body["method"] == "setValue": if request_body["params"] == True: print(1) led(4, 1) else: print(0) led(4, 0) client = TBDeviceMqttClient("demo.thingsboard.io", "wjH4O6ArXM535TBSPyxO") client.set_server_side_rpc_request_handler(on_server_side_rpc_request) client.connect() while True: time.sleep(1) #print( psutil.cpu_percent()) #print( psutil.virtual_memory().percent)
def main(): # Grove - Servo connected to PWM port servo = GroveServo(12) servo_angle = 90 # Grove - mini PIR motion pir_sensor connected to port D5 pir_sensor = GroveMiniPIRMotionSensor(5) # Grove - Ultrasonic Ranger connected to port D16 ultrasonic_sensor = GroveUltrasonicRanger(16) # Grove - LED Button connected to port D18 button = GroveLedButton(18) # Grove - Moisture Sensor connected to port A0 moisture_sensor = GroveMoistureSensor(0) # Grove - Light Sensor connected to port A2 light_sensor = GroveLightSensor(2) light_state = False # Grove - Temperature&Humidity Sensor connected to port D22 dht_sensor = DHT('11', 22) # Callback for server RPC requests (Used for control servo and led blink) def on_server_side_rpc_request(request_id, request_body): log.info('received rpc: {}, {}'.format(request_id, request_body)) if request_body['method'] == 'getLedState': client.send_rpc_reply(request_id, light_state) elif request_body['method'] == 'setLedState': light_state = request_body['params'] button.led.light(light_state) elif request_body['method'] == 'setServoAngle': servo_angle = float(request_body['params']) servo.setAngle(servo_angle) elif request_body['method'] == 'getServoAngle': client.send_rpc_reply(request_id, servo_angle) # Connecting to ThingsBoard client = TBDeviceMqttClient(thingsboard_server, access_token) client.set_server_side_rpc_request_handler(on_server_side_rpc_request) client.connect() # Callback on detect the motion from motion sensor def on_detect(): log.info('motion detected') telemetry = {"motion": True} client.send_telemetry(telemetry) time.sleep(5) # Deactivating the motion in Dashboard client.send_telemetry({"motion": False}) log.info("Motion alert deactivated") # Callback from button if it was pressed or unpressed def on_event(index, event, tm): if button._GroveLedButton__btn.is_pressed(): log.debug('button: single click') telemetry = {"button_press": True} client.send_telemetry(telemetry) log.info("Pressed") else: log.debug('button: single click') telemetry = {"button_press": False} client.send_telemetry(telemetry) log.info("Unpressed") if event & Button.EV_SINGLE_CLICK: button.led.light(True) elif event & Button.EV_DOUBLE_CLICK: button.led.blink() elif event & Button.EV_LONG_PRESS: button.led.light(False) # Adding the callback to the motion sensor pir_sensor.on_detect = on_detect # Adding the callback to the button button.on_event = on_event try: while True: distance = ultrasonic_sensor.get_distance() log.debug('distance: {} cm'.format(distance)) humidity, temperature = dht_sensor.read() log.debug('temperature: {}C, humidity: {}%'.format( temperature, humidity)) moisture = moisture_sensor.moisture log.debug('moisture: {}'.format(moisture)) log.debug('light: {}'.format(light_sensor.light)) # Formatting the data for sending to ThingsBoard telemetry = { 'distance': distance, 'temperature': temperature, 'humidity': humidity, 'moisture': moisture, 'light': light_sensor.light } # Sending the data client.send_telemetry(telemetry).get() time.sleep(.1) except Exception as e: raise e finally: client.disconnect()
def main(): #declaration des ports temperature temp_meteo_1 = 2 temp_meteo_2 = 3 temp_meteo_3 = 4 temp_meteo_4 = 5 temp_piece = 6 temp_exte = 16 #declaration des ports relais chauffe_meteo = 8 chauffe_piece = 15 ventilateur = 14 grovepi.pinMode(chauffe_meteo, "OUTPUT") grovepi.pinMode(chauffe_piece, "OUTPUT") grovepi.pinMode(ventilateur, "OUTPUT") #declaration led led = 7 count = 4 grovepi.pinMode(led, "OUTPUT") grovepi.analogWrite(led, 255) #déclaration des différents états à gérer #état des chauffages ChauffePieceState = False ChauffeMeteoState = False #etat des ventilateurs VentilateurState = False #etat des modes de chauffages MeteoAutoState = False PieceAutoState = False # Définition de la fonction servant à gérer les RPC (remote prcedure calls) entre l'interface et le rapsberry def on_server_side_rpc_request(request_id, request_body): #on affiche en log le rpc reçu log.info('received rpc: {}, {}'.format(request_id, request_body)) #get et set du chauffage de la piéce if request_body['method'] == 'getChauffePieceState': client.send_rpc_reply(request_id, ChauffePieceState) elif request_body['method'] == 'setChauffePieceState': ChauffePieceState = request_body['params'] grovepi.digitalWrite(chauffe_piece, ChauffePieceState) #get et set du chauffage de la météo elif request_body['method'] == 'setChauffeMeteoState': ChauffeMeteoState = request_body['params'] grovepi.digitalWrite(chauffe_meteo, ChauffeMeteoState) elif request_body['method'] == 'getChauffeMeteoState': client.send_rpc_reply(request_id, ChauffeMeteoState) #get et set de l'activation des ventilateurs elif request_body['method'] == 'setVentilateurState': VentilateurState = request_body['params'] grovepi.digitalWrite(ventilateur, VentilateurState) elif request_body['method'] == 'getVentilateurState': client.send_rpc_reply(request_id, VentilateurState) #get et set des modes de chauffages piéce et météo elif request_body['method'] == 'getMeteoAutoState': client.send_rpc_reply(request_id, MeteoAutoState) elif request_body['method'] == 'setMeteoAutoState': MeteoAutoState = request_body['params'] elif request_body['method'] == 'getPieceAutoState': client.send_rpc_reply(request_id, PieceAutoState) elif request_body['method'] == 'setPieceAutoState': PieceAutoState = request_body['params'] # Connection à Thingsboard client = TBDeviceMqttClient(thingsboard_server, access_token) client.set_server_side_rpc_request_handler(on_server_side_rpc_request) client.connect() #fonction retournant un dictionnaire avec toutes les temperatures def getTemperatures(): Temperatures = {} Temperatures['TemperatureMeteo1'] = grovepi.dht(temp_meteo_1, 1)[0] if isnan(Temperatures['TemperatureMeteo1']): Temperatures['TemperatureMeteo1'] = 0 Temperatures['TemperatureMeteo2'] = grovepi.dht(temp_meteo_2, 1)[0] if isnan(Temperatures['TemperatureMeteo2']): Temperatures['TemperatureMeteo2'] = 0 Temperatures['TemperatureMeteo3'] = grovepi.dht(temp_meteo_3, 1)[0] if isnan(Temperatures['TemperatureMeteo3']): Temperatures['TemperatureMeteo3'] = 0 Temperatures['TemperatureMeteo4'] = grovepi.dht(temp_meteo_4, 1)[0] if isnan(Temperatures['TemperatureMeteo4']): Temperatures['TemperatureMeteo4'] = 0 #moyenne des Températures extérieures TemperatureMoyenneMeteo = mean([ Temperatures.get('TemperatureMeteo1'), Temperatures.get('TemperatureMeteo2'), Temperatures.get('TemperatureMeteo3'), Temperatures.get('TemperatureMeteo4') ]) Temperatures['TemperatureMoyenneMeteo'] = TemperatureMoyenneMeteo if isnan(Temperatures['TemperatureMoyenneMeteo']): Temperatures['TemperatureMoyenneMeteo'] = 0 Temperatures['TemperaturePiece'] = grovepi.dht(temp_piece, 1)[0] if isnan(Temperatures['TemperaturePiece']): Temperatures['TemperaturePiece'] = 0 Temperatures['TemperatureExte'] = grovepi.dht(temp_exte, 1)[0] if isnan(Temperatures['TemperatureExte']): Temperatures['TemperatureExte'] = 0 return Temperatures #fonbction qui permet de déterminer l'état de chauffage nécessaire dans la piéce def HotOrColdPiece(TemperaturePiece): etat = False #ouverture du CSV CsvPiece = open("/home/pi/GrovePi/YES/automatisation/piece.csv", "r+") reader = csv.reader(CsvPiece) i = 0 for row in reader: #si On est à la premiére itération on regarde le mode de chauffage if i == 1: mode = row[0] log.info(mode) if i >= 1: #Si on est en monde conventionnel on récupére les créneux en les transformant #en format datetime.datetime.time(), on regarde si l'heure actuelle appartient à ce créneau #si c'est le cas on regarde la température nécessaire dans ce créneau et on en déduit l'état du #chauffage if mode == 'conv': debut = datetime.datetime.strptime(row[1], '%H:%M:%S').time() fin = datetime.datetime.strptime(row[2], '%H:%M:%S').time() if debut <= datetime.datetime.now().time() <= fin: log.info('bon créneau') if TemperaturePiece > int(row[3]): etat = False else: etat = True break #En mode smart on récupérer seulement l'état rentré du côté Matlab dans la derniére colonne du CSV if mode == "smart": if int(row[4]) == 1: etat = True else: etat = False break i = i + 1 CsvPiece.close() return etat #fonction qui génére l'état de la météo de maniére aléatoire def HotOrColdMeteo(TemperatureMoyenneMeteo): etat = random.choice((True, False)) return etat try: while True: #Obtention de toutes les données nécessaires Telemetry = getTemperatures() #si le chuffage de la piéce est en mode auto on génére l'état de la résistance grace à la fonction prédéfinie if PieceAutoState: print('mode auto') grovepi.digitalWrite( chauffe_piece, HotOrColdPiece(Telemetry['TemperaturePiece'])) #Si le chauffage de la météo est en mode auto on génére l'état des résistances et des ventilateurs en fonction de lma fonction prédéfinie if MeteoAutoState: if HotOrColdMeteo(Telemetry['TemperatureMoyenneMeteo']): grovepi.digitalWrite(chauffe_meteo, True) grovepi.digitalWrite(ventilateur, False) else: grovepi.digitalWrite(chauffe_meteo, False) grovepi.digitalWrite(ventilateur, True) log.info(Telemetry) #On envoie les données de telpératures à Thingsboard client.send_telemetry(Telemetry).get() #On crée la nouvelle ligne qui sera insérée dans le CSV ligne = [0, 0, 0, 0, 0, 0, 0, 0] ligne[0] = str(datetime.datetime.now()) ligne[1] = str(Telemetry['TemperatureMeteo1']) ligne[2] = str(Telemetry['TemperatureMeteo2']) ligne[3] = str(Telemetry['TemperatureMeteo3']) ligne[4] = str(Telemetry['TemperatureMeteo4']) ligne[5] = str(Telemetry['TemperatureMoyenneMeteo']) ligne[6] = str(Telemetry['TemperaturePiece']) ligne[7] = str(Telemetry['TemperatureExte']) f = open( '/home/pi/Desktop/DataTemperatures/' + datetime.datetime.now().strftime('%d:%m:%y') + '-dataTemp.csv', 'a') writer = csv.writer(f) writer.writerow(ligne) log.info('written in csv') f.close() #condition sécuritaire si la température dépasse les 60 on quitte la boucle et va directeent au finally ou les actionneurs sont arretes if Telemetry["TemperatureMoyenneMeteo"] >= 60 or Telemetry[ "TemperaturePiece"] >= 60: break #Ici on décide tous les combien de temps la prise de température doit être faite ainsi que l'actvation ou non des chauffages time.sleep(2) except Exception as e: raise e log.warning(e) finally: log.info("client disconnect") client.disconnect() grovepi.digitalWrite(chauffe_piece, False) grovepi.digitalWrite(chauffe_meteo, False) grovepi.digitalWrite(ventilateur, True)