3.0 KiB
General node file.
This File includes several main (verry important) components: The Node parent class and the database log- function.
The database funcion is used in almost every class and almost every function, so I put it here in a centeral location.
The reason it isn't in the main file is because the main file imports all classes and this function, but once the classes are called, this function can't be called up. So it needed to be in a file where all other files take information from and not put information in.
The file begings with importing a library that handles the database connection.
#Importing a database library to connect to the database.
import mysql.connector
Here the database log-in function is made, this allows functions to call for it and make a connection.
def dbLogin():
#This variable is used as a latch point to connect to the database with the correct log-in.
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="**********",
database="NodeData"
)
return mydb
After the function, a central class is made to act as a parent class for every other class that has something to do with the nodes and the data.
The class has some interchangable variables and primairly asks the incomming data for its mac adress and looks for any similarities.
It primairly gives the main MAC-address over to the child-classes so these can be used.
This class might seem small, but is not to be underestimated.
At the start of every class the "init" function is called. (In javascript this is known as the "constructor". For further information visit https://www.w3schools.com/python/gloss_python_class_init.asp)
The parent node is able to be further evolved, but for now is able do always provide the node ID to all child-classes. and a variable with the MAC-addresses.
# A general class which acts as a database connector and a node identifier
class Node():
def __init__(self, macAdress):
self.macAdress = macAdress
self.id = None
The function below uses the infromation from the database to find the corresponding node ID from the gotten MAc-address.
It searches inside of the database and finds a match with the given MAC-address.
It first makes a connection with the database by calling the previous function, then it executes the given querry, and searches for the node ID corresponding with the inserted MAC-address.
After this search, it inserts that given id into the ID variable.
def getNodeId(self):
id = (self.macAdress,)
#loging in
mydb = dbLogin()
#make a cursor.
cursor = mydb.cursor()
cursor.execute("""SELECT nodeID FROM Node WHERE MAC = %s""", id)
#get all the data
data = cursor.fetchall()
#make a for-loop to go along all the tuples in the data, and then all items in the tupe and those items get put into the ID
for tuples in data:
for item in tuples:
self.id = item