Exemplo n.º 1
0
 def __init__(self,ip,port):
     threading.Thread.__init__(self)
     self.name = ""
     self.ipv4 = ip
     self.port = port
     self.socket = None
     self.available = False
     self.zigbee = False
     self.zigbee_properties = None
     self.zigbee_addr_long = ''
     self.zigbee_addr_short = ''
     self.zigbee_cordy = False
     self.lowpan = False
     self.sensorTemp = False
     self.sensorHumdity = False
     self.status = {}
     self.daemon = True
     self.running = True
     self.queue = queue.PriorityQueue()
     self.pid = 0
     self.eid = 0
     self.packets_indicator = []
     self.get_indi = False
     self.get_packs = False
     self.keep_running = True
     self.reciver_addr_long = ''
     self.reciver_addr_short = ''
     self.temp_interval = 0
     self.humdity_interval = 0
     self.duration = 0
     self.counter = 0
     self.sender_name = ''
     self.db = DatabaseConnection()
Exemplo n.º 2
0
 def get_details_fitting_data(cls, commands: list, **kwargs):
     assert len(commands) > 0, \
         "At least one specifying command must be given"
     db_conn = DatabaseConnection()
     return db_conn.query(f"""SELECT *
         FROM {cls.get_table_name(**kwargs)}
         WHERE """ + " AND ".join([
         cls.argument_name_to_column_name(command[0]) +
         f" {command[1]} '{' '.join(command[2:])}'" for command in commands
     ]))
Exemplo n.º 3
0
 def __init__(self):
     threading.Thread.__init__(self)
     self.daemon = True
     self.queue = queue.PriorityQueue()
     self.nodes_info = [('192.168.1.209', 9998), ('192.168.1.208', 9998),
                        ('192.168.1.207', 9998)]
     self.Nodes = []
     self.running = True
     self.experiment = None
     self.db = DatabaseConnection()
     self.cordy = None
     self.setup_node()
Exemplo n.º 4
0
def create_table_volunteers():
    DatabaseConnection().change(
        """CREATE TABLE volunteers(
            personName text PRIMARY KEY NOT NULL,
            gender text NOT NULL,
            birthDate date NOT NULL,
            homeRegion text);""")
Exemplo n.º 5
0
def create_table_mysecs():
    DatabaseConnection().change(
        """CREATE TABLE mysecs(
            positionId integer PRIMARY KEY NOT NULL,
            personName text NOT NULL,
            regionName text NOT NULL,
            startDate date NOT NULL,
            endDate date);""")
Exemplo n.º 6
0
def create_table_weekends():
    DatabaseConnection().change(
        """CREATE TABLE weekends (
            weekendId integer PRIMARY KEY NOT NULL,
            weekendName text NOT NULL,
            weekendLocation text NOT NULL,
            startDate date NOT NULL,
            endDate date NOT NULL,
            regionName text NOT NULL);""")
Exemplo n.º 7
0
def create_table_regions():
    DatabaseConnection().change(
        """CREATE TABLE regions (
            regionId integer NOT NULL,
            regionName text PRIMARY KEY NOT NULL,
            regionMailName text NOT NULL,
            magazineName text NOT NULL,
            mCount integer NOT NULL,
            myCount integer NOT NULL,
            nonMCount integer NOT NULL,
            looking boolean NOT NULL);""")
Exemplo n.º 8
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle("IKnow")

        # DB-Connection
        self.dbConnection = DatabaseConnection()
        if self.dbConnection.connect():
            logging.info("Connected to the Database")
        else:
            logging.error("Failed to connect to the database")

        # Create Models
        self.tagModel = TagModel(self.dbConnection.db)
        self.knowledgeModel = KnowledgeModel(self.dbConnection.db)

        # Setup views
        self.ui.knowledgeTableView.setModel(self.knowledgeModel)
        self.ui.knowledgeTableView.hideColumn(0)
        self.ui.knowledgeTableView.setColumnWidth(1, 600)
        self.ui.knowledgeTableView.setColumnWidth(2, 700)

        self.ui.tagTreeWidget.setColumnWidth(0, 300)
        self.ui.tagTreeWidget.setColumnWidth(1, 30)

        # Load tags
        self.updateTagWidget()

        self.currentTag = None
        self.filterKnowledgeText = ""

        # Create menus
        act = QtGui.QAction("Remove selected Tag", self, statusTip="Remove the selected Tag. The child Tags are not touched.", triggered=self.removeSelectedTag)
        self.ui.tagTreeWidget.addAction(act)
        self.ui.tagTreeWidget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)

        # Connect signals and slots
        self.ui.tagTreeWidget.currentItemChanged.connect(self.tagChanged)
        self.ui.newTagButton.clicked.connect(self.showNewTagButtonDialog)
        self.ui.updateTagsButton.clicked.connect(self.updateTagWidget)
        self.ui.newKnowledgeButton.clicked.connect(self.showNewKnowledgeDialog)

        self.ui.filterTagsEdit.textChanged.connect(self.updateTagWidget)
        self.ui.filterKnowledgeEdit.textChanged.connect(self.filterKnowledgeByText)

        self.ui.knowledgeTableView.doubleClicked.connect(self.showEditKnowledgeDialog)
Exemplo n.º 9
0
from position import Position


def add_new_volunteer_and_positions():
    volunteer_name = UserInteraction.get_volunteer_name()
    add_new_volunteer(volunteer_name)
    for position_name in UserInteraction.get_position_names():
        add_new_position(position_name, volunteer_name)


def add_new_volunteer(volunteer_name):
    new_volunteer = Volunteer(name=volunteer_name,
                              birth_date=UserInteraction.get_birth_date(),
                              gender=UserInteraction.get_gender())
    new_volunteer.add_to_db()


def add_new_position(title, volunteer_name):
    new_postion = Position(title=title,
                           region=UserInteraction.get_region_name(),
                           held_by=volunteer_name,
                           start_date=UserInteraction.get_start_date(),
                           end_date=UserInteraction.get_end_date(),
                           position_id=UserInteraction.get_position_id())
    new_postion.add_to_db()


if __name__ == '__main__':
    add_new_volunteer_and_positions()
    DatabaseConnection.close()
Exemplo n.º 10
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.setWindowTitle("IKnow")

        # DB-Connection
        self.dbConnection = DatabaseConnection()
        if self.dbConnection.connect():
            logging.info("Connected to the Database")
        else:
            logging.error("Failed to connect to the database")

        # Create Models
        self.tagModel = TagModel(self.dbConnection.db)
        self.knowledgeModel = KnowledgeModel(self.dbConnection.db)

        # Setup views
        self.ui.knowledgeTableView.setModel(self.knowledgeModel)
        self.ui.knowledgeTableView.hideColumn(0)
        self.ui.knowledgeTableView.setColumnWidth(1, 600)
        self.ui.knowledgeTableView.setColumnWidth(2, 700)

        self.ui.tagTreeWidget.setColumnWidth(0, 300)
        self.ui.tagTreeWidget.setColumnWidth(1, 30)

        # Load tags
        self.updateTagWidget()

        self.currentTag = None
        self.filterKnowledgeText = ""

        # Create menus
        act = QtGui.QAction("Remove selected Tag", self, statusTip="Remove the selected Tag. The child Tags are not touched.", triggered=self.removeSelectedTag)
        self.ui.tagTreeWidget.addAction(act)
        self.ui.tagTreeWidget.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)

        # Connect signals and slots
        self.ui.tagTreeWidget.currentItemChanged.connect(self.tagChanged)
        self.ui.newTagButton.clicked.connect(self.showNewTagButtonDialog)
        self.ui.updateTagsButton.clicked.connect(self.updateTagWidget)
        self.ui.newKnowledgeButton.clicked.connect(self.showNewKnowledgeDialog)

        self.ui.filterTagsEdit.textChanged.connect(self.updateTagWidget)
        self.ui.filterKnowledgeEdit.textChanged.connect(self.filterKnowledgeByText)

        self.ui.knowledgeTableView.doubleClicked.connect(self.showEditKnowledgeDialog)

    def removeSelectedTag(self):
        selectedItem = self.ui.tagTreeWidget.selectedItems()[0]
        IDtoRemove = int(selectedItem.text(1))
        logging.debug("Remove selected Tag (ID=%d)." % IDtoRemove)
        self.tagModel.removeTag(IDtoRemove)
        self.updateTagWidget()

    def updateTagWidget(self):
        self.tagModel.updateTree()

        logging.debug("filter-Edit=%s" % self.ui.filterTagsEdit.text())
        filter = self.ui.filterTagsEdit.text()
        if filter == "":
            filterIDs = None
        else:
            foundIDs = self.tagModel.getIDsFilteredByName(filter)
            logging.debug("foundIDs=" + str(foundIDs))
            filterIDs = []
            filterIDs.extend(foundIDs)
            for ID in foundIDs:
                logging.debug("foundIDs=%s" % str(foundIDs))
                filterIDs.extend(self.tagModel.getParentIDsDownToRoot(ID))
                filterIDs.extend(self.tagModel.getAllChildIDs(ID))
            filterIDs = set(filterIDs)
            logging.debug("filterIDs=" + str(filterIDs))

        # Clear tree
        self.ui.tagTreeWidget.clear()

        # No filter applied => Show all tags
        if filter == "":
            self.tagModel.fillTreeWidgetWithTags(self.ui.tagTreeWidget)

        # Found tags with applied filter
        if filter != "" and len(foundIDs) > 0:
            self.tagModel.fillTreeWidgetWithTags(self.ui.tagTreeWidget, filterIDs=filterIDs)
            self.ui.tagTreeWidget.expandAll()

    def showNewTagButtonDialog(self):
        logging.debug("Show NewTagDialog")
        newTagDlg = NewTagDialog(self, self.tagModel, self.tagModel.tagParentsModel, parentID=self.currentTag)
        newTagDlg.exec_()
        self.updateTagWidget()

    def showNewKnowledgeDialog(self):
        logging.debug("Show NewKnowledgeDialog")
        newKnowledgeDlg = NewKnowledgeDialog(self, self.tagModel, self.tagModel.tagParentsModel, self.knowledgeModel, parentID=self.currentTag)
        newKnowledgeDlg.exec_()
        self.reloadKnowledge()

    def showEditKnowledgeDialog(self, modelIndex):
        logging.debug("Show EditKnowledgeDialog")
        logging.debug("Row=%d" % modelIndex.row())
        newKnowledgeDlg = NewKnowledgeDialog(self, self.tagModel, self.tagModel.tagParentsModel, self.knowledgeModel, editRow=modelIndex.row())
        newKnowledgeDlg.exec_()
        self.knowledgeModel.setFilterByTagID(self.currentTag)

    def tagChanged(self, current, previous):
        self.currentTag = int(current.text(1))
        logging.debug("currentTag = %d", self.currentTag)
        self.reloadKnowledge()

    def filterKnowledgeByText(self, filterText):
        self.filterKnowledgeText = filterText
        logging.debug("filterKnowledgeByText: self.filterKnowledgeText=%s" % self.filterKnowledgeText)
        self.reloadKnowledge()

    def reloadKnowledge(self):
        self.knowledgeModel.reload(self.currentTag, self.filterKnowledgeText)
Exemplo n.º 11
0
 def update_in_db(self):
     db_conn = DatabaseConnection()
     db_conn.change(self.get_update_command())
Exemplo n.º 12
0
 def add_to_db(self):
     db_conn = DatabaseConnection()
     try:
         db_conn.change(self.get_insertion_command())
     except IntegrityError:
         print(f"{sys.exc_info()[0].__name__}: {sys.exc_info()[1]}")
Exemplo n.º 13
0
class Node(threading.Thread):
    def __init__(self,ip,port):
        threading.Thread.__init__(self)
        self.name = ""
        self.ipv4 = ip
        self.port = port
        self.socket = None
        self.available = False
        self.zigbee = False
        self.zigbee_properties = None
        self.zigbee_addr_long = ''
        self.zigbee_addr_short = ''
        self.zigbee_cordy = False
        self.lowpan = False
        self.sensorTemp = False
        self.sensorHumdity = False
        self.status = {}
        self.daemon = True
        self.running = True
        self.queue = queue.PriorityQueue()
        self.pid = 0
        self.eid = 0
        self.packets_indicator = []
        self.get_indi = False
        self.get_packs = False
        self.keep_running = True
        self.reciver_addr_long = ''
        self.reciver_addr_short = ''
        self.temp_interval = 0
        self.humdity_interval = 0
        self.duration = 0
        self.counter = 0
        self.sender_name = ''
        self.db = DatabaseConnection()


        
    def node_recv_str(self):
        if self.available:
            try:
                msg = str(self.socket.recv(1024),'utf-8')
                if msg == b'':
                    print("[-] Connection Broken")
                    self.socket.close()
                return msg
            except Exception as e:
                print("[-] Could not receive: " + str(e))
                return False

    def node_recv_bytes(self):
        if self.available:
            try:
                msg = self.socket.recv(1024)
                if msg == b'':
                    print("[-] Connection Broken")
                    self.socket.close()
                return msg
            except Exception as e:
                print("[-] Could not receive: " + str(e))
                return False

    def node_send_str(self,msg):
        if self.available:
            try:
                self.socket.send(msg.encode())
                return True
            except Exception as e:
                print("[-] Could not send: " + str(e))
                self.close_socket()
                return False
        
    def extract(self,data):
        self.name = data['name']
        self.zigbee = data['zigbee']
        self.lowpan = data['lowpan']
        self.sensorTemp = data['Temperature']
        self.sensorHumdity = data['Humdity']
        self.status = {"name":self.name,
                        "zigbee":self.zigbee,
                        "lowpan":self.lowpan,
                        "Temperature":self.sensorTemp,
                        "Humdity":self.sensorHumdity}
                        
    
    def run(self):
        self.connect()
        self.collect_status()
        self.close_socket()
        self.main_loop()  
        


    def main_loop(self):
        while self.keep_running:
            if self.get_indi:
                self.clear_buffer()
                self.connect()
                self.get_indicator()
                self.close_socket()
            elif self.get_packs:
                self.connect()
                self.get_packets()
                self.close_socket()
            time.sleep(1)

    def assign_counter_message(self):
        self.node_send_str("cord")
        msg = self.socket.recv(1024)
        msg = pickle.loads(msg)
        if 'no msgs' in msg:
            self.counter = 0
        else:
            self.counter = int(msg)

    def clear_buffer(self):
        self.connect()
        self.node_send_str("zigbee/clear")
        self.packets_indicator.clear()
        self.close_socket()

    def get_packets(self):
        self.assign_counter_message()
        print("Packets: " + str(self.counter))
        for i in range(self.counter):
            self.node_send_str('gmsg')
            msg = self.socket.recv(1024)
            msg = pickle.loads(msg)
            print(msg)
            self.packets_indicator.append(msg)
            time.sleep(1)
        path = self.write_to_csvPackets()
        self.save_res(path)
        self.get_packs = False

    def save_res(self,path):
        folder_name = "results"
        output =  folder_name + "/" + path
        self.db.save_results(self.pid,self.eid,output)
        results_folder = "/home/aziz/interface/results/"
        shutil.move(path,results_folder)

    def read_temp(self):
        if self.available:
            if self.sensorTemp:
                if self.node_send_str("read/temp"):
                    read = self.node_recv_str()
                    print(read)



    def get_indicator(self):
        self.set_address_in_node()
        self.read_temp()
        self.read_humdity()
        self.get_indi = False
        path = self.write_to_csvIdicator()
        self.save_res(path)


        
    def read_temp(self):
        if self.temp_interval == 0:
            return
        tempcounter = int(self.duration/self.temp_interval)
        temp_read = 'read/temp/' + str(self.temp_interval) + "/" + str(self.duration)
        self.socket.send(temp_read.encode())
        while True:
            msg = self.socket.recv(1024)
            msg = pickle.loads(msg)
            print(msg)
            if 'done' in msg:
                print("done")
                break
            else:
                self.packets_indicator.append(msg)
            time.sleep(1)

    def read_humdity(self):
        if self.humdity_interval == 0:
            return
        humdityCounter = int(self.duration/self.humdity_interval)
        humdity_read = 'read/humdity/' + str(self.humdity_interval) + "/" + str(self.duration)
        self.socket.send(humdity_read.encode())
        while True:
            msg = self.socket.recv(1024)
            msg = pickle.loads(msg)
            print(msg)
            if 'done' in msg:
                print("done")
                break
            else:
                self.packets_indicator.append(msg)
            time.sleep(1)

    def change_Zigbee_cord(self):
        if self.available:
            if self.zigbee:
                if self.zigbee_cordy:
                    print("Already Cordinator")
                else:
                    if self.node_send_str("zigbee/changetocord"):
                        self.node_recv_str()
                        time.sleep(30)
                        self.collect_zigbee()
            else:
                print("No Zigbee")
    def change_Zigbee_route(self):
        if self.available:
            if self.zigbee:
                if not self.zigbee_cordy:
                    print("Already Router")
                else:
                    if self.node_send_str("zigbee/changetoroute"):
                        response = self.node_recv_str()
                        print(response)
                        time.sleep(30)
                        self.collect_zigbee()
            else:
                print("No Zigbee")


    def send_task(self):
        pass
                    
    def collect_status(self):
        if self.available:
            if self.node_send_str("status"):
                data = self.node_recv_str()
                print(data)
                self.extract(json.loads(data))
                self.collect_zigbee()
                
    def collect_zigbee(self):
        if self.zigbee:
            if self.node_send_str("status/zigbee"):
                zigbee_info = self.node_recv_str()
                self.extract_zigbee(json.loads(zigbee_info))
                print("zigbee: "  + str(self.zigbee_properties))

    def assign_zigbee_address(self,long_addr,short_addr):
        self.reciver_addr_long = long_addr
        self.reciver_addr_short = short_addr

    def set_address_in_node(self):
        cord_address = 'zigbee/set/'+ str(self.reciver_addr_long) + '/' + str(self.reciver_addr_short)
        self.socket.send(cord_address.encode())
        msg = self.node_recv_str()
        if 'OK  Address has been set' in msg:
            return True
        else:
            return False
    
    def close_socket(self):
        self.running = False
        self.socket.send("quit".encode())
        self.socket.close()
        
    def connect(self):
        self.socket  = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        print("[+] Connecting: " + str(self.ipv4) + " : " + str(self.port))
        try:
            self.socket.connect((self.ipv4,self.port))
            self.available = True
        except Exception as e:
            print("[-] Could not Connect To: " + str(self.ipv4) +" Because: " + str(e))
            self.available = False
            self.status = {"ip":self.ipv4,
                            "available":"no"}
            
    def extract_zigbee(self,data):
        self.zigbee_properties = data
        if self.zigbee_properties['CE'] == '1':
            self.zigbee_cordy = True
        else:
            self.zigbee_cordy = False
        self.zigbee_addr_long = "00" + self.zigbee_properties['SH'] + self.zigbee_properties['SL']
        if len(self.zigbee_properties['MY']) == 3:
            self.zigbee_addr_short = "0" + self.zigbee_properties['MY']
        else:
            self.zigbee_addr_short =  self.zigbee_properties['MY']
        
    def add_task(self,Task):
        self.queue.put(Task)


    def get_task(self):
        return self.queue.get()

    def write_to_csvIdicator(self):
        name = self.name + "-" + str(self.eid)+"-" + str(self.pid)
        path = name + ".csv"
        file = open(path,'w')
        writer = csv.writer(file)
        writer.writerow(["id","retries","discover_status","frame_id","dest_addr","deliver_status"])
        for data in self.packets_indicator:
            i_id = data['id']
            retries = data['retries']
            discover_status = data['discover_status']
            frame_id = data['frame_id']
            dest_addr = data['dest_addr']
            deliver_status = data['deliver_status']
            writer.writerow([i_id,retries,discover_status,frame_id,dest_addr,deliver_status])
        file.close()
        return path

    def write_to_csvPackets(self):
        name = self.name + "-" + str(self.eid)+"-" + str(self.pid)
        path = name + ".csv"
        file = open(path,'w')
        writer = csv.writer(file)
        writer.writerow(["sender_name","sensor","read","id","source_addr","dest_endpoint","source_endpoint","cluster","profile","options","source_addr_long"])
        for data in self.packets_indicator:
            i_id = data['id']
            rf_data = str(data['rf_data'],'utf-8')
            sensor,read = rf_data.split(' ')
            source_addr = data['source_addr']
            dest_endpoint = data['dest_endpoint']
            source_endpoint = data['source_endpoint']
            cluster = data['cluster']
            profile = data['profile']
            options = data['options']
            source_addr_long = data['source_addr_long']
            writer.writerow([self.sender_name,sensor,read,i_id,source_addr,dest_endpoint,source_endpoint,cluster,profile,options,source_addr_long])
        file.close()
        return path



    def __str__(self):
        if self.zigbee:
            return  "Name: " + self.name +"\nIpv4: " + self.ipv4 +"\nZigBeeSupport: " \
                + str(self.zigbee) + "\n6lowPanSupport: " + str(self.lowpan)  +"\nAvailable: "\
                 + str(self.available) + "\nZigbeeLongAddr: " + str(self.zigbee_addr_long) + "\nZigbeeShortAddr: " + str(self.zigbee_addr_short) + "\n"
        else:
            return  "Name: " + self.name +"\nIpv4: " + self.ipv4 +"\nZigBeeSupport: " \
                + str(self.zigbee) + "\n6lowPanSupport: " + str(self.lowpan)  +"\nAvailable: "\
                 + str(self.available) + "\n"
Exemplo n.º 14
0
def drop_old_tables():
    for table in get_all_existing_table_names():
        DatabaseConnection().change("DROP TABLE IF EXISTS {}".format(table))
Exemplo n.º 15
0
def create_table_weekend_participant():
    DatabaseConnection().change(
        """CREATE TABLE weekend_participant (
            weekendId integer NOT NULL,
            personName text NOT NULL);""")
Exemplo n.º 16
0
class ControllerManager(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True
        self.queue = queue.PriorityQueue()
        self.nodes_info = [('192.168.1.209', 9998), ('192.168.1.208', 9998),
                           ('192.168.1.207', 9998)]
        self.Nodes = []
        self.running = True
        self.experiment = None
        self.db = DatabaseConnection()
        self.cordy = None
        self.setup_node()

    def setup_node(self):
        for i in self.nodes_info:
            node = Node(i[0], i[1])
            node.start()
            self.Nodes.append(node)

    def set_cordy(self):
        for i in self.Nodes:
            if i.zigbee_cordy:
                self.cordy = i

    def run(self):
        time.sleep(5)
        self.set_cordy()
        print("[+] ControllerManager Started")
        while self.running:
            self.experiment = self.get_Experiment()
            exp_info = self.db.get_Experiment_info(self.experiment.id)
            if (exp_info['status'] == 'done'):
                print("Experiment Already Done")
                continue
            self.db.change_to_running(self.experiment.id)
            self.experiment.duration = int(exp_info['duration'])
            self.experiment.protocol = exp_info['protocol']
            self.experiment.title = exp_info['title']
            print(self.experiment.title)
            print(self.experiment.protocol)
            print(self.experiment.duration)
            self.experiment.nodes = self.db.get_Node_info(self.experiment.id)
            self.experiment.scenario = self.db.get_scenario_info(
                self.experiment.id)
            #print(self.experiment.nodes)
            #print(self.experiment.scenario)
            #print(exp_info)
            #self.setup_experiment()
            self.sensor()
            self.read_start()
            self.db.change_to_done(self.experiment.id)

    def setup_experiment(self):
        for node in self.experiment.nodes:
            for i in self.Nodes:
                if node['name'] == i.name:
                    if node['protocol'] == 'cord' and i.zigbee_cordy:
                        print(i.name + ": is coordinator")
                    elif node['protocol'] == 'cord' and not i.zigbee_cordy:
                        i.change_Zigbee_cord()
                    elif node['protocol'] == 'router' and i.zigbee_cordy:
                        i.change_Zigbee_route()
                    else:
                        print(i.name + ": is router")

    def read_start(self):
        print(self.experiment.scenario)
        for path in self.experiment.scenario:
            node1 = None
            node2 = None
            node1_id = path['en1']
            node2_id = path['en2']
            pathId = path['pid']
            print("Node1 ID : " + str(node1_id))
            print("Node2 ID : " + str(node2_id))
            node1_name = self.db.get_node_name(node1_id)
            node2_name = self.db.get_node_name(node2_id)
            print("node1 name " + str(node1_name))
            print("node2 name " + str(node2_name))
            for node in self.Nodes:
                if node.name == node1_name:
                    node1 = node
                    print(node1)
                if node.name == node2_name:
                    node2 = node
                    print(node2)
            if node2:
                long_addr = node2.zigbee_addr_long
                short_addr = node2.zigbee_addr_short
                if node1:
                    node1.assign_zigbee_address(long_addr, short_addr)
                    node1.pid = pathId
                    node1.eid = self.experiment.id
                    node2.clear_buffer()
                    node1.get_indi = True
                    while node1.get_indi:
                        time.sleep(1)
                    node2.pid = pathId
                    node2.eid = self.experiment.id
                    node2.sender_name = node1_name
                    node2.get_packs = True
                    while node2.get_packs:
                        time.sleep(1)

            else:
                print('node2 not found')

    def sensor(self):
        for node in self.experiment.nodes:
            node_name = node['name']
            print("Node: " + node['name'] + " Temp:" +
                  str(node['temperature']) + " Humdiry " +
                  str(node['humdity']))
            for anode in self.Nodes:
                if anode.name == node_name:
                    bnode = anode
                    print(bnode)
                    bnode.temp_interval = int(node['temperature'])
                    bnode.humdity_interval = int(node['humdity'])
                    bnode.duration = int(self.experiment.duration)

    def add_Experiment(self, id, priority=1):
        self.queue.put(Experiment(id, priority))

    def parse(self):
        pass

    def get_Experiment(self):
        return self.queue.get()

    def close(self):
        self.running = False
Exemplo n.º 17
0
def get_all_existing_table_names():
    return [table_tuple[0] for table_tuple
            in DatabaseConnection().query(
            "SELECT name FROM sqlite_master WHERE type='table';")]