Skip to content
Snippets Groups Projects
Commit 12bbad8d authored by KANGOUTE's avatar KANGOUTE
Browse files

Ajout des codes de la lopy4 et de l'extration des données depuis TTN pour...

Ajout des codes de la lopy4 et de l'extration des données depuis TTN pour l'inserer dans la bd locale
parent 9c342a1d
No related branches found
No related tags found
No related merge requests found
import mysql.connector
from datetime import datetime
def sendlastlinetodb():
# Connect to your MySQL database
conn = mysql.connector.connect(
host='localhost',
user='root',
password='',
database='projetsmartgarden'
)
cursor = conn.cursor()
# Read data from the file
now = datetime.now()
file_path = now.strftime("%Y%m%d") + "useful_data.txt"
# file_path = "20231206useful_data.txt"
# Read all lines from the file
with open(file_path, 'r') as file:
lines = file.readlines()
last_line = lines[-1]
# Convert the string representation of a dictionary to an actual dictionary
data_dict = eval(last_line)
print("data_dict = ", data_dict)
# Iterate through the sensors in the file
for sensor_name, sensor_value in data_dict.items():
# Search for the sensor in the capteur table
cursor.execute("""
SELECT capteur.id_capteur, parcelle.id_parcelle, parcelle.nom, jardin.id_jardin
FROM capteur
JOIN parcelle ON capteur.id_parcelle_fk = parcelle.id_parcelle
JOIN jardin ON parcelle.id_jardin_fk = jardin.id_jardin
WHERE capteur.nom = %s
""", (sensor_name,))
result = cursor.fetchone()
print("result = ",result)
if result:
id_capteur, id_parcelle, nom_parcelle, id_jardin = result
# Insert the data into the releve table
cursor.execute("""
INSERT INTO releve (id_capteur_fk, valeur)
VALUES (%s, %s)
""", (id_capteur, sensor_value))
# Commit the changes
conn.commit()
print(f"Data inserted for sensor '{sensor_name}' in parcel '{nom_parcelle}' of jardin '{id_jardin}'.")
else:
print(f"Sensor '{sensor_name}' not found in the database.")
# Close the connection
conn.close()
print("Execution complete!")
# Call the function to send data to the database
#sendlastlinetodb()
from network import LoRa
import socket
import time
import struct
import ubinascii
import binascii
import pycom
from machine import enable_irq, disable_irq, Pin
from dht import DTH
import machine
###################################################################################################################
def connect_to_ttn(lora_object):
"""Receives a lora object and tries to join"""
# join a network using OTAA (Over the Air Activation),
# choose dr = 0 if the gateway is not close to your device, try different dr if needed
lora_object.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0, dr=0)
# wait until the module has joined the network
pycom.rgbled(0x7f7f00) #yellow
while not lora_object.has_joined():
time.sleep(2.5)
print('Not yet joined...')
lora.nvram_erase()
pycom.heartbeat(False)
app_eui = ubinascii.unhexlify('0000000000000000')
app_key = ubinascii.unhexlify('89DFE3889B342C57A54D0FB534B7ED85') # replace the dash by the AppKey provided by TTN
#uncomment to use LoRaWAN application provided dev_eui
dev_eui = ubinascii.unhexlify('70B3D5499B36F758') # replace the dash by the DevEUI provided to TTN
pycom.rgbled(0xff0000) #red
time.sleep(1)
# configure the parameters of LoRaWAN, authorize adaptive datarate and choose a CLASS C device
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, device_class=LoRa.CLASS_C, adr=False)
print('DevEUI : ', binascii.hexlify(lora.mac()).upper())
lora.nvram_restore() #if there is nothing to restore it will return a False
connect_to_ttn(lora)
print("CONNECTED!!")
pycom.rgbled(0x00ff00) #green
# create a LoRa socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
# set the LoRaWAN data rate
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 0)
# make the socket blocking
s.setblocking(True)
###################################################################################################################
#Mettre votre n° de broche
th = DTH('P8')
pycom.heartbeat(False)
#ADC capteur
adc = machine.ADC() # create an ADC object
apin = adc.channel(pin='P13') # create an analog pin on P13 Funduino Moisture sensor
apin2 = adc.channel(pin='P14') # create an analog pin on P14 DFROBOT Moisture sensor
while True:
result = th.read()
while not result.is_valid():
time.sleep(.5)
result = th.read()
print('Temperature:', result.temperature)
print('Relativity Humidity:', result.humidity)
val = apin() # read an analog value Funduino Moisture sensor
valp = int(val*(100/4096)) #int part (soulement 100 valeurs)
print('Humidity floor 1:',valp,'%')
val2 = apin2() # read an analog value DFROBOT Moisture sensor
valp2 = int(val2*(100/4096)) #int part (soulement 100 valeurs)
print('Humidity floor 2:',valp2,'%')
# si le donées < 32 le code affichage format HEXA
# si le donées => 32 le code affichage format CHAR
#Temperature
temp = bytes([result.temperature]) #convert to char de données
#print('Sending Temperature: ',temp)
#s.send(temp)
#Humidity relativity
RHumidity = bytes([result.humidity]) #convert to char de données
#print('Sending Humidity Relativity: ',RHumidity)
#s.send(RHumidity)
#Humidity floor 1
Humidity1 = bytes([valp]) #convert to char de données
#print('Sending Humidity floor 1: ',Humidity1)
#s.send(Humidity1)
#Humidity floor 2
Humidity2 = bytes([valp2]) #convert to char de données
#print('Sending Humidity floor 2: ',Humidity2,'\n')
#s.send(Humidity2)
meteo = temp + RHumidity + Humidity1 + Humidity2
print('Sending: ')
print('Temperature: ',temp ,'Relativity Humidity : ',RHumidity ,'Humidity floor 1 : ',Humidity1 ,'Humidity floor 2 : ',Humidity2)
s.send(meteo)
print('\n')
\ No newline at end of file
#!/usr/bin/python3
# Connect to TTS MQTT Server and receive uplink messages using the Paho MQTT Python client library
#
# Original source:
# https://github.com/descartes/TheThingsStack-Integration-Starters/blob/main/MQTT-to-Tab-Python3/TTS.MQTT.Tab.py
#
# Instructions to use Eclipse Paho MQTT Python client library:
# https://www.thethingsindustries.com/docs/integrations/mqtt/mqtt-clients/eclipse-paho/)
#
import os
import sys
import logging
import paho.mqtt.client as mqtt
import json
import csv
import random
from datetime import datetime
from insertdatatodb import sendlastlinetodb
#from insertdatatodb01 import sendlastlinetodb as send2
# Procedure to get the USER, PASSWORD, PUBLIC_TLS_ADDRESS and PUBLIC_TLS_ADDRESS_PORT:
# 1. Login to The Things Stack Community Edition console
# https://console.cloud.thethings.network/
# 2. Select Go to applications
# 3. Select your application
# 4. On the left hand side menu, select Integrations | MQTT
# 5. See Connection credentials
# 6. For the password press button: Generate new API key
# Each time you press this button a new password is generated!
# The password looks like:
# NNSXS.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#
USER = "tp-lora-cooc@ttn"
PASSWORD = "NNSXS.XU7AOP3H2HCNIGDHAB7QM6AVK7O2C7CR5LQJSMA.DPBD6PLGSBSQRBFS3CL4APXCQMVMKGV6CBDYNSDZD4LQD57BF6LA"
PUBLIC_TLS_ADDRESS = "eu1.cloud.thethings.network"
PUBLIC_TLS_ADDRESS_PORT = 8883
DEVICE_ID = "eui-70b3d5499b36f758"
ALL_DEVICES = False
# Meaning Quality of Service (QoS)
# QoS = 0 - at most once
# The client publishes the message, and there is no acknowledgement by the broker.
# QoS = 1 - at least once
# The broker sends an acknowledgement back to the client.
# The client will re-send until it gets the broker's acknowledgement.
# QoS = 2 - exactly once
# Both sender and receiver are sure that the message was sent exactly once, using a kind of handshake
QOS = 2
DEBUG = False
def get_value_from_json_object(obj, key):
try:
return obj[key]
except KeyError:
return '-'
def stop(client):
client.disconnect()
print("\nExit")
sys.exit(0)
# Write uplink to tab file
def save_to_file(some_json):
end_device_ids = some_json["end_device_ids"]
device_id = end_device_ids["device_id"]
application_id = end_device_ids["application_ids"]["application_id"]
received_at = some_json["received_at"]
if 'uplink_message' in some_json:
uplink_message = some_json["uplink_message"]
f_port = get_value_from_json_object(uplink_message, "f_port")
# check if f_port is found
if f_port != '-':
f_cnt = get_value_from_json_object(uplink_message, "f_cnt")
frm_payload = uplink_message["frm_payload"]
# If decoded_payload is a json object or a string "-" it will be converted to string
decoded_payload = str(get_value_from_json_object(uplink_message, "decoded_payload"))
rssi = get_value_from_json_object(uplink_message["rx_metadata"][0], "rssi")
snr = get_value_from_json_object(uplink_message["rx_metadata"][0], "snr")
data_rate_index = get_value_from_json_object(uplink_message["settings"], "data_rate_index")
consumed_airtime = get_value_from_json_object(uplink_message, "consumed_airtime")
# Daily log of uplinks
now = datetime.now()
path_n_file = now.strftime("%Y%m%d") + ".txt"
path_n_file_useful_data = now.strftime("%Y%m%d")+ "useful_data.txt"
print(path_n_file)
print(path_n_file_useful_data)
if not os.path.isfile(path_n_file):
with open(path_n_file, 'a', newline='') as tabFile:
fw = csv.writer(tabFile, dialect='excel-tab')
fw.writerow(["received_at", "application_id", "device_id", "f_port", "f_cnt", "rssi", "snr",
"data_rate_index", "consumed_airtime", "frm_payload", "decoded_payload"])
with open(path_n_file, 'a', newline='') as tabFile:
fw = csv.writer(tabFile, dialect='excel-tab')
fw.writerow([received_at, application_id, device_id, f_port, f_cnt, rssi, snr,
data_rate_index, consumed_airtime, frm_payload, decoded_payload])
# Daily log of useful (decoded payload) of uplinks
if not os.path.isfile(path_n_file_useful_data):
with open(path_n_file_useful_data, 'a', newline='') as tabFile:
fw = csv.writer(tabFile, dialect='excel-tab')
#fw.writerow(["decoded_payload"])
with open(path_n_file_useful_data, 'a', newline='') as tabFile:
fw = csv.writer(tabFile, dialect='excel-tab')
fw.writerow([decoded_payload])
sendlastlinetodb()
#send2()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("\nConnected successfully to MQTT broker")
else:
print("\nFailed to connect, return code = " + str(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, message):
print("\nMessage received on topic '" + message.topic + "' with QoS = " + str(message.qos))
parsed_json = json.loads(message.payload)
if DEBUG:
print("Payload (Collapsed): " + str(message.payload))
print("Payload (Expanded): \n" + json.dumps(parsed_json, indent=4))
save_to_file(parsed_json)
# mid = message ID
# It is an integer that is a unique message identifier assigned by the client.
# If you use QoS levels 1 or 2 then the client loop will use the mid to identify messages that have not been sent.
def on_subscribe(client, userdata, mid, granted_qos):
print("\nSubscribed with message id (mid) = " + str(mid) + " and QoS = " + str(granted_qos))
def on_disconnect(client, userdata, rc):
print("\nDisconnected with result code = " + str(rc))
def on_log(client, userdata, level, buf):
print("\nLog: " + buf)
logging_level = client.LOGGING_LEVEL[level]
logging.log(logging_level, buf)
# Generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
print("Create new mqtt client instance")
mqttc = mqtt.Client(client_id)
print("Assign callback functions")
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.on_disconnect = on_disconnect
# mqttc.on_log = on_log # Logging for debugging OK, waste
# Setup authentication from settings above
mqttc.username_pw_set(USER, PASSWORD)
# IMPORTANT - this enables the encryption of messages
mqttc.tls_set() # default certification authority of the system
# mqttc.tls_set(ca_certs="mqtt-ca.pem") # Use this if you get security errors
# It loads the TTI security certificate. Download it from their website from this page:
# https://www.thethingsnetwork.org/docs/applications/mqtt/api/index.html
# This is normally required if you are running the script on Windows
print("Connecting to broker: " + PUBLIC_TLS_ADDRESS + ":" + str(PUBLIC_TLS_ADDRESS_PORT))
mqttc.connect(PUBLIC_TLS_ADDRESS, PUBLIC_TLS_ADDRESS_PORT, 60)
if ALL_DEVICES:
print("Subscribe to all topics (#) with QoS = " + str(QOS))
mqttc.subscribe("#", QOS)
elif len(DEVICE_ID) != 0:
topic = "v3/" + USER + "/devices/" + DEVICE_ID + "/up"
print("Subscribe to topic " + topic + " with QoS = " + str(QOS))
mqttc.subscribe(topic, QOS)
#sendlastlinetodb()
else:
print("Can not subscribe to any topic")
stop(mqttc)
print("And run forever")
try:
run = True
while run:
mqttc.loop(10) # seconds timeout / blocking time
print(".", end="", flush=True) # feedback to the user that something is actually happening
except KeyboardInterrupt:
stop(mqttc)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment