Beispiel #1
0
class Pinger(modules.ControlApplication):
    def __init__(self, hostList=[], interval=1):
        super(Pinger, self).__init__()
        self.log = logging.getLogger('Pinger')

        self.pingInterval = interval
        self.pingTimer = TimerEventSender(self, PingTimeEvent)
        self.pingTimer.start(self.pingInterval)

        self.hostList = hostList

    def _ping(self, address):
        status, result = sp.getstatusoutput("ping -c1 -w5 " + str(address))
        if status == 0:
            return True
        else:
            return False

    @modules.on_event(PingTimeEvent)
    def send_random_samples(self, event):
        # reschedule function
        self.pingTimer.start(self.pingInterval)

        # ping devices
        for host in self.hostList:
            isUp = self._ping(host)
            if isUp:
                self.log.debug("Host {} is UP".format(host))
            else:
                self.log.debug("Host {} is DOWN".format(host))

            event = HostStateEvent(host, isUp)
            self.send_event(event)
Beispiel #2
0
class MyIperfController(modules.ControlApplication):
    def __init__(self):
        super(MyIperfController, self).__init__()
        self.log = logging.getLogger('MyIperfControllerWithAppIntents')

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start control app")

        node = self.localNode

        self.log.debug("My local node: {}, Local: {}".format(
            node.hostname, node.local))

        for dev in node.get_devices():
            self.log.debug("Dev: %s" % dev.name)

        for m in node.get_modules():
            self.log.debug("Module: %s" % m.name)

        for apps in node.get_control_applications():
            self.log.debug("App: %s" % apps.name)

        # start iperf server
        iperfServerEvent = IperfServerRequestEvent()
        #iperfServerEvent.resultReportInterval = 1
        iperfServerEvent.stopAfterFirstReport = True
        iperfServerEvent.app_intent = LongBulkTransferIntent()

        self.log.info("Start iperf server ...")
        self.send_event(iperfServerEvent)

        self.timeInterval = 1
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def start_iperf_client(self, event):
        self.log.info("Start iperf client ...")

        self.log.info("application intent: ")

        # start iperf client
        iperfClientEvent = IperfClientRequestEvent()
        iperfClientEvent.resultReportInterval = 1
        iperfClientEvent.stopAfterFirstReport = False
        iperfClientEvent.transmissionTime = 5
        iperfClientEvent.destination = '127.0.0.1'
        iperfClientEvent.app_intent = LongBulkTransferIntent()

        self.log.info("Start iperf client ...")
        self.send_event(iperfClientEvent)
Beispiel #3
0
class SimpleBenchmark(modules.ControlApplication):
    def __init__(self, title=''):
        super(SimpleBenchmark, self).__init__()
        self.log = logging.getLogger('SimpleBenchmark')
        self.title = title
        self.running = False

        self.timeInterval = 4
        self.blocking_timer = TimerEventSender(
            self, PeriodicBlockingEvaluationTimeEvent)
        self.non_blocking_timer = TimerEventSender(
            self, PeriodicNonBlockingEvaluationTimeEvent)

        self.non_blocking_timer.start(self.timeInterval)

        self.packetLossEventsEnabled = False

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start control app")
        print('"Experiment";"Call type";"Nr calls";"Total duration";"Average per call"')
        self.csv_template = '"{title}";{call};{nr};{total};{per_call}'
        self.running = True

    @modules.on_exit()
    def my_stop_function(self):
        self.log.info("stop control app")
        self.running = False

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}"
                      .format(node.uuid, node.local))
        self._add_node(node)

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if self._remove_node(node):
            self.log.info("Node: {}, Local: {} removed reason: {}"
                          .format(node.uuid, node.local, reason))

    def non_blocking_cb(self, data):

        self.current_num += 1

        if self.current_num >= self.repeatNum:
            end = datetime.datetime.now()
            duration = end - self.start
            perCall = duration / self.repeatNum
            self.log.info(
                "{} RPC calls were executed in: {}s".format(
                    self.repeatNum, duration))
            self.log.info(
                "--- mean duration of single call: {}s".format(perCall))
            print(self.csv_template.format(
                title=self.title,
                call='non blocking',
                nr=self.repeatNum,
                total=duration,
                per_call=perCall))

            self.blocking_timer.start(self.timeInterval)

    @modules.on_event(PeriodicNonBlockingEvaluationTimeEvent)
    def periodic_non_blocking_evaluation(self, event):
        self.log.info("Periodic Non Blocking Evaluation")
        self.log.info(
            "My nodes: %s",
            ', '.join([node.hostname for node in self.get_nodes()]))

        if len(self.get_nodes()) == 0:
            self.non_blocking_timer.start(self.timeInterval)
            return

        node = self.get_node(0)
        device = node.get_device(0)

        self.current_num = 0
        self.repeatNum = 5000
        self.start = datetime.datetime.now()
        self.log.info(
            "Start performace test, execute {} non blocking RPC calls".format(
                self.repeatNum))

        for i in range(self.repeatNum):
            device.callback(self.non_blocking_cb).get_channel("wlan0")
            time.sleep(0.0001)

    @modules.on_event(PeriodicBlockingEvaluationTimeEvent)
    def periodic_blocking_evaluation(self, event):
        self.log.info("Periodic Blocking Evaluation")
        self.log.info(
            "My nodes: %s",
            ', '.join([node.hostname for node in self.get_nodes()]))

        if len(self.get_nodes()) == 0:
            self.blocking_timer.start(self.timeInterval)
            return

        node = self.get_node(0)
        device = node.get_device(0)

        # test blocking call in loop
        self.current_num = 0
        self.repeatNum = 5000
        self.start = datetime.datetime.now()
        self.log.info(
            "Start performace test, execute {} blocking RPC calls".format(
                self.repeatNum))

        for i in range(self.repeatNum):
            device.get_channel("wlan0")

        end = datetime.datetime.now()
        duration = end - self.start
        perCall = duration / self.repeatNum
        self.log.info(
            "{} blocking RPC calls were executed in: {}s".format(
                self.repeatNum, duration))
        self.log.info(
            "--- mean duration of single blocking call: {}s".format(
                perCall))
        print(self.csv_template.format(
            title=self.title,
            call='blocking',
            nr=self.repeatNum,
            total=duration,
            per_call=perCall))

        self.non_blocking_timer.start(self.timeInterval)
Beispiel #4
0
class ChannelSounderWiFiController(modules.ControlApplication):
    def __init__(self, num_nodes):
        super(ChannelSounderWiFiController, self).__init__()
        self.log = logging.getLogger('ChannelSounderWiFiController')
        self.log.info("ChannelSounderWiFiController")
        self.nodes = {}  # APs UUID -> node
        self.num_nodes = num_nodes

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start control app")

        self.channel_lst = (1, 3, 6, 9, 11)
        self.next_channel_idx = 1
        self.ifaceName = 'mon0'
        self.start = None
        #self.hopping_interval = 3
        self.margot_uuid = None

        # CSI stuff
        self.results = []

        self.timeInterval = 1
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

    def schedule_ch_switch(self):
        try:
            # schedule first channel switch in now + 3 seconds
            #if self.start == None:
            #    self.start = datetime.datetime.now() + datetime.timedelta(seconds=3)
            #else:
            #    self.start = self.start + datetime.timedelta(seconds=self.hopping_interval)

            # new channel
            self.next_channel_idx = (self.next_channel_idx + 1) % len(
                self.channel_lst)
            nxt_channel = self.channel_lst[self.next_channel_idx]

            self.log.info('schedule_ch_switch at %s to %d' %
                          (str(self.start), nxt_channel))

            for node in self.nodes.values():
                device = node.get_device(0)
                #device.exec_time(self.start).callback(self.channel_set_cb).set_channel(nxt_channel, self.ifaceName)
                if node.uuid == self.margot_uuid:
                    device.callback(self.channel_set_cb).set_channel(
                        nxt_channel, self.ifaceName)
                else:
                    device.callback(self.channel_set_cb).set_channel(
                        nxt_channel, 'wlan0')

        except Exception as e:
            self.log.error("{} !!!Exception!!!: {}".format(
                datetime.datetime.now(), e))

    def channel_set_cb(self, data):
        """
        Callback function called when channel switching is done
        """
        node = data.node
        device = node.get_device(0)
        samples = 1
        csi = device.get_csi(samples, False)

        tuple = (self.channel_lst[self.next_channel_idx], node.uuid, csi)

        self.results.append(tuple)

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}".format(
            node.uuid, node.local))
        self.nodes[node.uuid] = node

        devs = node.get_devices()
        for dev in devs:
            self.log.info("Dev: %s" % str(dev.name))
            ifaces = dev.get_interfaces()
            self.log.info('Ifaces %s' % ifaces)
            if 'mon0' in ifaces:
                self.margot_uuid = node.uuid

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if node in self.nodes:
            del self.nodes[node.uuid]
            self.log.info("Node: {}, Local: {} removed reason: {}".format(
                node.uuid, node.local, reason))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        print("all node are available ...")
        self.timer.start(self.timeInterval)

        if len(self.nodes) < self.num_nodes:
            # wait again
            pass
        else:
            self.schedule_ch_switch()
class LocalRadioSlicer(modules.ControlApplication):
    def __init__(self):
        super(LocalRadioSlicer, self).__init__()
        self.log = logging.getLogger('LocalRadioSlicer')
        self.update_interval = 10  # 1 sec

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start wifi radio slicer")

        # store object referenes
        node = self.localNode
        self.log.info(node)
        self.device = node.get_device(0)
        self.log.info(self.device)
        self.myHMACID = 'RadioSlicerID'
        self.iface = 'ap5'
        self.total_slots = 20
        self.phy_to_data_factor = 0.6
        # slots are in microseonds
        self.slot_duration = 10000  # 10 ms
        self.stepperiod = 3

        sta1 = "00:15:6d:86:0f:84"  #tv set, IP: 192.168.6.10
        sta2 = '00:16:ea:5f:2a:03'  #internet radio, IP: 192.168.6.20
        sta3 = "ec:1f:72:82:09:56"  #Mobile Phone youtube, IP 192.168.6.30
        sta4 = "00:15:6d:84:3c:12"  #Guest Smartphone 1, IP: 192.168.7.10
        sta5 = "00:15:6d:84:3c:13"  #Guest Smartphone 2, IP: 192.168.7.20
        self.min_rates = {sta1: 15.0, sta2: 1.0}
        self.min_rate_home_devices = 1.0
        self.phy_rates = {}
        self.min_slots = {}
        self.stop = False
        self.runs = 0

        # create new MAC for local node
        self.mac = HMACConfigParam(no_slots_in_superframe=self.total_slots,
                                   slot_duration_ns=self.slot_duration)

        # assign allow all to each slot
        for slot_nr in range(self.total_slots):
            acGuard = HMACAccessPolicyParam()
            acGuard.allowAll()  # allow all
            self.mac.addAccessPolicy(slot_nr, acGuard)
        self.mac.printConfiguration()
        # install configuration in MAC
        #self.device.install_mac_processor(self.iface, self.mac)
        self.device.activate_radio_program(self.myHMACID, self.mac, self.iface)
        print(
            "*************************************************************\n")
        print("EQUAL SHARE FOR ALL\n")
        print(
            "*************************************************************\n")
        staslotshareevent = StaSlotShareEvent("TV", 33)
        self.send_event(staslotshareevent)
        staslotshareevent = StaSlotShareEvent("Guest1", 33)
        self.send_event(staslotshareevent)
        staslotshareevent = StaSlotShareEvent("Guest2", 33)
        self.send_event(staslotshareevent)
        #self.log.debug('... Waiting 100s')
        #time.sleep(100)
        #print("*************************************************************\n")
        #print("SLICER ACTIVATED!!!!\n")
        #print("*************************************************************\n")
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.update_interval)
        #self.log.debug('... Waiting 100s')
        #time.sleep(100)
        #self.log.debug('... done')
        #self.stop = True
        #self.log.debug('... Enabling free for all')
        # assign allow all to each slot
        #for slot_nr in range(self.total_slots):
        #        acGuard = HMACAccessPolicyParam()
        #        acGuard.allowAll()  # allow all
        #        self.mac.addAccessPolicy(slot_nr, acGuard)
        #self.mac.printConfiguration()
        #self.log.debug('... Calling Stop Function')
        #self.my_stop_function()
        self.log.debug('... done')

    @modules.on_exit()
    def my_stop_function(self):
        self.log.info("stop wifi radio slicer")

        # install configuration in MAC
        #self.device.uninstall_mac_processor(self.iface, self.mac)
        self.device.deactivate_radio_program(self.myHMACID)

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_slice_adapdation(self, event):
        print("Number of Runs: " + str(self.runs))
        if self.runs < self.stepperiod:
            staslotshareevent = StaSlotShareEvent("TV", 33)
            self.send_event(staslotshareevent)
            staslotshareevent = StaSlotShareEvent("Guest1", 33)
            self.send_event(staslotshareevent)
            staslotshareevent = StaSlotShareEvent("Guest2", 33)
            self.send_event(staslotshareevent)
            self.runs = self.runs + 1
            self.timer.start(self.update_interval)
        elif (self.runs >= self.stepperiod) and (self.runs <
                                                 2 * self.stepperiod):
            self.runs = self.runs + 1
            print("Periodic slice adaptations ...")
            if self.runs == 5:
                print(
                    "*************************************************************\n"
                )
                print(
                    "SLICER ACTIVATED - Guaranteed Bandwidth for HOME STA1: 15Mbps\n"
                )
                print(
                    "*************************************************************\n"
                )
            primary_slots_exclusive = 0  #Slots used by primary devices getting exclusive slots
            needed_slots_standard_primary = 0  # Slots needed by standard primary users
            if True:
                if True:
                    # step 1: get information about client STAs being served
                    tx_bitrate_link = self.device.get_tx_bitrate_of_connected_devices(
                        self.iface)
                    for sta_mac_addr, sta_speed in tx_bitrate_link.items():
                        #sta_tx_bitrate_val = float(sta_speed[0]) # e.g. 12
                        sta_tx_bitrate_val = 54.0  # e.g. 12
                        sta_tx_bitrate_unit = sta_speed[1]  # e.g. Mbit/s

                        print(
                            str(sta_mac_addr) + ": STA_TX_BITRATE PHY: " +
                            str(sta_tx_bitrate_val) + " " +
                            str(sta_tx_bitrate_unit))
                        sta_tx_bitrate_val = sta_tx_bitrate_val * self.phy_to_data_factor
                        print(
                            str(sta_mac_addr) + ": STA_TX_BITRATE DATA: " +
                            str(sta_tx_bitrate_val) + " " +
                            str(sta_tx_bitrate_unit))

                        if sta_tx_bitrate_unit == "MBit/s":
                            self.phy_rates[
                                sta_mac_addr] = sta_tx_bitrate_val  #Store all PHY Rates of Primary STAs
                        else:
                            print("CONVERT THE BITRATE!!!!!")
                            # TODO write converter

                    # step 2: process link info & decide on new slice sizes

                    for sta_mac_addr in self.phy_rates:
                        slot_bitrate = float(
                            self.phy_rates[sta_mac_addr]) / float(
                                self.total_slots)
                        print("Slot Bitrate for STA: " + str(slot_bitrate))
                        if sta_mac_addr in self.min_rates.keys(
                        ):  #If this primary device should get an exclusive slice
                            print("STA need to get explusive slice")
                            print("Policy Min Bitrate: " +
                                  str(self.min_rates[sta_mac_addr]))
                            number_of_slots = round(
                                self.min_rates[sta_mac_addr] / slot_bitrate +
                                0.5)
                            self.min_slots[
                                sta_mac_addr] = number_of_slots + 1  # plus 1 because of guard slots
                            primary_slots_exclusive = primary_slots_exclusive + number_of_slots
                            print("Min Slots needed for exclusive primary: " +
                                  str(self.min_slots[sta_mac_addr]))
                        else:  #Primary STA will get standard slot with other non exclusive primaries but trying to get min Rate per Primary
                            print("STA gets slice with other primaries")
                            print(
                                "Standard Min Bitrate for non-exclusive primaries: "
                                + str(self.min_rate_home_devices))
                            number_of_slots = round(
                                self.min_rate_home_devices / slot_bitrate +
                                0.5) + 1  # 1 for backup slots
                            print(
                                "Min Slots needed for non-exclusive primary: "
                                + str(number_of_slots))
                            needed_slots_standard_primary = needed_slots_standard_primary + number_of_slots
                    # step 3: update hMAC
                    print("Exclusive primaries total slots: " +
                          str(primary_slots_exclusive))
                    print("Non exclusive primaries total slots: " +
                          str(needed_slots_standard_primary))

                    # assign access policies to each slot in superframe
                    #Count needed slots for primary user
                    total_used_slots_exclusive_primary = 0.0
                    total_used_slots_non_exclusive_primary = 0.0
                    total_used_slots = 0.0
                    for sta_mac_addr in self.min_slots:
                        total_used_slots = total_used_slots + self.min_slots[
                            sta_mac_addr]
                    if total_used_slots > self.total_slots:
                        print(
                            "Warning!: More slots for exclusive primaries needed as available, target bitrate for all primary users not achievable! Needed: "
                            + str(total_used_slots) + " Available: " +
                            str(self.total_slots))
                        total_used_slots = self.total_slots
                    else:
                        print("Total used slots for exclusive primaries: " +
                              str(total_used_slots))
                    total_used_slots_exclusive_primary = total_used_slots
                    total_used_slots = total_used_slots + needed_slots_standard_primary
                    if total_used_slots > self.total_slots:
                        print(
                            "Warning!: More slots for primaries needed as available, target bitrate for all primary users not achievable! Needed: "
                            + str(total_used_slots) + " Available: " +
                            str(self.total_slots))
                        total_used_slots = self.total_slots
                    else:
                        print("Total used slots for primaries: " +
                              str(total_used_slots))
                    total_used_slots_non_exclusive_primary = total_used_slots - total_used_slots_exclusive_primary
                    print("Total used slots for non-exclusive primaries: " +
                          str(total_used_slots_non_exclusive_primary))
                    check_exclusives = [0] * len(self.min_slots)
                    for slot_nr in range(0, int(self.total_slots)):
                        print("Processing slot nr: " + str(slot_nr))
                        #ac_slot = self.mac.getAccessPolicy(slot_nr)
                        ac_slot = HMACAccessPolicyParam()
                        if slot_nr == 0:
                            print("Guard between secondaries and primaries")
                            ac_slot.disableAll()
                        elif slot_nr < total_used_slots_exclusive_primary:
                            sta_number = 0
                            for sta_mac_addr in self.min_slots:
                                if check_exclusives[
                                        sta_number] < self.min_slots[
                                            sta_mac_addr]:
                                    ac_slot.addDestMacAndTosValues(
                                        sta_mac_addr, 0)
                                    check_exclusives[
                                        sta_number] = check_exclusives[
                                            sta_number] + 1
                                    if check_exclusives[
                                            sta_number] == self.min_slots[
                                                sta_mac_addr]:
                                        ac_slot.disableAll()
                                        print("Guard between primaries")
                                    else:
                                        print("Adding mac " +
                                              str(sta_mac_addr))
                                    break
                                sta_number = sta_number + 1
                                #ac_slot.addDestMacAndTosValues(sta_mac_addr, 0)
                        #elif slot_nr == total_used_slots_exclusive_primary:
                        #ac_slot.disableAll()
                        elif slot_nr > total_used_slots_exclusive_primary and slot_nr < total_used_slots:
                            for sta_mac_addr in self.phy_rates:
                                if sta_mac_addr not in self.min_slots.keys():
                                    print("Adding mac " + str(sta_mac_addr))
                                    ac_slot.addDestMacAndTosValues(
                                        sta_mac_addr, 0)
                        elif slot_nr == total_used_slots:
                            ac_slot.disableAll()
                            print("Guard after primaries")
                        else:
                            #ac_slot.disableAll()
                            ac_slot.allowAll()
                            print("Secondaries")
                        self.mac.addAccessPolicy(slot_nr, ac_slot)
                    #for slot_nr in range(int(total_used_slots), int(self.total_slots)):
                    # TODO Replace this with STAs of Guest Network
                    #    print("Processing secondary slot nr: "+str(slot_nr))
                    #    ac_slot = self.mac.getAccessPolicy(slot_nr)
                    #    ac_slot = ac_slot.disableAll()
                    #self.mac.addAccessPolicy(slot_nr, ac_slot)
                    # TODO: sven do something ...
                    # node on which scheme should be applied, e.g. nuc15 interface sta1
                    #    staDstHWAddr = "04:f0:21:17:36:68"
                    #    ac_slot.addDestMacAndTosValues(staDstHWAddr, 0)

                    # update configuration in hMAC
                    self.mac.printConfiguration()
                    #self.device.update_mac_processor(self.iface, self.mac)
                    self.device.update_radio_program(self.myHMACID, self.mac,
                                                     self.iface)
                    staslotshareevent = StaSlotShareEvent(
                        "TV",
                        int((100 / self.total_slots) *
                            (total_used_slots_exclusive_primary +
                             ((self.total_slots -
                               total_used_slots_exclusive_primary) / 3))))
                    self.send_event(staslotshareevent)
                    staslotshareevent = StaSlotShareEvent(
                        "Guest1",
                        int((100 / self.total_slots) *
                            (((self.total_slots -
                               total_used_slots_exclusive_primary) / 3))))
                    self.send_event(staslotshareevent)
                    staslotshareevent = StaSlotShareEvent(
                        "Guest2",
                        int((100 / self.total_slots) *
                            (((self.total_slots -
                               total_used_slots_exclusive_primary) / 3))))
                    self.send_event(staslotshareevent)

            #except Exception as e:
            #    self.log.error("{} Failed updating mac processor, err_msg: {}"
            #                   .format(datetime.datetime.now(), e))
            #    raise e
            self.timer.start(self.update_interval)
        else:
            print("Demo Finished, repeating...")
            #    self.log.debug('... Enabling free for all')
            print(
                "*************************************************************\n"
            )
            print("EQUAL SHARE FOR ALL\n")
            print(
                "*************************************************************\n"
            )
            #assign allow all to each slot
            # create new MAC for local node
            self.mac = HMACConfigParam(no_slots_in_superframe=self.total_slots,
                                       slot_duration_ns=self.slot_duration)
            # assign allow all to each slot
            for slot_nr in range(self.total_slots):
                acGuard = HMACAccessPolicyParam()
                if slot_nr == 0:
                    acGuard.disableAll()
                else:
                    acGuard.allowAll()  # allow all
                self.mac.addAccessPolicy(slot_nr, acGuard)
            self.mac.printConfiguration()
            #self.device.deactivate_radio_program(self.myHMACID)
            #self.device.activate_radio_program(self.myHMACID, self.mac, self.iface)
            self.device.update_radio_program(self.myHMACID, self.mac,
                                             self.iface)
            #self.log.debug('... Calling Stop Function')
            #self.my_stop_function()
            staslotshareevent = StaSlotShareEvent("TV", 33)
            self.send_event(staslotshareevent)
            staslotshareevent = StaSlotShareEvent("Guest1", 33)
            self.send_event(staslotshareevent)
            staslotshareevent = StaSlotShareEvent("Guest2", 33)
            self.send_event(staslotshareevent)
            self.log.debug('... done')
            self.runs = 0
            self.timer.start(self.update_interval)
Beispiel #6
0
class LocalRadioSlicer(modules.ControlApplication):
    def __init__(self):
        super(LocalRadioSlicer, self).__init__()
        self.log = logging.getLogger('LocalRadioSlicer')
        self.update_interval = 1 # 1 sec

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start wifi radio slicer")

        # store object referenes
        node = self.localNode
        self.log.info(node)
        self.device = node.get_device(0)
        self.log.info(self.device)
        self.iface = 'ap5'
        self.total_slots = 20
        # slots are in microseonds
        slot_duration = 20000  # 20 ms
        
        sta1 = "00:15:6d:84:fb:7a" #fernseher
        self.min_rates = {sta1 : 15.0}
        self.phy_rates = {}
        self.min_slots = {}


        # create new MAC for local node
        self.mac = HMACConfigParam(
            no_slots_in_superframe=self.total_slots,
            slot_duration_ns=slot_duration)

        # assign allow all to each slot
        for slot_nr in range(self.total_slots):
                acGuard = HMACAccessPolicyParam()
                acGuard.allowAll()  # allow all
                self.mac.addAccessPolicy(slot_nr, acGuard)
        self.mac.printConfiguration()
        # install configuration in MAC
        self.device.install_mac_processor(self.iface, self.mac)

        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.update_interval)

        self.log.info('... done')


    @modules.on_exit()
    def my_stop_function(self):
        self.log.info("stop wifi radio slicer")

        # install configuration in MAC
        self.device.uninstall_mac_processor(self.iface, self.mac)


    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_slice_adapdation(self, event):
        print("Periodic slice adaptations ...")
        if True:
            if True:
                # step 1: get information about client STAs being served
                tx_bitrate_link = self.device.get_tx_bitrate_of_connected_devices(self.iface)
                for sta_mac_addr, sta_speed in tx_bitrate_link.items():
                    sta_tx_bitrate_val = sta_speed[0] # e.g. 12
                    sta_tx_bitrate_unit = sta_speed[1] # e.g. Mbit/s
                    print(str(sta_mac_addr)+": STA_TX_BITRATE: "+str(sta_tx_bitrate_val)+" "+str(sta_tx_bitrate_unit))
                    if sta_tx_bitrate_unit == "MBit/s":
                        self.phy_rates[sta_mac_addr] = sta_tx_bitrate_val
                    else:
                        print("CONVERT THE BITRATE!!!!!")
                        # TODO write converter

                # step 2: process link info & decide on new slice sizes
                
                for sta_mac_addr in self.phy_rates:
                    if sta_mac_addr in self.min_rates.keys():
                        print("STA is in min_rates")
                        slot_bitrate = float(self.phy_rates[sta_mac_addr]) / float(self.total_slots)
                        print("Slot Bitrate for STA: "+str(slot_bitrate))
                        print("Policy Min Bitrate: "+str(self.min_rates[sta_mac_addr]))
                        number_of_slots = round(self.min_rates[sta_mac_addr] / slot_bitrate + 0.5) 
                        self.min_slots[sta_mac_addr]= number_of_slots
                        print("Min Slots needed: "+str(self.min_slots[sta_mac_addr]))                     

                # step 3: update hMAC

                # assign access policies to each slot in superframe
                #Count needed slots for primary user
                total_used_slots = 0.0
                for sta_mac_addr in self.min_slots:
                    total_used_slots = total_used_slots + self.min_slots[sta_mac_addr]                    
                if total_used_slots > self.total_slots:
                    print("Warning!: More slots needed as available, target bitrate for all primary users not achievable! Needed: "+str(total_used_slots)+" Available: "+str(self.total_slots))
                    total_used_slots = self.total_slots            
                else:
                    print("Total used slots for primary: "+str(total_used_slots)) 
                self.mac.printConfiguration()
                for slot_nr in range(0,int(total_used_slots)):
                    print("Processing primary slot nr: "+str(slot_nr))  
                    #ac_slot = self.mac.getAccessPolicy(slot_nr)
                    ac_slot = HMACAccessPolicyParam()
                    for sta_mac_addr in self.min_slots:
                        print("Adding mac "+str(sta_mac_addr))
                        ac_slot.addDestMacAndTosValues(sta_mac_addr, 0)
                    self.mac.addAccessPolicy(slot_nr, ac_slot)
                #for slot_nr in range(int(total_used_slots), int(self.total_slots)):
                    # TODO Replace this with STAs of Guest Network
                #    print("Processing secondary slot nr: "+str(slot_nr))
                #    ac_slot = self.mac.getAccessPolicy(slot_nr)
                #    ac_slot = ac_slot.disableAll()
                    #self.mac.addAccessPolicy(slot_nr, ac_slot)
                    # TODO: sven do something ...
                    # node on which scheme should be applied, e.g. nuc15 interface sta1
                #    staDstHWAddr = "04:f0:21:17:36:68"
                #    ac_slot.addDestMacAndTosValues(staDstHWAddr, 0)

                # update configuration in hMAC
                self.mac.printConfiguration()
                self.device.update_mac_processor(self.iface, self.mac)

        #except Exception as e:
        #    self.log.error("{} Failed updating mac processor, err_msg: {}"
        #                   .format(datetime.datetime.now(), e))
        #    raise e

        self.timer.start(self.update_interval)
Beispiel #7
0
class SlaveController(modules.ControlApplication):
    def __init__(self):
        super(SlaveController, self).__init__()
        self.log = logging.getLogger('SlaveController')
        self.running = False

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

        self.dut_iface = "eno1"
        self.bn_iface = "wlp2s0"

    def _run_command(self, command):
        sp = subprocess.Popen(command,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              shell=True)
        out, err = sp.communicate()

        if out:
            self.log.debug("standard output of subprocess:")
            self.log.debug(out)
        if err:
            self.log.debug("standard error of subprocess:")
            self.log.debug(err)

        return [sp.returncode, out.decode("utf-8"), err.decode("utf-8")]

    def _setup_l2_tunneling(self):
        self.log.info(
            "Create VXLAN (virtual) interface and add it to the Linux bridge")
        self._run_command(
            "ip link add vxlan10 type vxlan id 10 group 224.10.10.10 ttl 10 dev "
            + self.bn_iface)
        self._run_command("ip link set vxlan10 up")
        self._run_command("brctl addif br0 vxlan10")

        self.log.info("Set bigger MTU to fit packets from DUT nodes")
        self._run_command("ifconfig wlp2s0 mtu 1550")
        self._run_command("ifconfig vxlan10 mtu 1500")

    def _teardown_l2_tunneling(self):
        self.log.info("Destroy VXLAN (virtual) interface")
        self._run_command("brctl delif br0 vxlan10")
        self._run_command("ip link set vxlan10 down")
        self._run_command("ip link delete vxlan10")

        self.log.info("Set default MTU on wireless iface")
        self._run_command("ifconfig wlp2s0 mtu 1500")

    @modules.on_start()
    def my_start_function(self):
        print("Start Control Application")
        self.running = True
        self._setup_l2_tunneling()

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False
        self._teardown_l2_tunneling()

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")
        self.timer.start(self.timeInterval)
        return
class MyController(modules.ControlApplication):
    def __init__(self):
        super(MyController, self).__init__()
        self.log = logging.getLogger('MyController')
        self.running = False
        self.nodes = []

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

        self.myFilterRunning = False
        self.packetLossEventsEnabled = False

    @modules.on_start()
    def my_start_function(self):
        print("start control app")
        self.running = True

        node = self.localNode
        self.log.info("My local, Local: {}".format(node.local))

        for dev in node.get_devices():
            print("Dev: ", dev.name)
            print(dev)

        for m in node.get_modules():
            print("Module: ", m.name)
            print(m)

        for app in node.get_control_applications():
            print("App: ", app.name)
            print(app)

        device = node.get_device(0)
        device.set_tx_power(15, 'ath0')
        device.set_channel(random.randint(1, 11), 'ath0')
        device.packet_loss_monitor_start()
        self.packetLossEventsEnabled = True
        device.spectral_scan_start()

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False

    @modules.on_event(PacketLossEvent)
    def serve_packet_loss_event(self, event):
        node = event.node
        device = event.device
        self.log.info("Packet loss, dev: {}".format(device))

    @modules.on_event(AveragedSpectrumScanSampleEvent)
    def serve_spectral_scan_sample(self, event):
        avgSample = event.avg
        self.log.info("Averaged Spectral Scan Sample: {}".format(avgSample))

    def default_cb(self, data):
        node = data.node
        devName = None
        if data.device:
            devName = data.device.name
        msg = data.msg
        print("Default Callback: " "Dev: {}, Data: {}".format(devName, msg))

    def get_power_cb(self, data):
        node = data.node
        dev = data.device
        msg = data.msg
        print("Power in " "Dev: {}, was set to: {}".format(dev.name, msg))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")

        node = self.localNode
        device = node.get_device(0)

        self.log.info("My local node, Local: {}".format(node.local))
        self.timer.start(self.timeInterval)

        if self.packetLossEventsEnabled:
            device.packet_loss_monitor_stop()
            self.packetLossEventsEnabled = False
        else:
            device.packet_loss_monitor_start()
            self.packetLossEventsEnabled = True

        if self.myFilterRunning:
            self.send_event(StopMyFilterEvent())
            self.myFilterRunning = False
        else:
            self.send_event(StartMyFilterEvent())
            self.myFilterRunning = True

        # execute non-blocking function immediately
        device.blocking(False).set_tx_power(random.randint(1, 20), 'ath0')

        # execute non-blocking function immediately, with specific callback
        device.callback(self.get_power_cb).get_tx_power('ath0')

        # schedule non-blocking function delay
        device.delay(3).callback(self.default_cb).get_tx_power("wlan0")

        # schedule non-blocking function exec time
        exec_time = datetime.datetime.now() + datetime.timedelta(seconds=3)
        newChannel = random.randint(1, 11)
        device.exec_time(exec_time).set_channel(newChannel, 'ath0')

        # execute blocking function immediately
        result = device.get_channel('ath0')
        print("{} Channel is: {}".format(datetime.datetime.now(), result))

        # exception handling, clean_per_flow_tx_power_table implementation
        # raises exception
        try:
            device.clean_per_flow_tx_power_table("wlan0")
        except Exception as e:
            print("{} !!!Exception!!!: {}".format(datetime.datetime.now(), e))
Beispiel #9
0
class MyController(modules.ControlApplication):
    def __init__(self, mode):
        super(MyController, self).__init__()
        self.log = logging.getLogger('MyController')
        self.mode = mode
        self.running = False

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

    @modules.on_start()
    def my_start_function(self):
        print("start control app")
        self.running = True

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}".format(
            node.uuid, node.local))
        self._add_node(node)

        for dev in node.get_devices():
            print("Dev: ", dev.name)
            print(dev)

        for m in node.get_modules():
            print("Module: ", m.name)
            print(m)

        for app in node.get_control_applications():
            print("App: ", app.name)
            print(app)

        device = node.get_device(0)
        device.set_tx_power(15, "wlan0")
        device.set_channel(random.randint(1, 11), "wlan0")
        device.packet_loss_monitor_start()
        device.spectral_scan_start()

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if self._remove_node(node):
            self.log.info("Node: {}, Local: {} removed reason: {}".format(
                node.uuid, node.local, reason))

    @modules.on_event(PacketLossEvent)
    def serve_packet_loss_event(self, event):
        node = event.node
        device = event.device
        self.log.info("Packet loss in node {}, dev: {}".format(
            node.hostname, device.name))

    @modules.on_event(AveragedSpectrumScanSampleEvent)
    def serve_spectral_scan_sample(self, event):
        avgSample = event.avg
        self.log.info("Averaged Spectral Scan Sample: {}".format(avgSample))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")
        print("My nodes: ", [node.hostname for node in self.get_nodes()])
        self.timer.start(self.timeInterval)

        if len(self.get_nodes()) == 0:
            return
Beispiel #10
0
class MyController(modules.ControlApplication):
    def __init__(self):
        super(MyController, self).__init__()
        self.log = logging.getLogger('MyController')
        self.running = False

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

    @modules.on_start()
    def my_start_function(self):
        print("start control app")
        self.running = True

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}".format(
            node.uuid, node.local))
        self._add_node(node)

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if self._remove_node(node):
            self.log.info("Node: {}, Local: {} removed reason: {}".format(
                node.uuid, node.local, reason))

    @modules.on_event(PacketLossEvent)
    def serve_packet_loss_event(self, event):
        node = event.node
        device = event.device
        self.log.info("Packet loss in node {}, dev: {}".format(
            node.hostname, device.name))

    @modules.on_event(AveragedSpectrumScanSampleEvent)
    def serve_spectral_scan_sample(self, event):
        avgSample = event.avg
        self.log.info("Averaged Spectral Scan Sample: {}".format(avgSample))

    def default_cb(self, data):
        node = data.node
        devName = None
        if data.device:
            devName = data.device.name
        msg = data.msg
        print("Default Callback: "
              "Node: {}, Dev: {}, Data: {}".format(node.hostname, devName,
                                                   msg))

    def get_power_cb(self, data):
        node = data.node
        dev = data.device
        msg = data.msg
        print("Power in "
              "Node: {}, Dev: {}, was set to: {}".format(
                  node.hostname, dev.name, msg))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")
        print("My nodes: ", [node.hostname for node in self.get_nodes()])
        self.timer.start(self.timeInterval)

        if len(self.get_nodes()) == 0:
            return
        return
Beispiel #11
0
class MyController(modules.ControlApplication):
    def __init__(self):
        super(MyController, self).__init__()
        self.log = logging.getLogger('MyController')
        self.running = False

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

        self.packetLossEventsEnabled = False

    @modules.on_start()
    def my_start_function(self):
        print("start control app")
        self.running = True

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}".format(
            node.uuid, node.local))
        self._add_node(node)

        for dev in node.get_devices():
            print("Dev: ", dev.name)
            print(dev)

        for m in node.get_modules():
            print("Module: ", m.name)
            print(m)

        for app in node.get_control_applications():
            print("App: ", app.name)
            print(app)

        device = node.get_device(0)
        device.set_tx_power(15, "wlan0")
        device.set_channel(random.randint(1, 11), "wlan0")
        device.packet_loss_monitor_start()
        device.spectral_scan_start()
        # device.play_waveform()
        # TODO: is_implemented()

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if self._remove_node(node):
            self.log.info("Node: {}, Local: {} removed reason: {}".format(
                node.uuid, node.local, reason))

    @modules.on_event(PacketLossEvent)
    def serve_packet_loss_event(self, event):
        node = event.node
        device = event.device
        self.log.info("Packet loss in node {}, dev: {}".format(
            node.hostname, device.name))

    @modules.on_event(AveragedSpectrumScanSampleEvent)
    def serve_spectral_scan_sample(self, event):
        avgSample = event.avg
        self.log.info("Averaged Spectral Scan Sample: {}".format(avgSample))

    def default_cb(self, data):
        node = data.node
        devName = None
        if data.device:
            devName = data.device.name
        msg = data.msg
        print("Default Callback: "
              "Node: {}, Dev: {}, Data: {}".format(node.hostname, devName,
                                                   msg))

    def get_power_cb(self, data):
        node = data.node
        msg = data.msg
        dev = node.get_device(0)
        print("Power in "
              "Node: {}, Dev: {}, was set to: {}".format(
                  node.hostname, dev.name, msg))

        newPwr = random.randint(1, 20)
        dev.blocking(False).set_tx_power(newPwr, "wlan0")
        print("Power in "
              "Node: {}, Dev: {}, was set to: {}".format(
                  node.hostname, dev.name, newPwr))

    def scheduled_get_channel_cb(self, data):
        node = data.node
        msg = data.msg
        dev = node.get_device(0)
        print("Scheduled get_channel; Power in "
              "Node: {}, Dev: {}, was set to: {}".format(
                  node.hostname, dev.name, msg))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")
        print("My nodes: ", [node.hostname for node in self.get_nodes()])
        self.timer.start(self.timeInterval)

        if len(self.get_nodes()) == 0:
            return

        node = self.get_node(0)
        device = node.get_device(0)

        if device.is_packet_loss_monitor_running():
            device.packet_loss_monitor_stop()
            device.spectral_scan_stop()
        else:
            device.packet_loss_monitor_start()
            device.spectral_scan_start()

        avgFilterApp = None
        for app in node.get_control_applications():
            if app.name == "MyAvgFilter":
                avgFilterApp = app
                break

        if avgFilterApp.is_running():
            myValue = random.randint(1, 20)
            [nValue1, nValue2] = avgFilterApp.blocking(True).add_two(myValue)
            print("My value: {} + 2 = {}".format(myValue, nValue1))
            print("My value: {} * 2 = {}".format(myValue, nValue2))
            avgFilterApp.stop()

            newWindow = random.randint(10, 50)
            old = avgFilterApp.blocking(True).get_window_size()
            print("Old Window Size : {}".format(old))
            avgFilterApp.blocking(True).change_window_size_func(newWindow)
            nValue = avgFilterApp.blocking(True).get_window_size()
            print("New Window Size : {}".format(nValue))

        else:
            avgFilterApp.start()
            newWindow = random.randint(10, 50)
            event = ChangeWindowSizeEvent(newWindow)
            avgFilterApp.send_event(event)

        # execute non-blocking function immediately
        device.blocking(False).set_tx_power(random.randint(1, 20), "wlan0")

        # execute non-blocking function immediately, with specific callback
        device.callback(self.get_power_cb).get_tx_power("wlan0")

        # schedule non-blocking function delay
        device.delay(3).callback(self.default_cb).get_tx_power("wlan0")

        # schedule non-blocking function exec time
        exec_time = datetime.datetime.now() + datetime.timedelta(seconds=3)
        newChannel = random.randint(1, 11)
        device.exec_time(exec_time).set_channel(newChannel, "wlan0")

        # schedule execution of function multiple times
        start_date = datetime.datetime.now() + datetime.timedelta(seconds=2)
        interval = datetime.timedelta(seconds=1)
        repetitionNum = 3
        device.exec_time(start_date, interval, repetitionNum).callback(
            self.scheduled_get_channel_cb).get_channel("wlan0")

        # execute blocking function immediately
        result = device.get_channel("wlan0")
        print("{} Channel is: {}".format(datetime.datetime.now(), result))

        # exception handling, clean_per_flow_tx_power_table implementation
        # raises exception
        try:
            device.clean_per_flow_tx_power_table("wlan0")
        except Exception as e:
            print("{} !!!Exception!!!: {}".format(datetime.datetime.now(), e))
Beispiel #12
0
class Scanner(modules.ControlApplication):
    def __init__(self, mode, ap_iface, scan_iface, channels, hopping_interval,
                 reporting_interval):
        super(Scanner, self).__init__()
        self.log = logging.getLogger('Scanner')
        self.mode = mode
        self.ap_iface = ap_iface
        self.scan_iface = scan_iface
        self.channels = channels
        self.hopping_interval = hopping_interval
        self.reporting_interval = reporting_interval
        self.sta_map_file = '/tmp/sta_map.dat'
        self.next_ch_id = 0

    @modules.on_start()
    def my_start_function(self):
        self.log.debug("start scanner app")

        # start scanner
        self.exec_file = 'scanner/scanner'
        self.processArgs = self.exec_file + ' ' + self.scan_iface
        self.process = subprocess.Popen(self.processArgs.split(), shell=False)
        # wait to settle down
        time.sleep(1)

        # channel hopping every 100ms
        self.chHoppingTimeInterval = self.hopping_interval
        self.chTimer = TimerEventSender(self, PeriodicChannelSwitchTimeEvent)
        self.chTimer.start(self.chHoppingTimeInterval)

        # reporting signal quality as event
        self.reportingTimeInterval = self.reporting_interval
        self.reportingTimer = TimerEventSender(self,
                                               PeriodicCQIReportingTimeEvent)
        self.reportingTimer.start(self.reportingTimeInterval)

    @modules.on_exit()
    def my_stop_function(self):
        self.log.debug("stop scanner app")
        # stop scanner
        self.process.kill()

    @modules.on_event(PeriodicChannelSwitchTimeEvent)
    def periodic_channel_switch(self, event):

        self.log.debug("Periodic channel hopping")
        self.log.debug("My node: %s" % self.localNode.hostname)
        self.chTimer.start(self.chHoppingTimeInterval)

        device = self.localNode.get_device(0)

        try:
            # switch to next channel
            device.radio.set_channel(self.channels[self.next_ch_id])

            self.next_ch_id = (self.next_ch_id + 1) % len(self.channels)
        except Exception as e:
            self.log.error("{} !!!Exception!!!: {}".format(
                datetime.datetime.now(), e))

    @modules.on_event(PeriodicCQIReportingTimeEvent)
    def periodic_reporting(self, event):

        self.log.debug("Periodic reporting")
        self.log.debug("My node: %s" % self.localNode.hostname)
        self.chTimer.start(self.reportingTimeInterval)

        device = self.localNode.get_device(0)

        try:
            # read and create event
            # CQI towards co-located client not being served
            candidate_sigpower = self.read_passive_scan_results()
            # CQI towards served client
            curr_sigpower = self.get_avg_sigpower()

            event = CQIReportingEvent(candidate_sigpower, curr_sigpower)

            self.send_event(event)
        except Exception as e:
            self.log.error("{} !!!Exception!!!: {}".format(
                datetime.datetime.now(), e))

    def read_passive_scan_results(self):
        """
        Get the signal quality towards co-located clients being served by neighboring APs. STA_MAC_ADDR -> dBm
        Returns in dBm
        """
        scan_results = open(self.sta_map_file, 'r')
        rv = {}
        for line in scan_results:
            row_arr = line.split(",")
            if (len(row_arr) >= 2):
                macAddr = row_arr[0]
                sigPow = row_arr[1]
            else:
                continue
            rv[macAddr] = sigPow
        return rv

    def get_avg_sigpower(self):
        """
        Get the signal quality of currently served/associated client stations. STA_MAC_ADDR -> dBm
        Returns in dBm
        """
        rv = {}
        station_info = self.localNode.net.iface(
            self.ap_iface).get_info_of_connected_devices()
        if station_info is not None:
            for node in station_info.keys():
                agent_control_ip = node.ip
                station_info_node = station_info[node]
                for mac in station_info_node.keys():
                    rv[mac] = station_info[node][mac]['signal avg'][0]
        return rv
Beispiel #13
0
class MyController(modules.ControlApplication):
    def __init__(self):
        super(MyController, self).__init__()
        self.log = logging.getLogger('MyController')
        self.running = False

        self.timeInterval = 10
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

        self.packetLossEventsEnabled = False

    @modules.on_start()
    def my_start_function(self):
        print("start control app")
        self.running = True

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        self.running = False

    @modules.on_event(events.NewNodeEvent)
    def add_node(self, event):
        node = event.node

        self.log.info("Added new node: {}, Local: {}".format(
            node.uuid, node.local))
        self._add_node(node)

        for dev in node.get_devices():
            print("Dev: ", dev.name)
            print(dev)

        for m in node.get_modules():
            print("Module: ", m.name)
            print(m)

        for app in node.get_control_applications():
            print("App: ", app.name)
            print(app)

    @modules.on_event(events.NodeExitEvent)
    @modules.on_event(events.NodeLostEvent)
    def remove_node(self, event):
        self.log.info("Node lost".format())
        node = event.node
        reason = event.reason
        if self._remove_node(node):
            self.log.info("Node: {}, Local: {} removed reason: {}".format(
                node.uuid, node.local, reason))

    def default_cb(self, data):
        node = data.node
        devName = None
        if data.device:
            devName = data.device.name
        msg = data.msg
        print("Default Callback: "
              "Node: {}, Dev: {}, Data: {}".format(node.hostname, devName,
                                                   msg))

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        # go over collected samples, etc....
        # make some decisions, etc...
        print("Periodic Evaluation")
        print("My nodes: ", [node.hostname for node in self.get_nodes()])
        self.timer.start(self.timeInterval)

        if len(self.get_nodes()) == 0:
            return

        node = self.get_node(0)
        device = node.get_device(0)

        # node.is_access_locked()
        # device.is_access_locked()
        ## atomic lock (check if locked and if not lock)
        # device.lock_access()
        # device.unlock_access()

        transaction = transactions.Transaction()
        task1 = transactions.Task()
        task1.set_entities(device)
        task1.set_save_point_func(func=device.get_channel, args=["wlan0"])
        task1.set_function(func=device.set_channel, args=[12, "wlan0"])
        transaction.add_task(task1)

        task2 = transactions.Task()
        task2.set_entities(device)
        task2.set_save_point_value(args=[10, "wlan0"])
        task2.set_function(func=device.set_tx_power, args=[8, "wlan0"])
        transaction.add_task(task2)

        # rollback configuration change
        # if it breaks the connection with the controller and any node
        transaction.rollback_if_connection_lost(True, timeout=10)

        # commit is a blocking call that
        # runs three-phase-commit (3PC) protocol
        transaction.commit()

        transaction.is_executed()
        transaction.is_rolled_back()
        tstatus = transaction.get_status()
        print("Transaction status: ", tstatus)
Beispiel #14
0
class GuiFeeder(modules.ControlApplication):
    def __init__(self, staList=[]):
        super(GuiFeeder, self).__init__()
        self.log = logging.getLogger('GuiFeeder')

        self.sta_list = []
        for sta in staList:
            self.log.debug("New STA: {},{},{}".format(sta[0], sta[1], sta[2]))
            s = StaInfo(sta[0], sta[1], sta[2])
            self.sta_list.append(s)

    @modules.on_start()
    def my_start(self):
        self.timeInterval = 10
        self.timer = TimerEventSender(self, SampleSendTimeEvent)
        self.timer.start(self.timeInterval)

    @modules.on_event(StaThroughputConfigEvent)
    def serve_throughput_config_event(self, event):
        sta = event.sta
        throughput = event.throughput
        self.log.info("Set Thrughput for STA: {}: to: {}".format(
            sta, throughput))

    @modules.on_event(HostStateEvent)
    def change_sta_state(self, event):
        self.log.info("Host: {} state info".format(event.ip, ))

        for s in self.sta_list:
            if s.ip == event.ip:
                if s.state is None:
                    s.state = event.state
                    return
                elif ((s.state and not event.state)
                      or (not s.state and event.state)):
                    self.log.info("STA {}:{} changed state to {}".format(
                        s.name, s.ip, event.state))
                    s.state = event.state

                    # sent event to GUI
                    ev = StaStateEvent(s.name, s.state)
                    self.send_event(ev)

                    # if new state if UP start iperf
                    if s.state:
                        if s.iperfProcess is None:
                            s.iperfProcess = IperfClientProcess(
                                self, s.name, s.ip)
                        s.iperfProcess.start()
                    else:
                        if s.iperfProcess:
                            s.iperfProcess.stop()

    @modules.on_event(SampleSendTimeEvent)
    def send_random_samples(self, ev):
        self.timer.start(1)
        share = 100

        for sta in self.sta_list:
            #if sta.state:
            self.log.info("Send new random samples for device: {}".format(
                sta.name))

            event = StaStateEvent(sta.name, True)
            self.send_event(event)

            throughput = random.uniform(5, 108)
            event = StaThroughputEvent(sta.name, throughput)
            self.send_event(event)

            phyRate = random.uniform(5, 54)
            event = StaPhyRateEvent(sta.name, phyRate)
            self.send_event(event)

            slotShare = random.uniform(0, share)
            share = share - slotShare
            event = StaSlotShareEvent(sta.name, slotShare)
            self.send_event(event)
Beispiel #15
0
class MyGnuRadioController(modules.ControlApplication):
    def __init__(self):
        super(MyGnuRadioController, self).__init__()
        self.log = logging.getLogger('MyGnuRadioController')
        self.running = False

        # GnuRadio program to be loaded
        fid = open(os.path.join(os.path.expanduser("."), "testgrc.grc"))
        self.grc_xml = fid.read()

        self.min_freq = 5200e6
        self.max_freq = 5300e6
        self.step_freq = 10e6
        self.freq = self.min_freq

    @modules.on_start()
    def my_start_function(self):
        self.log.info("start control app")
        self.running = True

        node = self.localNode

        self.log.debug("My local node: {}, Local: {}".format(
            node.hostname, node.local))

        for dev in node.get_devices():
            self.log.debug("Dev: %s" % dev.name)

        for m in node.get_modules():
            self.log.debug("Module: %s" % m.name)

        for apps in node.get_control_applications():
            self.log.debug("App: %s" % apps.name)

        self.device = node.get_device(0)

        # activate GnuRadio RP
        self.grc_radio_program_name = 'test'
        inval = {}
        inval['ID'] = 11
        inval['grc_radio_program_code'] = self.grc_xml

        self.device.activate_radio_program(self.grc_radio_program_name,
                                           **inval)

        self.timeInterval = 1
        self.timer = TimerEventSender(self, PeriodicEvaluationTimeEvent)
        self.timer.start(self.timeInterval)

    @modules.on_exit()
    def my_stop_function(self):
        print("stop control app")
        tvals = {}
        tvals['do_pause'] = str(False)

        self.device.deactivate_radio_program(self.grc_radio_program_name,
                                             **tvals)

        self.running = False

    @modules.on_event(PeriodicEvaluationTimeEvent)
    def periodic_evaluation(self, event):
        print("Periodic channel hopping ...")

        self.freq = self.freq + self.step_freq
        if self.freq > self.max_freq:
            self.freq = self.min_freq

        inval = {}
        inval['freq'] = self.freq
        # set new freq
        self.device.set_parameters(inval)
        self.log.info("New freq is: %s" % self.freq)

        self.timer.start(self.timeInterval)