Пример #1
0
def iBot(i):
    wireless = Wireless(['wlan0'])
    link="https://rajayalla98.pythonanywhere.com/get"
    if i == 9:
        if wireless.connect(ssid='I-Bot', password='******'):
            time.sleep(100)
            print wireless.current()
            response = urllib2.urlopen('http://11.11.11.11/')
            
            html = response.read()
            humidity,temperature = html.split("....")
            print humidity,temperature
            return temperature,humidity
            
        else:
            print "Did not connect"
            return [tem,hum]
    elif i == 19:
        if wireless.connect(ssid='Dont ask me', password='******'):
            data = {'temperature':tem,'humidity':hum}
            time.sleep(10)
            print wireless.current()
            requests.get(link,params=data)
            return [tem,hum]
        else:
            print "Did not connect"
            return [tem,hum]
    else:
        print "in loop"
        return [tem,hum]
Пример #2
0
def main():
    wireless = Wireless()

    while(True):
        if wireless.current() == ssid:
            print "Already connected to {0}".format(ssid)
            break

        while wireless.current() != ssid:
            print "Connecting..."
            wireless.connect(ssid=ssid, password=password)
            if wireless.current() == ssid:
                print "Connected to: {0}".format(ssid)
                break
Пример #3
0
class Network:
    def __init__(self):
        self.network = Wireless()
        self.networkLock = threading.Lock()

        self.defaultNetwork = config.getDefaultNetwork()

    def connect(self, ssid, pw, lock=True):
        if lock == True:
            self.networkLock.acquire()
        if self.network.current() != ssid:
            if timed(lambda: self.network.connect(ssid=ssid, password=pw), 8) == False:
                raise NetworkError(ssid)
            else:
                if ssid != self.network.current():
                    raise NetworkError(ssid)


    def disconnect(self):
        self.networkLock.release()

    def connectToDefault(self):
        self.network.connect(ssid=self.defaultNetwork[0], password=self.defaultNetwork[1])

    def getSSIDList(self):
        try:
            ssids = []
            nmc = NMClient.Client.new()
            devs = nmc.get_devices()
            for dev in devs:
                if dev.get_device_type() == NetworkManager.DeviceType.WIFI:
                    for ap in dev.get_access_points():
                        ssids.append(ap.get_ssid())
        except:
            pass
        return ssids

    def isGoPro(self, ssid):
        lettersMatched = 0
        matchWord = 'gopro'
        for char in ssid:
            if char.lower() == matchWord[lettersMatched]:
                lettersMatched += 1

                if lettersMatched == len(matchWord):
                    return True
        return False
Пример #4
0
 def guesser():
     """guess 'u' or 'h'"""
     try:
         from wireless import Wireless
         wireless = Wireless()
         connection = wireless.current()
         if connection.startswith('eduroam') or connection.startswith('saar'):
             return 'u'
         else:
             return 'h'
     except:
         return 'u'
Пример #5
0
def get_currently_connected_ap_ssid():
    # strip() trims the trailing newline character
    # Typically, decode-strip-split will convert the raw check_output() like
    # b'wlan0     ESSID:"NyankoLab-2.4G"\n'
    # into
    # ['wlan0', 'ESSID:"NyankoLab-2.4G"']
    #  stdout = subprocess.check_output(['iwgetid']).decode('utf-8').strip().split()
    #  logging.info(f'Wi-Fi AP info: {stdout}')
    #  if len(stdout) < 2:
    #    return ''
    #  essid_and_name = stdout[1].split(':')
    #  if len(essid_and_name) < 2:
    #    logging.warn(f'iwgetid returned SSID info in an unexpected format: {stdout}')
    #    return ''
    #  ssid = essid_and_name[1].strip('"')
    #  return ssid if 0 < len(ssid) else None
    w = Wireless()
    ssid = w.current()
    logging.info(f'Current ssid: {ssid}')
    return ssid
Пример #6
0
def getNetwork():
    """Tries to discover the name of the current network, first the
    network interface but then the name of the WiFi network, if no
    WiFi network is present, it will return the name of the network
    interface.  If there is no default route and thus no Internet then
    it will return an empty string."""
    gws = netifaces.gateways()
    # Need to make sure the default route exists.
    if gws['default'] != {}:
        defaultGW = gws['default'][netifaces.AF_INET]
        currentNetwork = defaultGW[1]
    else:  # If the above is true, there is no default route
        return ""

    # Now we need to check to see if we're on a WiFi network or not.
    w = Wireless()
    wName = w.current()
    if not wName is None:
        currentNetwork = wName

    return currentNetwork
def announce_ip():
    index = 0
    wireless = Wireless()
    while index < 200:
        print '++ attempting to announce ip: {}'.format(index)
        try:
            ip_address = get_ip()
            current_connection = wireless.current()
            print '++ found ip_address: {}'.format(str(ip_address))
            print '++ found current_connection: {}'.format(str(current_connection))
            routes = subprocess.check_output('route -n', shell=True)
            print '++ routes'
            print routes
            print '++ endroutes'
            if ip_address:
                slack_notify_message('@channel: its pi: {} | {}'.format(str(ip_address), str(current_connection)))
                break
            # else try to connect
            if USE_PYTHON_TO_CONNECT:
                print '++ trying to connect'
                connected = wireless.connect(ssid=SECRETS_DICT['WIFI_SSID'], password=SECRETS_DICT['WIFI_PASSWORD'])
                if not connected:
                    print ':-( failed to connect'
                else:
                    print ':) connected'
        except Exception as e:
            print ':/ error: {}'.format(str(e.message))
            pass
        index += 1
        time.sleep(1)
    # after we have connected, log some info about the connection
    if LOG_DETAILED_INFO:
        try:
            print '++++ logging detailed info'
            ifconfig = subprocess.check_output('ifconfig', shell=True)
            print 'ifconfig: {}'.format(ifconfig)
            iwget = subprocess.check_output('iwgetid', shell=True)
            print 'iwget: {} | {}'.format(iwget, get_ip())
        except Exception as e:
            print 'warning: failed to log detailed info: {}'.format(e.message)
Пример #8
0
def checkNetwork(ssid):
    timeout = 20
    sleeptime = 5
    loop = 0
    while loop < timeout:
        wireless = Wireless()
        s = wireless.current()

        # Connected to a wifi network
        if s is not None:
            # Total network
            if s == ssid:
                print("+-[Connected] to {}".format(ssid))
                return True
            # Another wifi network
            else:
                return True
        else:
            print("+-[Not connected] to {}. Waiting 5s to retry".format(ssid))
            time.sleep(sleeptime)
            loop += 1

    return False
Пример #9
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Find active users on the current wireless network.')
    parser.add_argument('-p',
                        '--packets',
                        default=1000,
                        type=int,
                        help='How many packets to capture.')
    parser.add_argument('-i',
                        '--interface',
                        default=None,
                        type=str,
                        help='Which wireless interface to use.')
    parser.add_argument('-s',
                        '--ssid',
                        default=None,
                        type=str,
                        help='Which SSID to use.')
    parser.add_argument('-r',
                        '--results',
                        default=None,
                        type=int,
                        help='How many results to show.')
    args = parser.parse_args()

    try:
        if args.interface:
            iface = args.interface
        else:
            wireless = Wireless()
            ifaces = wireless.interfaces()
            eprint('Available interfaces: {}'.format(', '.join(ifaces)))
            iface = ifaces[-1]
        eprint('Interface: {}'.format(iface))

        if args.ssid:
            ssid = args.ssid
        else:
            wireless = Wireless()
            ssid = wireless.current()
            if ssid is None:
                eprint(NO_SSID)
                return
        eprint('SSID: {}'.format(ssid))
    except:
        eprint(NO_WIRELESS)
        raise

    mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}'
    mac_re = re.compile(mac_re_str, re.I)
    network_macs = set()
    try:
        gws = netifaces.gateways()[netifaces.AF_INET]
        gw_ifaces = ', '.join([gw[1] for gw in gws])
        eprint('Available gateways: {}'.format(gw_ifaces))
        gw_ip = next(gw[0] for gw in gws if gw[1] == iface)
        eprint('Gateway IP: {}'.format(gw_ip))
        gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)])
        gw_arp = gw_arp.decode('utf-8')
        gw_mac = EUI(mac_re.search(gw_arp).group(0))
        gw_mac.dialect = mac_unix_expanded
        network_macs.add(gw_mac)
        eprint('Gateway MAC: {}'.format(gw_mac))
    except StopIteration:
        eprint('No gateway for {}'.format(iface))
    except KeyError:
        eprint('No gateways available: {}'.format(netifaces.gateways()))
    except:
        eprint(NO_GATEWAY_MAC)

    bssid_re = re.compile(' BSSID:(\S+) ')

    tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I)
    length_re = re.compile(' length (\d+)')
    client_macs = set()
    data_totals = defaultdict(int)

    cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split()
    try:
        bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}'
        progress = tqdm(run_process(cmd),
                        total=args.packets,
                        bar_format=bar_format)
        for line in progress:
            line = line.decode('utf-8')

            # find BSSID for SSID
            if ssid in line:
                bssid_matches = bssid_re.search(line)
                if bssid_matches:
                    bssid = bssid_matches.group(1)
                    if 'Broadcast' not in bssid:
                        network_macs.add(EUI(bssid))

            # count data packets
            length_match = length_re.search(line)
            if length_match:
                length = int(length_match.group(1))
                mac_matches = tcpdump_mac_re.findall(line)
                if mac_matches:
                    macs = set([EUI(match[1]) for match in mac_matches])
                    leftover = macs - network_macs
                    if len(leftover) < len(macs):
                        for mac in leftover:
                            data_totals[mac] += length
                            client_macs.add(mac)

        if progress.n < progress.total:
            eprint('Sniffing finished early.')

    except subprocess.CalledProcessError:
        eprint('Error collecting packets.')
        raise
    except KeyboardInterrupt:
        pass

    totals_sorted = sorted(data_totals.items(),
                           key=lambda x: x[1],
                           reverse=True)

    eprint('Total of {} user(s)'.format(len(totals_sorted)))

    for mac, total in reversed(totals_sorted[:args.results]):
        mac.dialect = mac_unix_expanded
        if total > 0:
            print('{}\t{} bytes'.format(mac, total))
Пример #10
0
portal = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port_number = 80

result = parser.read(configPath)
if len(result) == 1 and parser["APP_CONFIG"].get("AppConnected") == "True":

    filePath = parser["CLOUD_CONFIG"].get("SFP")
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(filePath)
    wifi_ssid = parser["APP_CONFIG"].get("SSID")
    logged_url = parser["APP_CONFIG"].get("CameraURL")
    logged_name = parser["APP_CONFIG"].get("CameraName")

    print("Configuration Loaded ...\nChecking Internet connection")

    wireless = Wireless()
    if wireless.current() != wifi_ssid:
        wireless.connect(ssid=wifi_ssid,
                         password=parser["APP_CONFIG"].get("PSK"))
        print("Connecting to {} ".format(wifi_ssid), end=".")
        wifi_connection_init = time.time()
        while wireless.current() != wifi_ssid:
            if time.time() - wifi_connection_init:
                print(
                    "Cannot connect to {} \nSetup failed...Program Exitted".
                    format(wifi_ssid),
                    end=".",
                )
                exit()
            print(end=".")
            continue
    # delay added due to dns resolution issues
Пример #11
0
# function to check the presense of SSID
def is_present(candidate):
    subprocess.call(["airport -s -x>ssids.xml"], shell=True)
    myplist = plistlib.readPlist('ssids.xml')
    print 'The current list is:', myplist
    for el in myplist:
        if candidate == el.get('SSID_STR'):
            print 'State is valid'
            return True
    print 'State is not valid'
    return False


wireless = Wireless()
print "Current: ", wireless.current()
print "Interfaces: ", wireless.interfaces()

# ---------  Open the files
lines = [line.strip() for line in open("Untitled.txt", 'r')]
dones = [line.strip() for line in open("Done.txt", 'r')]
subprocess.call(["airport -s -x>ssids.xml"], shell=True)
f = open('Results.txt', 'a')
f2 = open('Done.txt', 'a')
result = plistlib.readPlist('ssids.xml')
print 'Already done: ', dones

i = 0
# ------  Going to scan
for elem in result:
    victim = elem.get('SSID_STR')
Пример #12
0
    def __init__(self):
        super(mainApp, self).__init__()
        self.setupUi(self)

        # GUI thread things
        self.progress_bar_thread = progress_bar_thread()
        self.connect(self.progress_bar_thread, SIGNAL('update_progress_bar()'),
                     self.update_progress_bar)

        # initialize notification object
        if (platform.system() == 'Linux'):
            Notify.init('indistinct chatter')
            self.bubble = Notify.Notification.new('!', '?')
            image = GdkPixbuf.Pixbuf.new_from_file('egg.png')
            self.bubble.set_icon_from_pixbuf(image)

        if (platform.system() == 'Windows'):
            self.balloon = ToastNotifier()

        self.my_username = socket.getfqdn()

        # flag to tell if this host is a server
        self.isServer = False

        # data received from clients
        self.data = ['.', '.']

        # ip and connection info about chat clients
        self.addr_list = []
        self.conn_list = []

        # clients counter: chat client i .. media client j
        self.i = 0
        self.j = 0

        # setting text color for 'is typing...', chat area and error label
        self.lbl_typing.setStyleSheet('color: rgb(170, 0, 0)')
        self.txt_chat.setTextColor(QColor(50, 50, 50))
        self.lbl_error.setStyleSheet('color: rgb(255, 0, 0)')

        # connecting the GUI objects to their methods
        self.lndt_host.setFocus(True)

        try:
            wireless = Wireless()

            if (wireless.current() == 'RUN'):
                self.lndt_host.setText('192.168.1.')

            else:
                self.lndt_host.setText('127.0.0.1')

        except:
            self.lndt_host.setText('127.0.0.1')

        self.btn_send.clicked.connect(self.send_chat)
        self.btn_server.clicked.connect(self.server_conn)
        self.btn_client.clicked.connect(self.client_conn)
        self.btn_attach.clicked.connect(self.attach_file)

        # press enter to send a message instead of clicking send button
        self.lndt_msg.returnPressed.connect(self.send_chat)

        # press enter to connect as a client to the given server
        self.lndt_host.returnPressed.connect(self.client_conn)

        # send the 'I am typing' signal whenever the msg box text changes
        self.lndt_msg.textChanged.connect(self.typing_notification)

        # setting the chat socket connection parameters
        self.host = ''
        self.port = 5557

        # establishing a TCP connection for the chat server
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # this line allows re-using the same socket even if it was closed improperly
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        ################
        ## media part ##
        ################

        # ip and connection info about media clients
        self.media_addr_list = []
        self.media_conn_list = []

        # setting the media socket connection parameters
        self.media_host = ''
        self.media_port = 3245

        # establishing a TCP connection for the media server
        self.media_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # this line allows re-using the same socket even if it was closed improperly
        self.media_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
Пример #13
0
class AutoConnector(Thread):
    """ thread that connects to a wlan, if available, or creates a hotspot for other devices """
    def __init__(self, event):
        super().__init__()

        self.stopped = event
        self.count = 0
        self.wlan_count_found = 0
        self.wireless_module = Wireless()

        self.wlan_name_found_to_connect = ""
        self.wlan_name_found_to_connect_time = 999999999999

        # defines a hotspot object with the ssid "Test Wlan" and the password from the constants,
        # ssid will be changed later. Because of a known bug, the hotspot is stopped once before the start.
        self.access_point = pyaccesspoint.AccessPoint(
            ssid="Test Wlan", password=const.Connection.WLAN_PASSWORD)
        self.access_point.stop()

        self.hotspot_status = False
        self.own_wlan_name_from_hotspot = "parknet"
        self.own_wlan_time_from_hotspot = 9999999999999

        self.last_wlan_connected = "unset"
        self.block_list = []

    def run(self):
        """ starts scanning for wlan and connects to a wlan or starts a hotspot, if necessary """
        while not self.stopped.wait(5):
            self.wlan_count_found = 0
            self.count += 1
            print(f"Connected with: {self.wireless_module.current()}")

            if self.wireless_module.current() is None:
                if self.last_wlan_connected != "unset":
                    time_for_block = int(time.time()) + 60
                    self.add_to_block_list(self.last_wlan_connected,
                                           time_for_block)
                    self.last_wlan_connected = "unset"
            else:
                self.last_wlan_connected = self.wireless_module.current()

            self.wlan_scan()
            print(f"Loop Count: {self.count} Wlans: {self.wlan_count_found}")
            self.connect_to_network_or_create_hotspot()

    def wlan_scan(self):
        """ scans for wlan networks and selects the network that is called "parknet" and has existed the longest """
        self.wlan_name_found_to_connect = ""
        self.wlan_name_found_to_connect_time = 999999999999

        try:
            wlan_scans = Cell.all("wlan0")
            for wlan_scan in wlan_scans:
                if wlan_scan.ssid.startswith("parknet"):
                    if wlan_scan.ssid != self.own_wlan_name_from_hotspot:
                        try:
                            time_wlan_create = int(
                                wlan_scan.ssid.replace("parknet", ""))
                            if time_wlan_create < self.wlan_name_found_to_connect_time:
                                if not self.is_blocked(str(wlan_scan.ssid)):
                                    print(
                                        f"{wlan_scan.ssid} Quality: {wlan_scan.quality} Protected: {wlan_scan.encrypted}"
                                    )

                                    self.wlan_count_found += 1
                                    self.wlan_name_found_to_connect = wlan_scan.ssid
                                    self.wlan_name_found_to_connect_time = time_wlan_create
                                else:
                                    print(
                                        f"Blocked Wlan Hotspot Found: {wlan_scan.ssid}"
                                    )
                        except ValueError:
                            print(
                                f"Wrong Wlan Hotspot Found: {wlan_scan.ssid.replace('parknet', '')}"
                            )
                    else:
                        print(
                            f"Found own hotspot {wlan_scan.ssid} Quality: {wlan_scan.quality} Protected: {wlan_scan.encrypted}"
                        )

                if wlan_scan.ssid == "Lukas123":
                    print("Found Lukas Wlan")

                    self.wlan_name_found_to_connect = wlan_scan.ssid
                    self.wlan_name_found_to_connect_time = 1
                    self.wlan_count_found += 1
                    break
        except:
            print(f"Error while scanning for wifi {traceback.format_exc()}")

    def start_hotspot(self):
        """ starts a hotspot with the name "parkent" and the current time"""
        if not self.hotspot_status:
            print("Starting hotspot")

            self.own_wlan_name_from_hotspot = "parknet" + str(int(time.time()))
            self.own_wlan_time_from_hotspot = int(time.time())
            self.access_point.ssid = self.own_wlan_name_from_hotspot

            self.access_point.start()
            self.hotspot_status = True

    def stop_hotspot(self):
        """ stops the hotspot """
        if self.hotspot_status:
            print("Disabling hotspot")

            self.access_point.stop()
            self.hotspot_status = False
            self.own_wlan_time_from_hotspot = 9999999999999

    def connect_to_network_or_create_hotspot(self):
        """ starts a hotspot if no suitable wlan network was found or connects to a wlan"""
        if self.wlan_count_found <= 0:
            print("Hotspot mode")
            self.start_hotspot()
        elif self.own_wlan_time_from_hotspot > self.wlan_name_found_to_connect_time:
            if self.hotspot_status:
                print("Hotspot mode off")
                self.stop_hotspot()
            elif self.wireless_module.current(
            ) != self.wlan_name_found_to_connect:
                print(
                    f"Connecting to network {self.wlan_name_found_to_connect}")
                print(
                    f"Status: {self.wireless_module.connect(self.wlan_name_found_to_connect, const.Connection.WLAN_PASSWORD)}"
                )
                time.sleep(2)
                print(f"Wlan network: {self.wireless_module.current()}")

                if self.wireless_module.current() is not None:
                    self.last_wlan_connected = self.wireless_module.current()

    def is_blocked(self, ssid):
        """ checks whether an SSID is currently blocked

            Args:
                ssid(str): The name of the wlan that should be checked for a block

            Returns:
                bool: Whether the given ssid is blocked (True) or not (False)
        """
        for block in self.block_list:
            if block.ssid == ssid and block.blocktime > int(time.time()):
                return True
            else:
                return False

        return False

    def add_to_block_list(self, ssid, blocktime):
        """ blocks a ssid for a given time

            Args:
                ssid(str): The name of the wlan that should be blocked
                blocktime(int): Time how long the wlan name should be blocked
        """
        self.block_list.append(SSIDBlock(ssid, blocktime))
        print(f"Blocking {ssid} for {blocktime}")

    def print_list(self):
        """ prints a list of WLAN networks that were blocked at some point and whether they are currently blocked"""
        for block in self.block_list:
            print(f"{block} Blocked: {self.is_blocked(block.ssid)}")

    @staticmethod
    def start_connector():
        """ starts the thread for the AutoConnector"""
        stopFlag = Event()
        thread = AutoConnector(stopFlag)
        thread.start()
Пример #14
0
import SignalStrength


menuStrings=["________________________________ \n","Seleccione una opcion: \n","1-Buscar Redes","2-Medir Potencia", "3-Configuracion","4-Salir"]


while True:

#Menu Principal

	from wireless import Wireless
	wireless = Wireless()
	currentConection=wireless.current()

	
	print  menuStrings[0], "Conectado a la red ", currentConection,"\n", menuStrings[0]
	for i in range (1,len(menuStrings)):
		print menuStrings[i]
	print  menuStrings[0]

	  
      
	option=input()


	options = {1 : SignalStrength.Scan,
           	   2 : SignalStrength.Power,
	   	   3 : SignalStrength.RateConfig,
		   4 : exit, 
	  	  
Пример #15
0
button.when_held = shutdown
# When low battery alert goes high, trigger the shutdown
low_battery.when_pressed = shutdown

operation = 0

try:
    while True:
        blue_led.on()

        if operation == 0:
            hostname = socket.gethostname()
            show_message(hostname, operation)

        elif operation == 1:
            current_ap = wireless.current()
            show_message("Connected to %s" % current_ap, operation)

        elif operation == 2:
            ip_addresses = readIPaddresses()

            for addr in ip_addresses:
                if operation == 2:
                    show_message(addr, operation)

        elif operation == 3:
            # DHT11 on pin 23
            humidity, temperature = Adafruit_DHT.read_retry(11, 23)
            show_message(
                'Temp {0:0.1f}C  Humid {1:0.1f}%'.format(
                    temperature, humidity), operation)
Пример #16
0
class MainWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)

        ##### Camera / Wifi Configuration imports

        with open("sony/camera_settings.config") as json_file:
            json_data = json.load(json_file)

        self.SSID = json_data['ssid']
        self.PASSWORD = json_data['password']
        #self.MAC_ADDRESS = json_data['mac_address']
        self.IP_ADDRESS = json_data['ip_address']
        #self.MODEL = json_data['model']

        self.wireless = Wireless()

        if self.wireless.current() == self.SSID:
            self.api = Controller(self.IP_ADDRESS)
            self.sonycap = SonyCV(self.IP_ADDRESS)
        else:
            print "Camera WiFi not connected"

        self.fps = 30
        self.sdcard_path = None
        self.video_path = None

        # Creates QPixmap of a black rectangle as video placeholder
        # Livestream default size (Sony) = 640 x 360
        black_rect = QtGui.QPixmap(640, 360)
        black_rect.fill(QtGui.QColor("black"))

        ##### Widget Definitions / Settings

        self.video_frame_left = QtGui.QLabel()
        self.video_frame_right = QtGui.QLabel()
        self.video_frame_left.setPixmap(black_rect)
        self.video_frame_right.setPixmap(black_rect)

        self.listwidget = QtGui.QListWidget(self)

        self.SDPath_label = QtGui.QLabel(self)
        self.SDPath_label.setText("SD Card Path:")
        self.SDPathButton = QtGui.QPushButton("Set")
        self.SDPathButton.clicked.connect(self.getSDPath)
        self.SDPath = QtGui.QLineEdit(self)
        self.SDPath.setReadOnly(True)

        self.videoPath_label = QtGui.QLabel(self)
        self.videoPath_label.setText("Videos Destination:")
        self.videoPathButton = QtGui.QPushButton("Set")
        self.videoPathButton.clicked.connect(self.getVideoPath)
        self.videoPath = QtGui.QLineEdit(self)
        self.videoPath.setReadOnly(True)

        self.transfer_label = QtGui.QLabel(self)
        self.transfer_label.setText("Transfer Videos:")
        self.transfer_button = QtGui.QPushButton("Transfer")
        self.transfer_button.clicked.connect(self.get_files_from_sdcard)

        self.convert_videos_label = QtGui.QLabel(self)
        self.convert_videos_label.setText("Convert videos to h.264:")
        self.convert_videos_button = QtGui.QPushButton("Convert")
        self.convert_videos_button.clicked.connect(self.convert_videos)

        self.camera_wifi_label = QtGui.QLabel(self)
        self.camera_wifi_label.setText("Camera Wifi:")
        self.camera_wifi_connected_label = QtGui.QLabel(self)
        self.camera_wifi_connected()

        self.controls_label = QtGui.QLabel(self)
        self.controls_label.setText("Controls")
        self.controls_label.setFont(QtGui.QFont("Arial", 14, QtGui.QFont.Bold))
        self.controls_label.setAlignment(QtCore.Qt.AlignCenter)
        self.settings_label = QtGui.QLabel(self)
        self.settings_label.setText("Settings")
        self.settings_label.setFont(QtGui.QFont("Arial", 14, QtGui.QFont.Bold))
        self.settings_label.setAlignment(QtCore.Qt.AlignCenter)
        self.transfer_convert_label = QtGui.QLabel(self)
        self.transfer_convert_label.setText("Transfer / Convert")
        self.transfer_convert_label.setFont(QtGui.QFont("Arial", 14, QtGui.QFont.Bold))
        self.transfer_convert_label.setAlignment(QtCore.Qt.AlignCenter)

        self.stream_label = QtGui.QLabel(self)
        self.stream_label.setText("Live Stream:")
        self.stream_button = QtGui.QPushButton('Start')
        self.stream_bool = False
        #self.connect(self.stream_button, QtCore.SIGNAL("released()"), self.stream_toggle)
        self.stream_button.released.connect(self.stream_toggle)
        self.stream_light = QtGui.QLabel(self)

        self.record_label = QtGui.QLabel(self)
        self.record_label.setText("Video Record:")
        self.record_button = QtGui.QPushButton('On')
        self.record_bool = False
        #self.connect(self.stream_button, QtCore.SIGNAL("released()"), self.stream_toggle)
        self.record_button.released.connect(self.record_toggle)
        self.record_light = QtGui.QLabel(self)

        self.beepMode_label = QtGui.QLabel(self)
        self.beepMode_label.setText("Beep Mode:")
        self.beepMode_checkbox = QtGui.QCheckBox()
        self.connect(self.beepMode_checkbox, QtCore.SIGNAL('stateChanged(int)'), self.beep_toggle)

        self.flipMode_label = QtGui.QLabel(self)
        self.flipMode_label.setText("Video Flip:")
        self.flipMode_checkbox = QtGui.QCheckBox()
        self.connect(self.flipMode_checkbox, QtCore.SIGNAL('stateChanged(int)'), self.flip_toggle)

        self.format_quality_label = QtGui.QLabel(self)
        self.format_quality_label.setText("Format / Quality:")
        self.format_combobox = QtGui.QComboBox(self)
        self.connect(self.format_combobox, QtCore.SIGNAL('activated(int)'), self.quality_handler)
        self.quality_combobox = QtGui.QComboBox(self)
        self.connect(self.quality_combobox, QtCore.SIGNAL('activated(int)'), self.video_settings_handler)
        self.formats = ['XAVC S 4K', 'XAVC S', 'MP4']
        XAVC_S_4K_qualities = ['100M 30p', '60M 30p', '100M 24p', '60M 24p']
        XAVC_S_qualities = ['50M 60p', '50M 30p', '50M 24p', '100M 120p', '60M 120p', '100M 240p', '60M 240p']
        MP4_qualities = ['PS', 'HQ', 'STD', 'HS120', 'HS240']
        self.qualities = [XAVC_S_4K_qualities, XAVC_S_qualities, MP4_qualities]


        ##### Enabled / Disable buttons based on WiFi connection

        if self.wireless.current() == self.SSID:
            self.stream_button.setEnabled(True)
            self.record_button.setEnabled(True)
            self.beepMode_checkbox.setEnabled(True)
            self.flipMode_checkbox.setEnabled(True)
            self.format_combobox.setEnabled(True)
            self.quality_combobox.setEnabled(True)
        else:
            self.stream_button.setEnabled(False)
            self.record_button.setEnabled(False)
            self.beepMode_checkbox.setEnabled(False)
            self.flipMode_checkbox.setEnabled(False)
            self.format_combobox.setEnabled(False)
            self.quality_combobox.setEnabled(False)


        gridLayout = QtGui.QGridLayout()
        gridLayout.setSpacing(5)
        gridLayout.setContentsMargins(5, 5, 5, 5)

        # Top row
        gridLayout.addWidget(self.controls_label, 0, 0, 1, 3)
        gridLayout.addWidget(self.settings_label, 0, 3, 1, 3)
        gridLayout.addWidget(self.transfer_convert_label, 0, 7, 1, 3)
        gridLayout.addWidget(self.camera_wifi_label, 0, 11, 1, 1)
        gridLayout.addWidget(self.camera_wifi_connected_label, 0, 12, 1, 1)

        # Bottom row
        gridLayout.addWidget(self.video_frame_left, 5, 0, 1, 6)
        gridLayout.addWidget(self.video_frame_right, 5, 7, 1, 6)

        # Column 1
        gridLayout.addWidget(self.record_label, 1, 0, 1, 1)
        gridLayout.addWidget(self.record_button, 1, 1, 1, 1)
        gridLayout.addWidget(self.record_light, 1, 2, 1, 1)
        gridLayout.addWidget(self.stream_label, 2, 0, 1, 1)
        gridLayout.addWidget(self.stream_button, 2, 1, 1, 1)
        gridLayout.addWidget(self.stream_light, 2, 2, 1, 1)

        # Column 2
        gridLayout.addWidget(self.format_quality_label, 2, 3, 1, 1)
        gridLayout.addWidget(self.format_combobox, 2, 4, 1, 1)
        gridLayout.addWidget(self.quality_combobox, 2, 5, 1, 1)
        gridLayout.addWidget(self.beepMode_label, 3, 3, 1, 1)
        gridLayout.addWidget(self.beepMode_checkbox, 3, 4, 1, 1)
        gridLayout.addWidget(self.flipMode_label, 4, 3, 1, 1)
        gridLayout.addWidget(self.flipMode_checkbox, 4, 4, 1, 1)

        # Column 3
        gridLayout.addWidget(self.SDPath_label, 1, 7, 1, 1)
        gridLayout.addWidget(self.SDPathButton, 1, 8, 1, 1)
        gridLayout.addWidget(self.SDPath, 1, 9, 1, 1)
        gridLayout.addWidget(self.videoPath_label, 2, 7, 1, 1)
        gridLayout.addWidget(self.videoPathButton, 2, 8, 1, 1)
        gridLayout.addWidget(self.videoPath, 2, 9, 1, 1)
        gridLayout.addWidget(self.transfer_label, 3, 7, 1, 1)
        gridLayout.addWidget(self.transfer_button, 3, 8, 1, 1)
        gridLayout.addWidget(self.convert_videos_label, 4, 7, 1, 1)
        gridLayout.addWidget(self.convert_videos_button, 4, 8, 1, 1)

        # Column 4
        gridLayout.addWidget(self.listwidget, 1, 10, 4, 3)

        # (widget_name, row, column, rows spanned, columns spanned)

        self.setLayout(gridLayout)
        self.setWindowTitle('Control Panel')
        self.show()

        self.timer = QtCore.QTimer()

        self.init_gui_state()

    def init_gui_state(self):
        if self.wireless.current() == self.SSID:

            # Initialize beep mode setting
            if self.api.beepMode('Current') == 'On':
                self.beepMode_checkbox.setChecked(True)
            else:
                self.beepMode_checkbox.setChecked(False)

            # Initialize camera flip setting
            if self.api.flipSetting('Current') == 'On':
                self.flipMode_checkbox.setChecked(True)
            else:
                self.flipMode_checkbox.setChecked(False)

            # Initialize format / quality settings
            current_format, current_quality = self.api.videoSettings('Current')
            for i, format in enumerate(self.formats):
                self.format_combobox.addItem(format)

                if current_format == self.formats[i]:
                    self.format_combobox.setCurrentIndex(i)

                    qualities = self.qualities[i]
                    for k, quality in enumerate(qualities):
                        self.quality_combobox.addItem(qualities[k])
                        if current_quality == qualities[k]:
                            self.quality_combobox.setCurrentIndex(k)

    def camera_wifi_connected(self):
        if self.wireless.current() == self.SSID:
            self.camera_wifi_connected_label.setText("Connected")
            self.camera_wifi_connected_label.setStyleSheet('QLabel {color: green;}')
        else:
            self.camera_wifi_connected_label.setText("Not Connected")
            self.camera_wifi_connected_label.setStyleSheet('QLabel {color: red;}')

    def stream_toggle(self):
        #sending_button = self.sender()
        #print sending_button.text()
        if self.wireless.current() == self.SSID:
            self.stream_bool = not self.stream_bool
            if self.stream_bool:
                self.startCapture()
                self.stream_light.setText("Streaming")
                self.stream_light.setStyleSheet('QLabel {color: red;}')
                self.stream_button.setText("Stop")
                #self.stream_button.setStyleSheet('QPushButton {color: white;}')
            else:
                self.stopCapture()
                self.stream_light.setText("")
                self.stream_button.setText("Start")
                #self.stream_button.setStyleSheet('QPushButton {color: black;}')

    def record_toggle(self):
        #sending_button = self.sender()
        #print sending_button.text()
        if self.wireless.current() == self.SSID:
            self.record_bool = not self.record_bool
            if self.record_bool:
                self.api.recordMode('On')
                self.record_light.setText("Recording")
                self.record_light.setStyleSheet('QLabel {color: red;}')
                #self.record_light.setPixmap(QtGui.QPixmap("record-button.png"))
                self.record_button.setText("Off")
                #self.stream_button.setStyleSheet('QPushButton {color: white;}')
            else:
                self.api.recordMode('Off')
                self.record_light.setText("")
                self.record_button.setText("On")
                #self.stream_button.setStyleSheet('QPushButton {color: black;}')

    def startCapture(self):
        if self.wireless.current() == self.SSID:
            self.timer.timeout.connect(self.nextFrameSlot)
            self.timer.start(1000./self.fps)

    def stopCapture(self):
        self.timer.stop()

    def nextFrameSlot(self):
        frame = self.sonycap.capture()
        # Converts frame from BGR for RGB format
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        img = QtGui.QImage(frame, frame.shape[1], frame.shape[0], QtGui.QImage.Format_RGB888)

        pix = QtGui.QPixmap.fromImage(img)
        self.video_frame_left.setPixmap(pix)

    def beep_toggle(self):
        if self.wireless.current() == self.SSID:
            if self.beepMode_checkbox.isChecked():
                self.api.beepMode('On')
            else:
                self.api.beepMode('Off')

    def flip_toggle(self):
        if self.wireless.current() == self.SSID:
            if self.flipMode_checkbox.isChecked():
                self.api.flipSetting('On')
            else:
                self.api.flipSetting('Off')

    def video_settings_handler(self):
        current_format = str(self.format_combobox.currentText())
        current_quality = str(self.quality_combobox.currentText())

        # Selecting a quality after format will trigger a change
        # of settings on the camera
        self.api.videoSettings(current_format, current_quality)

    def quality_handler(self):
        current_format = str(self.format_combobox.currentText())
        self.quality_combobox.clear()

        for i, format in enumerate(self.formats):
            if current_format == self.formats[i]:
                qualities = self.qualities[i]

                for k, quality in enumerate(qualities):
                    self.quality_combobox.addItem(qualities[k])

    def getSDPath(self):
        sdcard_path = QtGui.QFileDialog.getExistingDirectory(
                      self,
                      "Open a folder",
                      "/Volumes",
                      QtGui.QFileDialog.ShowDirsOnly)
        self.sdcard_path = str(sdcard_path)
        self.SDPath.setText(sdcard_path)

    def getVideoPath(self):
        video_path = QtGui.QFileDialog.getExistingDirectory(
                     self,
                     "Open a folder",
                     expanduser("~"),
                     QtGui.QFileDialog.ShowDirsOnly)
        self.video_path = str(video_path)
        self.videoPath.setText(video_path)

    def get_files_from_sdcard(self):
        fm = fileMover(self.sdcard_path, self.video_path)
        fm.getFilesFromSDCard('XAVCS')

    def convert_videos(self):
        ffmpegConverter(self.video_path)
Пример #17
0
class GoProProxy:
    maxRetries = 3

    # init
    def __init__(self, log_level=logging.INFO):
        # setup log
        log_file = '/var/log/gopro-proxy.log'
        log_format = '%(asctime)s   %(message)s'
        logging.basicConfig(format=log_format, level=log_level)

        # file logging
        fh = logging.FileHandler(log_file)
        fh.setLevel(log_level)
        fh.setFormatter(logging.Formatter(log_format))
        logger = logging.getLogger()
        logger.setLevel(log_level)
        logger.addHandler(fh)

        # setup camera
        self.camera = GoProHero()
        self.snapshots = os.environ.get('GOPRO_SNAPSHOTS', True)

        # setup wireless
        interface = os.environ.get('GOPRO_WIFI_INTERFACE', None)
        self.wireless = Wireless(interface)

    # connect to the camera's network
    def connect(self, camera):
        func_str = 'GoProProxy.connect({}, {})'.format(
            camera.ssid, camera.password)

        # jump to a new network only if needed
        if self.wireless.current() != camera.ssid:
            self.wireless.connect(
                ssid=camera.ssid, password=camera.password)

        # evaluate connection request
        if self.wireless.current() == camera.ssid:
            # reconfigure the password in the camera instance
            self.camera.password(camera.password)

            logging.info('{}{}{}'.format(Fore.CYAN, func_str, Fore.RESET))
            return True
        else:
            logging.info('{}{} - network not found{}'.format(
                Fore.YELLOW, func_str, Fore.RESET))
            return False

    # send command
    def sendCommand(self, command):
        result = False

        # make sure we are connected to the right camera
        if self.connect(command.camera):
            # try to send the command, a few times if needed
            i = 0
            while i < self.maxRetries and result is False:
                result = self.camera.command(command.command, command.value)
                i += 1
        else:
            # mini-status update if we couldn't connect
            command.camera.last_attempt = timezone.now()
            command.camera.summary = 'notfound'

        # did we successfully talk to the camera?
        self.updateCounters(command.camera, result)
        command.camera.save()

        # save result
        command.time_completed = timezone.now()
        command.save()

    # get status
    def getStatus(self, camera):
        # make sure we are connected to the right camera
        camera.last_attempt = timezone.now()
        connected = self.connect(camera)

        # could we find the camera?
        if connected:
            # update counters
            camera.last_update = camera.last_attempt
            self.updateCounters(camera, True)

            # try to get the camera's status
            status = self.camera.status()
            camera.summary = status['summary']

            # extend existing status if possible
            if camera.status != '':
                # allows us to retain knowledge of settings when powered off
                try:
                    old_status = json.loads(camera.status)
                    if old_status != '':
                        old_status.update(status)
                        status = old_status
                except ValueError:
                    logging.info('{}{} - existing status malformed{}'.format(
                        Fore.YELLOW, 'GoProProxy.getStatus()', Fore.RESET))

            # save status to camera
            camera.status = json.dumps(status)

            # grab snapshot when the camera is powered on
            if self.snapshots is True and 'power' in status \
                    and status['power'] == 'on':
                camera.save()
                image = self.camera.image()
                if image is not False:
                    camera.image = image
                    camera.image_last_update = camera.last_attempt
        else:
            # update counters
            self.updateCounters(camera, False)

            # update status
            camera.summary = 'notfound'

        # save result
        camera.save()

    def updateCounters(self, camera, success):
        camera.connection_attempts += 1
        if success is not True:
            camera.connection_failures += 1

    # main loop
    def run(self):
        logging.info('{}GoProProxy.run(){}'.format(Fore.GREEN, Fore.RESET))
        logging.info('Wifi interface: {}, wifi driver: {}'.format(
            self.wireless.interface(), self.wireless.driver()))
        logging.info('Attempt snapshots: {}'.format(self.snapshots))

        # keep running until we land on Mars
        # keep the contents of this loop short (limit to one cmd/status or one
        # status) so that we can quickly catch KeyboardInterrupt, SystemExit
        while 'people' != 'on Mars':

            # PRIORITY 1: send command for the current network on if possible
            commands = Command.objects.filter(
                time_completed__isnull=True,
                camera__ssid__exact=self.wireless.current())
            if len(commands) > 0:
                self.sendCommand(commands[0])

                # get the status now because it is cheap
                if self.wireless.current() == commands[0].camera.ssid:
                    self.getStatus(commands[0].camera)

            # PRIORITY 2: send the oldest command still in the queue
            else:
                commands = Command.objects.filter(
                    time_completed__isnull=True).order_by('-date_added')
                if len(commands) > 0:
                    self.sendCommand(commands[0])

                    # get the status now because it is cheap
                    if self.wireless.current() == commands[0].camera.ssid:
                        self.getStatus(commands[0].camera)

                # PRIORITY 3: check status of the most stale camera
                else:
                    cameras = Camera.objects.all().order_by('last_attempt')
                    if len(cameras) > 0:
                        self.getStatus(cameras[0])

            # protect the cpu in the event that there was nothing to do
            time.sleep(0.1)
Пример #18
0
                               berry['y'], -1, berry['half'], 'qmark.jpg')

                    print "created not berry"
            state = 3
            size = len(ref.get())
            arr = ref.get()
            stats = []
            new_stats = []
            for i in range(1, size):
                stats.append(ref.child(str(i)).child('status').get())
            isc = False
        if state == 3:
            while (state != 4):
                if cv2.waitKey(1) == ord('u'):
                    send(7)
                    if wireless.current() != 'TELLO-AA1A76':
                        wireless.connect(ssid='TELLO-AA1A76', password='')
                    state = 5
                    break
                new_stats[:] = []
                ref = db.reference('/berries')
                for i in range(1, size):
                    new_stats.append(ref.child(str(i)).child('status').get())
                print("new status", new_stats)
                dif = len(new_stats) - len(stats)
                for i in range(dif):
                    stats.append('')

                for i in range(len(new_stats)):
                    if not (stats[i] != None and new_stats[i] != None
                            and int(new_stats[i]) == int(stats[i])):
Пример #19
0
class ServerBrain:

	def __init__(self, socket = None):
		
		self.socket = socket
		
		self.dronesName = ["Solo Gold", "Solo Green"]
		self.wifiConnections = {
			'Solo Gold' : ['SoloLink_gold', 'sololinkmst'],
			'Solo Green' : ['SoloLink_MST', 'sololinkmst']
		}
		#used to switch connection
		self.conn = Wireless()
		#array of drones initializer
		self.drones = {
			'Solo Gold' : drone.Drone('Solo Gold', self.wifiConnections['Solo Gold']),
			'Solo Green' : drone.Drone('Solo Green', self.wifiConnections['Solo Green'])
		}

	def getDistanceMeters(firstLocation, secondLocation):
		latitude = float(secondLocation.lat) - float(firstLocation.lat)
		longitude = float(secondLocation.lon) - float(firstLocation.lon)
		return math.sqrt((latitude*latitude) + (longitude*longitude))*1.113195e5

	def switchConnection(self, droneName):
		print "I'm going to switch WiFi connection, ", droneName
		return self.conn.connect(ssid=self.drones[droneName].wifiConnection[0], password=self.drones[droneName].wifiConnection[1])
		
	def connectDrone(self, droneName):
		
		if self.conn.current() != self.wifiConnections[droneName]:
			if self.switchConnection(droneName) == False:
				#self.conn.power(False) #this command sets off the WiFi antenna
				return droneName + " netwotk is not reacheble"
		
		self.drones[droneName].connect()
		location = self.drones[droneName].getActualLocation()
		
		return location

	def activateThread(self, functionName, name, listOfLocations):

		if functionName == "flight":
			eventlet.spawn(self.flight, listOfLocations, name)
	
	def arm(self, name):

		print "Arming... ", name
		self.switchConnection(name)
		self.drones[name].vehicle = connect('udpout:10.1.1.10:14560', wait_ready=True)
		
		print "Current WiFi network: ", self.conn.current()
		
		print "Vehicle of " + name + " is: ", self.drones[name].vehicle is not None
		
		print name + " is armable: ", self.drones[name].vehicle.is_armable
		while not self.drones[name].vehicle.is_armable:
			print "Waiting for vehicle to initialise..", name
			
		self.drones[name].vehicle.mode = VehicleMode("GUIDED")
		self.drones[name].vehicle.armed = True

		print name + " armed: ", self.drones[name].vehicle.armed
		while not self.drones[name].vehicle.armed:
			print "Waiting for arming ", name
			time.sleep(1)
		print "I finish the arm function execution and I'm ready to take off, ", name

	def flight(self, listOfLocations, name):
		print "I'm " + name + " and I'm inside flight function"
		
		self.arm(name)
		targetAltitude = 2
		self.drones[name].vehicle.simple_takeoff(targetAltitude)
		
		eventlet.sleep(5)
		
		while True:
			print "I'm trying to understand if I reach the target altitude ", name
			eventlet.sleep(3)
			self.switchConnection(name)
			message = {"reached": False , "altitude": self.drones[name].vehicle.location.global_relative_frame.alt, "name" : name}
			if self.drones[name].vehicle.location.global_relative_frame.alt >= targetAltitude*0.95:
				message = {"reached": True , "altitude": targetAltitude, "name" : name}
				self.drones[name].vehicle.mode = VehicleMode('RTL')
			self.socket.emit('Altitude Reached', message)
			if message["reached"] == True:
				break

		eventlet.sleep(3)

		self.drones[name].buildListOfLocations(listOfLocations)

		for locationToReach in listOfLocations:
			eventlet.sleep(3)
			self.switchConnection(name)
			#self.drones[name].vehicle = connect('udpout:10.1.1.10:14560', wait_ready=True)
			print "Location to reach for " + name + " is ", locationToReach
			soloCurrentLocation = vehicle.location.global_relative_frame
			targetDistance = self.getDistanceMeters(soloCurrentLocation, locationToReach)
			self.drones[name].vehicle.simple_goto(locationToReach)
			eventlet.sleep(2)
			while True:
				self.switchConnection(name)
				soloCurrentLocation = self.drones[name].vehicle.global_relative_frame
				remainingDistance = self.getDistanceMeters(soloCurrentLocation, targetDistance)
				socketio.emit('Update Live Location', {
					"name": name,
					"status": "flying",
					"latitude" : soloCurrentLocation.lat,
					"longitude" : soloCurrentLocation.lon, 
					"altitude" : soloCurrentLocation.alt,
					})
				if remainingDistance <= targetDistance * 0.05:
					#here the code for taking picture
					socketio.emit('Update Live Location', {
					"name": name,
					"status": "reached"
					})
					break
				eventlet.sleep(2)
		#self.drones[name].vehicle = connect('udpout:10.1.1.10:14560', wait_ready=True)
		self.drones[name].vehicle.mode = VehicleMode('RTL')









		
Пример #20
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Find active users on the current wireless network.')
    parser.add_argument('-p',
                        '--packets',
                        default=1000,
                        type=int,
                        help='How many packets to capture.')
    parser.add_argument('-r',
                        '--results',
                        default=None,
                        type=int,
                        help='How many results to show.')
    args = parser.parse_args()

    try:
        wireless = Wireless()
        ssid = wireless.current()
        if ssid is None:
            eprint(
                'No SSID is currently available. Connect to the network first.'
            )
            return
        eprint('SSID: {}'.format(ssid))
    except:
        eprint('Couldn\'t get current wireless SSID.')
        raise

    network_macs = set()
    try:
        gw = netifaces.gateways()['default'][netifaces.AF_INET]
        iface = gw[1]
        gw_arp = subprocess.check_output(['arp', '-n', str(gw[0])])
        gw_arp = gw_arp.decode('utf-8')
        gw_mac = EUI(re.search(' at (.+) on ', gw_arp).group(1))
        gw_mac.dialect = mac_unix_expanded
        network_macs.add(gw_mac)
        eprint('Gateway: {}'.format(gw_mac))
    except KeyError:
        eprint('No gateway is available: {}'.format(netifaces.gateways()))
        return
    except:
        eprint('Error getting gateway mac address.')

    bssid_re = re.compile(' BSSID:(\S+) ')
    da_re = re.compile(' DA:(\S+) ')
    sa_re = re.compile(' SA:(\S+) ')

    mac_re = re.compile('(SA|DA|BSSID):(([\dA-F]{2}:){5}[\dA-F]{2})', re.I)
    length_re = re.compile(' length (\d+)')
    client_macs = set()
    data_totals = defaultdict(int)

    cmd = 'tcpdump -i {} -Ile -c {}'.format(iface, args.packets).split()
    try:
        bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}'
        for line in tqdm(run_process(cmd),
                         total=args.packets,
                         bar_format=bar_format):
            line = line.decode('utf-8')

            # find BSSID for SSID
            if ssid in line:
                bssid_matches = bssid_re.search(line)
                if bssid_matches:
                    bssid = bssid_matches.group(1)
                    if not 'Broadcast' in bssid:
                        network_macs.add(EUI(bssid))

            # count data packets
            length_match = length_re.search(line)
            if length_match:
                length = int(length_match.group(1))
                mac_matches = mac_re.findall(line)
                if mac_matches:
                    macs = set([EUI(match[1]) for match in mac_matches])
                    leftover = macs - network_macs
                    if len(leftover) < len(macs):
                        for mac in leftover:
                            data_totals[mac] += length
                            client_macs.add(mac)

    except subprocess.CalledProcessError:
        eprint('Error collecting packets.')
        raise
    except KeyboardInterrupt:
        pass

    print()

    totals_sorted = sorted(data_totals.items(),
                           key=lambda x: x[1],
                           reverse=True)

    eprint('Total of {} user(s)'.format(len(totals_sorted)))

    for mac, total in reversed(totals_sorted[:args.results]):
        mac.dialect = mac_unix_expanded
        if total > 0:
            print('{}\t{} bytes'.format(mac, total))
Пример #21
0
class ConnectToSSID:
    def __init__(self, ssid, password):
        self.ssid = ssid
        self.password = password
        self.wireless = Wireless()
        self.system = platform.system()
    
    def connect(self):
        if self.system == 'Linux':
            self.connect_linux()
        if self.system == 'Darwin':
            self.connect_osx()
        if self.system == 'Windows':
            self.connect_windows()
                    
    def connect_linux(self):
        while(True):
            if self.wireless.current() == self.ssid:
                print "Already connected to {0}".format(self.ssid)
                break
                
            while self.wireless.current() != self.ssid:
                print "Connecting..."
                self.wireless.connect(ssid=self.ssid, password=self.password)
                if self.wireless.current() == self.ssid:
                    print "Connected to: {0}".format(self.ssid)
                    break
    
    def get_mac_address(self):
   		ifname = 'wlan0'
		s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
		return ':'.join(['%02x' % ord(char) for char in info[18:24]])	
    
    def connect_osx(self):
        reload(sys)
        sys.setdefaultencoding('utf8')
        ssid_osx = self.ssid.replace (" ", "\ ")
        
        while(True):
            if self.wireless.current() == self.ssid:
                print "Already connected to {0}".format(self.ssid)
                break
            
            while(True):
                if self.find_ssid() == True:
                    print "SSID: {0} found".format(self.ssid)
                    break
                    
            while(True):
                if self.wireless.current() != self.ssid:
                    print "Connecting..."
                    try:
                        threading.Timer(5, self.timeout).start()
                        self.wireless.connect(ssid=ssid_osx, password=self.password)
                    except:
                        break
            if self.wireless.current() == self.ssid:
                print "Connected to: {0}".format(self.ssid)
                break
    
    def ssid_list(self):
        cmd = '/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s'
        p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
        output = p.stdout.read()
        output = str(output)
        return output
        
    def find_ssid(self):
        while(True):
            ssid_list = self.ssid_list()
            num = int(ssid_list.find(self.ssid))
            
            if num >= 0:    
                return type(num) is int
            if num < 0:    
                print "Searching for SSID: {0}".format(self.ssid)
                continue
            break
    
    def timeout(self):
        thread.interrupt_main()
    
    def connect_windows(self):
        print "Doesn't currently support Windows"
Пример #22
0
def main(args):
    parser = argparse.ArgumentParser(
        description='Find active users on the current wireless network.')
    parser.add_argument('-p', '--packets',
                        default=1000,
                        type=int,
                        help='How many packets to capture.')
    parser.add_argument('-i', '--interface',
                        default=None,
                        type=str,
                        help='Which wireless interface to use.')
    parser.add_argument('-s', '--ssid',
                        default=None,
                        type=str,
                        help='Which SSID to use.')
    parser.add_argument('-r', '--results',
                        default=None,
                        type=int,
                        help='How many results to show.')
    args = parser.parse_args()

    try:
        if args.interface:
            iface = args.interface
        else:
            wireless = Wireless()
            ifaces = wireless.interfaces()
            eprint('Available interfaces: {}'.format(', '.join(ifaces)))
            iface = ifaces[-1]
        eprint('Interface: {}'.format(iface))

        if args.ssid:
            ssid = args.ssid
        else:
            wireless = Wireless()
            ssid = wireless.current()
            if ssid is None:
                eprint(NO_SSID)
                return
        eprint('SSID: {}'.format(ssid))
    except:
        eprint(NO_WIRELESS)
        raise

    mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}'
    mac_re = re.compile(mac_re_str, re.I)
    network_macs = set()
    try:
        gws = netifaces.gateways()[netifaces.AF_INET]
        gw_ifaces = ', '.join([gw[1] for gw in gws])
        eprint('Available gateways: {}'.format(gw_ifaces))
        gw_ip = next(gw[0] for gw in gws if gw[1] == iface)
        eprint('Gateway IP: {}'.format(gw_ip))
        gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)])
        gw_arp = gw_arp.decode('utf-8')
        gw_mac = EUI(mac_re.search(gw_arp).group(0))
        gw_mac.dialect = mac_unix_expanded
        network_macs.add(gw_mac)
        eprint('Gateway MAC: {}'.format(gw_mac))
    except StopIteration:
        eprint('No gateway for {}'.format(iface))
    except KeyError:
        eprint('No gateways available: {}'.format(netifaces.gateways()))
    except:
        eprint(NO_GATEWAY_MAC)

    bssid_re = re.compile(' BSSID:(\S+) ')

    tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I)
    length_re = re.compile(' length (\d+)')
    client_macs = set()
    data_totals = defaultdict(int)

    cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split()
    try:
        bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}'
        progress = tqdm(run_process(cmd),
                        total=args.packets,
                        bar_format=bar_format)
        for line in progress:
            line = line.decode('utf-8')

            # find BSSID for SSID
            if ssid in line:
                bssid_matches = bssid_re.search(line)
                if bssid_matches:
                    bssid = bssid_matches.group(1)
                    if 'Broadcast' not in bssid:
                        network_macs.add(EUI(bssid))

            # count data packets
            length_match = length_re.search(line)
            if length_match:
                length = int(length_match.group(1))
                mac_matches = tcpdump_mac_re.findall(line)
                if mac_matches:
                    macs = set([EUI(match[1]) for match in mac_matches])
                    leftover = macs - network_macs
                    if len(leftover) < len(macs):
                        for mac in leftover:
                            data_totals[mac] += length
                            client_macs.add(mac)

        if progress.n < progress.total:
            eprint('Sniffing finished early.')

    except subprocess.CalledProcessError:
        eprint('Error collecting packets.')
        raise
    except KeyboardInterrupt:
        pass

    totals_sorted = sorted(data_totals.items(),
                           key=lambda x: x[1],
                           reverse=True)

    eprint('Total of {} user(s)'.format(len(totals_sorted)))

    for mac, total in reversed(totals_sorted[:args.results]):
        mac.dialect = mac_unix_expanded
        if total > 0:
            print('{}\t{} bytes'.format(mac, total))
Пример #23
0
# Check if a wifi adapter is available
try:
    wifi = Wireless()
    wlan_interface = wifi.interfaces()[0]
except Exception as e:
    psm.screen.fillRect(0, 0, 320, 240, fill = (0,0,0), display = False)
    psm.screen.drawAutoText("No Wi-Fi adapter", 35, 20, fill = (255,0,0), size = 25, display = False)
    psm.screen.drawAutoText("available!", 35, 50, fill = (255,0,0), size = 25, display = False)
    psm.screen.drawButton(35, 160, width = 250, height = 40, text="Continue", display=False)
    psm.screen.fillRect(0, 0, 1, 1, fill = (0,0,0), display = True)
    while True:
        cont = psm.screen.checkButton(35, 160, 250, 40)
        if cont: sys.exit(0)

current = wifi.current() # Currently connected network
available = Cell.all(wlan_interface) # Available networks
box = TouchScreenInput(psm.screen)

# Writes wifi configuration to wpa_supplicant.conf
def write_to_config(new):
    # Makes backup by appending to wpa_supplicant.conf~bk
    with open(config_file, "r") as f:
        bak = f.read()
    with open(config_file+"~bk", "a+") as f:
        f.write("\n\n---------------------------\n" + str(int(time.time())) + "\n\n" + new)
    # Writes new configuration
    with open(config_file, "w") as f:
        f.write(new)

# Deletes connection details for a network
Пример #24
0
from wireless import Wireless

wireless = Wireless()
print(wireless.current())

# python3 -m pip install wireless
#only MAC
Пример #25
0
def update_current_connection():
    global wifi, current
    wifi = Wireless()
    current = wifi.current()
Пример #26
0
    spoofMAC = randomMAC()
    print('MAC Address: {}').format(MAC)
    print('Fake MAC Address: {}').format(spoofMAC)
    print('\n')

    if wifi.power() == False:
        print 'Wireless Adapter is Off, turning ON'
        wifi.power(True)
        macAddressChanger(NetworkInterface, spoofMAC)
    else:
        macAddressChanger(NetworkInterface, spoofMAC)

print('\n')
print("Restarting Wireless Adapter")
#RESTART WIRELESS ADAPTER FOR MACCHANGER
if wifi.current() == None:
    wifi.power(False)
else:
    wifi.power(False)
wifi.power(True) 
print("Wireless Adapter is ON!")

#WIRELESS SCAN
print('\n')
print("Scanning for Open Wireless Networks")
wifiScan = subprocess.Popen(['airport', '-s'], stdout=subprocess.PIPE)
(output, err) = wifiScan.communicate()
wifiScanResult = scanNone(output)

#MENU SELECTOR PARA ESCOGER EL WIFI PUBLICO
#EVALUAR STATUS SI CONECTA A LA RED O NO!
Пример #27
0
sys.setdefaultencoding('utf8')

# function to check the presense of SSID
def is_present (candidate):
    subprocess.call(["airport -s -x>ssids.xml"], shell=True)
    myplist = plistlib.readPlist('ssids.xml')
    print 'The current list is:', myplist
    for el in myplist:
        if candidate == el.get('SSID_STR'):
            print 'State is valid'
            return True
    print 'State is not valid'
    return False

wireless = Wireless()
print "Current: ", wireless.current()
print "Interfaces: ",wireless.interfaces()

# ---------  Open the files
lines = [line.strip() for line in open("Untitled.txt", 'r')]
dones = [line.strip() for line in open("Done.txt", 'r')]
subprocess.call(["airport -s -x>ssids.xml"], shell=True)
f= open('Results.txt', 'a')
f2= open('Done.txt', 'a')
result = plistlib.readPlist('ssids.xml')
print 'Already done: ', dones

i = 0
# ------  Going to scan
for elem in result:
    victim = elem.get('SSID_STR')
Пример #28
0
    print('MAC Address: {}').format(MAC)
    print('Fake MAC Address: {}').format(spoofMAC)
    print('\n')

    if wifi.power() == False:
        print 'Wireless Adapter is Off, turning ON'
        wifi.power(True)
        macAddressChanger(NetworkInterface, spoofMAC)
    else:
        macAddressChanger(NetworkInterface, spoofMAC)

if argsCurrent == 0:
    print('\n')
    print("Restarting Wireless Adapter")
    #RESTART WIRELESS ADAPTER FOR MACCHANGER
    if wifi.current() == None:
        wifi.power(False)
    else:
        wifi.power(False)
    wifi.power(True) 
    print("Wireless Adapter is ON!")

    #WIRELESS SCAN
    print('\n')
    print("Scanning for Open Wireless Networks")
    wifiScan = subprocess.Popen(['airport', '-s'], stdout=subprocess.PIPE)
    (output, err) = wifiScan.communicate()
    wifiScanResult = scanNone(output)

    #MENU SELECTOR PARA ESCOGER EL WIFI PUBLICO
    #EVALUAR STATUS SI CONECTA A LA RED O NO!
Пример #29
0
import urllib2, sys, time, socket
from wireless import Wireless

userName = "******"
password = "******"

ssid = Wireless()

print ssid.current()

sleepTime = 10
socket.setdefaulttimeout(sleepTime)

hostname = ['https://192.168.10.3/connect/PortalMain', '192.168.10.3']
url = "connect/PortalMain?action=doLoginSubmit&flowId=UserLogin&username="******"&password="******"/tmp/Wifi.log", 'w')

else:
    try:
        fh = open(file, 'w')
    except IOError:
        print "Error writing to file %s\n" % (file)


def setup():
    if len(sys.argv) > 1:
        userName = sys.argv[1]
        password = sys.argv[2]
Пример #30
0
 def getSSID():
   from wireless import Wireless
   wireless = Wireless()
   return  wireless.current()
Пример #31
0
class ServerBrain:
    def __init__(self, socket=None):

        self.socket = socket
        #used to switch connection
        self.connectionManager = Wireless()

        #array of drone initializer
        self.drones = {'Solo Gold': None, 'Solo Green': None}

    '''
	This method returns a list that contains the name of the drones in the system
	'''

    def getDroneNames(self):
        droneList = list()
        for drone in self.drones:
            droneList.append(drone)
        return droneList

    '''
	This method is used for creating an instance of the class Drone.
	'''

    def connectDrone(self, droneName):
        '''
		Trying to find a free network for the drone
		'''

        interface, network = self.__getNetwork__(droneName, 'drone')
        if (interface, network) == (False, False):
            return droneName + " network is not reacheable"
        else:
            infosToReturn = {}
            self.drones[droneName] = Drone(droneName, interface, network)
            try:
                self.drones[droneName].connect()
                infosToReturn['drone status'] = 'available'
                infosToReturn['home location'] = self.drones[
                    droneName].getCurrentLocation()
                infosToReturn['drone battery'] = self.drones[
                    droneName].getBattery()
                infosToReturn['camera status'] = 'available'
                return infosToReturn
            except Exception as e:
                print "Error on establishing a connection with the " + droneName
                #raise
                return "timeout expired"

    '''
	This method assigns the locations to reach to the Solo passed as parameter.
	'''

    def buildPath(self, droneName, locationsToReach):
        '''
		algorithm for building a path for droneName
		'''
        self.drones[droneName].buildListOfLocations(locationsToReach)
        return {
            'drone':
            droneName,
            'locations to reach':
            self.drones[droneName].serializeListOfLocationsToReach()
        }

    def buildRandomPath(self, droneInvolved):
        if self.drones[droneInvolved] is None:
            return "ERROR"
        import randomflytry
        randomSurveyLocation = randomflytry.randMissionRead('randMission.txt')
        locations = []
        for location in randomSurveyLocation['picList']:
            '''
			location is a mission class instance. I can access to the single location values in a simple way:
			- location.latitude
			- location.longitude
			- location.altitude
			'''
            locations.append({
                "latitude": location.latitude,
                "longitude": location.longitude,
                "altitude": location.altitude
            })
            pass
        self.drones[droneInvolved].buildListOfLocations(locations)
        return {'drone': droneInvolved, 'locations': locations}

    '''
	This method generates the points inside the rectangular area delimited by the 3 points sent by client.
	If the 3 points are perfectly put from client, this method will return all the points to client and moreover it will assing these points to
	each Solo involved in the survey. Otherwise it will notify the client of the possibile errors it has got.
	'''

    def buildRectangularSurveyPointsReal(self, data):

        points = data['locationsList']
        altitude = points[0]['altitude']
        involvedDrones = data['drones']
        #check if involved drones are connected
        for drone in involvedDrones:
            if self.drones[drone] == None:
                missionDivisionData = {
                    'response':
                    'Connection Error',
                    'body':
                    'You need to be connected with the drones involved in the rectangular survey'
                }
                return missionDivisionData
        pointsNewFormat = []
        import rectPlan
        for point in points:
            pointsNewFormat.append(
                rectPlan.latlon(point['latitude'], point['longitude']))

        result = rectPlan.rectMission(pointsNewFormat[0], pointsNewFormat[1],
                                      pointsNewFormat[2], altitude)
        if result == 'Bad':
            return result
        #print "Result: ", result['picList']

        droneList = []
        for drone in data['drones']:
            droneList.append(drone)
            location = self.drones[drone].getCurrentLocation()
            droneList.append(location['latitude'])
            droneList.append(location['longitude'])

        missionDivisionData = rectPlan.missionDivision(result, droneList)
        missionDivisionData = rectPlan.serializeMissionData(
            missionDivisionData)
        '''
		Assign locations to reach to each involved drone
		'''
        if missionDivisionData['response'] == 'Good' or missionDivisionData[
                'response'] == 'Warn':
            #filling the locationsToReach array for each involved drone
            for UAVInfo in missionDivisionData['UAVs']:
                drone = UAVInfo['name']
                self.drones[drone].buildListOfLocations(UAVInfo['points'])
        return missionDivisionData

    '''
	Same of precedent method but cheating...
	'''

    def buildRectangularSurveyPointsCheating(self, data):
        points = data['locationsList']
        altitude = points[0]['altitude']
        involvedDrones = data['drones']
        #check if involved drones are connected
        for drone in involvedDrones:
            if self.drones[drone] == None:
                missionDivisionData = {
                    'response':
                    'Connection Error',
                    'body':
                    'You need to be connected with the drones involved in the rectangular survey'
                }
                return missionDivisionData
        pointsNewFormat = []
        import rectPlan
        for point in points:
            pointsNewFormat.append(
                rectPlan.latlon(point['latitude'], point['longitude']))

        result = rectPlan.rectMission(pointsNewFormat[0], pointsNewFormat[1],
                                      pointsNewFormat[2], altitude)
        if result == 'Bad':
            return result
        #print "Result: ", result['picList']

        droneList = []
        for drone in data['drones']:
            droneList.append(drone)
            location = self.drones[drone].getCurrentLocation()
            droneList.append(location['latitude'])
            droneList.append(location['longitude'])

        missionDivisionData = rectPlan.missionDivisionCheating(
            result, droneList, data['total'])
        #missionDivisionData = rectPlan.missionDivision(result, droneList)
        missionDivisionData = rectPlan.serializeMissionData(
            missionDivisionData)
        #dataToReturn is required for keeping data on missionDivisionData correct. In fact with the modify of "completed" field in eache UAVInfo object,
        #the risk is that client could not understand which points to show. File will be modified with the missionDivisionData updated for each drone("completed" key's value).
        dataToReturn = missionDivisionData
        '''
		Assign locations to reach to each involved drone
		'''
        if missionDivisionData['response'] == 'Good' or missionDivisionData[
                'response'] == 'Warn':
            #filling the locations to reach array for each drone involved
            UAVInfo = missionDivisionData['UAVs']
            for index in xrange(0, len(UAVInfo)):
                drone = UAVInfo[index]['name']
                #if drone has already a filled list of locations to reach, I need to go ahead
                #otherwise I need to understand if the mission has been already completed and if not I can assign points to the associated drone and set the key "completed" to True
                if self.drones[drone] is not None:
                    if self.drones[drone].listOfLocationsToReach is None:
                        self.drones[drone].buildListOfLocations(
                            UAVInfo[index]['points'])
                        UAVInfo[index]['to complete'] = True
                else:
                    print "This drone has already locations to reach"
            missionDivisionData['UAVs'] = UAVInfo
            file = open("oldSurvey.txt", "w")
            file.write(str(missionDivisionData))
            file.close()
        return dataToReturn

    '''
	This method allows to upload the points to reach by the Solos from a file where there is a dictionary with a particular structure.
	The structure of the dictionary is:
		missionDivisionData = {
			'response' : 'Good|Warm|Error',
			'UAVs' : [ {
				'name' : '..',
				'points' : [loc1, loc2, ...],
				'to complete' : True|False,
				'completed' : True|False
			},
			{
				'name' : '..',
				'points' : [loc1, loc2, ...],
				'to complete' : True|False,
				'completed' : True|False
			}]
		}
	As you can see the dictionary contains information about the last multiple flight that has involved multiple Solos.
	This method searches for that element of the array in missionDivisionData['UAVs'] that belongs to a connected Solo and that has key 'to complete' set to True.
	Once it finds the element of the array, it will upload the points in the key 'points' to the current listOfLocationsToReach associated to the current Solo.
	After the uploading (that can involve multiple Solos), this method will update the file with the new information about the old survey.
	'''

    def checkOldSurvey(self):
        #taking information about old survey not completed
        missionDivisionData = (open("oldSurvey.txt", "r").read())
        if len(missionDivisionData) == 0:
            return "No old survey to end"
        missionDivisionData = eval(missionDivisionData)
        #dataToReturt is required for keeping data on missionDivisionData correct. In fact with the modify of "completed" field in eache UAVInfo object,
        #the risk is that client could not understand which points to show. File will be modified with the missionDivisionData updated for each drone("completed" key's value).
        dataToReturn = missionDivisionData
        UAVInfo = missionDivisionData['UAVs']
        for index in xrange(0, len(UAVInfo)):
            drone = UAVInfo[index]['name']
            #if drone has already a filled list of locations to reach, I need to go ahead
            #otherwise I need to understand if the mission has been already completed and if not I can assign points to the associated drone and set the key "completed" to True
            if self.drones[drone] is not None:
                if self.drones[drone].listOfLocationsToReach is not None:
                    print drone + " has already locations to reach"
                else:
                    print drone + " has an empty list of locations"
                    if UAVInfo[index]['completed'] == False:
                        self.drones[drone].buildListOfLocations(
                            UAVInfo[index]['points'])
                        UAVInfo[index]['to complete'] = True
                    else:
                        print "This set of points has been completed"
        missionDivisionData['UAVs'] = UAVInfo
        file = open("oldSurvey.txt", "w")
        file.write(str(missionDivisionData))
        file.close()
        return dataToReturn

    '''
	This method creates a thread for a drone's flight.
	'''

    def takeAFlight(self, drone):
        if self.drones[
                drone] is not None and self.drones[drone].firstFlight is False:
            print drone + " has already had a flight, for the next flight I need to clear its memory.."
            self.drones[drone].cleanTheMemory()

        # we use the singleFlightWithTheUsingOfSolosMemory for the random flight
        eventlet.spawn(
            self.drones[drone].singleFlightWithTheUsingOfSolosMemory,
            self.connectionManager, self.socket)

    '''
	This method allows the drone to have an oscillation flight.
	'''

    def takeAnOscillationFlight(self, drone):
        data = self.drones[drone].oscillationFlight()
        return data

    '''
	This method starts the rectangular survey flight creating threads for each Solo involved.
	'''

    def takeARectangularFlight(self):
        #I need to be sure that the memory has been cleaned
        for drone in self.drones:
            if self.drones[drone] is not None and self.drones[
                    drone].firstFlight is False:
                print drone + " has already had a flight, for the next flight I need to clear its memory.."
                self.drones[drone].cleanTheMemory()

        for drone in self.drones:
            if self.drones[drone] is not None:
                if len(self.drones[drone].listOfLocationsToReach) > 0:
                    print "launching the thread for " + drone + " for having a flight."
                    eventlet.spawn(
                        self.drones[drone].flightWithTheUsingOfSolosMemory,
                        self.connectionManager, self.socket)
                    eventlet.sleep(15)
                    #time.sleep(10)

    '''
	This method is used for building the wifi network name the drone will connect to.
	'''

    def __getNetworkName__(self, type, drone):
        color = drone.split(
        )[1]  # I've just taken the drone color from drone name(ex:'Solo Gold')
        if type == "drone":
            print "Drone setting network"
            wifiNetwork = "SoloLink_" + color + "Drone"
        return wifiNetwork

    '''
	This method is designed in order to get network interface value and wifi network name for the Solo.
	'''

    def __getNetwork__(self, drone, type):
        wifiNetwork = self.__getNetworkName__(type, drone)
        print wifiNetwork
        '''This for-loop checks if this network is already connected '''
        for interface in self.connectionManager.interfaces():
            self.connectionManager.interface(interface)
            print self.connectionManager.current()
            if self.connectionManager.current() == wifiNetwork:
                print "You are already connected to this network, ", wifiNetwork
                self.connectionManager.connect(ssid=wifiNetwork,
                                               password="******")
                return self.connectionManager.interface(
                ), self.connectionManager.current()
            print self.connectionManager.current()
        '''This for-loop checks if this network has not a connection yet '''
        for interface in self.connectionManager.interfaces():
            self.connectionManager.interface(interface)
            if self.connectionManager.current() == None:
                print "I've just found one free antenna ready to be connected"
                if self.connectionManager.connect(ssid=wifiNetwork,
                                                  password="******"):
                    return self.connectionManager.interface(
                    ), self.connectionManager.current()
                else:
                    '''This could be possible if the network is not available '''
                    print "Network not available"
                    return False, False

        print "I haven't found a free antenna for your connection... sorry, ", wifiNetwork
        return False, False

    def closeBrain(self):
        for drone in self.drones:
            if self.drones[drone] is not None:
                print "closing connection with the vehicle of " + drone
                self.drones[drone].vehicle.close()
            self.drones[drone] = None
Пример #32
0
        s.fileno(),
        0x8915, # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
        )[20:24])

myLCD = lcd.Jhd1313m1(0, 0x3E, 0x62)

myLCD.setColor(0, 255, 0)

myLCD.setCursor(0, 0)

ip = getIP('wlan0')
    
wireless = Wireless()

ssid = wireless.current()

myLCD.write(ssid)

myLCD.setCursor(1,0)

myLCD.write(ip)

while True:
    if ip != getIP('wlan0'):
        myLCD.clear()
        myLCD.setCursor(0,0)
        ssid = wireless.current()
        myLCD.write(ssid)
        ip = getIP('wlan0')
        myLCD.setCursor(1, 0)
Пример #33
0
def get_current_access_point():
    w = Wireless()
    return w.current()
Пример #34
0
class ServerBrain:
    def __init__(self, socket=None):

        self.socket = socket

        self.dronesName = ["Solo Gold", "Solo Green"]
        self.wifiConnections = {
            'Solo Gold': ['SoloLink_gold', 'sololinkmst'],
            'Solo Green': ['SoloLink_MST', 'sololinkmst']
        }
        #used to switch connection
        self.conn = Wireless()
        #array of drones initializer
        self.drones = {
            'Solo Gold':
            drone.Drone('Solo Gold', self.wifiConnections['Solo Gold']),
            'Solo Green':
            drone.Drone('Solo Green', self.wifiConnections['Solo Green'])
        }

    def getDistanceMeters(firstLocation, secondLocation):
        latitude = float(secondLocation.lat) - float(firstLocation.lat)
        longitude = float(secondLocation.lon) - float(firstLocation.lon)
        return math.sqrt((latitude * latitude) +
                         (longitude * longitude)) * 1.113195e5

    def switchConnection(self, droneName):
        print "I'm going to switch WiFi connection, ", droneName
        return self.conn.connect(
            ssid=self.drones[droneName].wifiConnection[0],
            password=self.drones[droneName].wifiConnection[1])

    def connectDrone(self, droneName):

        if self.conn.current() != self.wifiConnections[droneName]:
            if self.switchConnection(droneName) == False:
                #self.conn.power(False) #this command sets off the WiFi antenna
                return droneName + " netwotk is not reacheble"

        self.drones[droneName].connect()
        location = self.drones[droneName].getActualLocation()

        return location

    def activateThread(self, functionName, name, listOfLocations):

        if functionName == "flight":
            eventlet.spawn(self.flight, listOfLocations, name)

    def arm(self, name):

        print "Arming... ", name
        self.switchConnection(name)
        self.drones[name].vehicle = connect('udpout:10.1.1.10:14560',
                                            wait_ready=True)

        print "Current WiFi network: ", self.conn.current()

        print "Vehicle of " + name + " is: ", self.drones[
            name].vehicle is not None

        print name + " is armable: ", self.drones[name].vehicle.is_armable
        while not self.drones[name].vehicle.is_armable:
            print "Waiting for vehicle to initialise..", name

        self.drones[name].vehicle.mode = VehicleMode("GUIDED")
        self.drones[name].vehicle.armed = True

        print name + " armed: ", self.drones[name].vehicle.armed
        while not self.drones[name].vehicle.armed:
            print "Waiting for arming ", name
            time.sleep(1)
        print "I finish the arm function execution and I'm ready to take off, ", name

    def flight(self, listOfLocations, name):
        print "I'm " + name + " and I'm inside flight function"

        self.arm(name)
        targetAltitude = 2
        self.drones[name].vehicle.simple_takeoff(targetAltitude)

        eventlet.sleep(5)

        while True:
            print "I'm trying to understand if I reach the target altitude ", name
            eventlet.sleep(3)
            self.switchConnection(name)
            message = {
                "reached":
                False,
                "altitude":
                self.drones[name].vehicle.location.global_relative_frame.alt,
                "name":
                name
            }
            if self.drones[
                    name].vehicle.location.global_relative_frame.alt >= targetAltitude * 0.95:
                message = {
                    "reached": True,
                    "altitude": targetAltitude,
                    "name": name
                }
                self.drones[name].vehicle.mode = VehicleMode('RTL')
            self.socket.emit('Altitude Reached', message)
            if message["reached"] == True:
                break

        eventlet.sleep(3)

        self.drones[name].buildListOfLocations(listOfLocations)

        for locationToReach in listOfLocations:
            eventlet.sleep(3)
            self.switchConnection(name)
            #self.drones[name].vehicle = connect('udpout:10.1.1.10:14560', wait_ready=True)
            print "Location to reach for " + name + " is ", locationToReach
            soloCurrentLocation = vehicle.location.global_relative_frame
            targetDistance = self.getDistanceMeters(soloCurrentLocation,
                                                    locationToReach)
            self.drones[name].vehicle.simple_goto(locationToReach)
            eventlet.sleep(2)
            while True:
                self.switchConnection(name)
                soloCurrentLocation = self.drones[
                    name].vehicle.global_relative_frame
                remainingDistance = self.getDistanceMeters(
                    soloCurrentLocation, targetDistance)
                socketio.emit(
                    'Update Live Location', {
                        "name": name,
                        "status": "flying",
                        "latitude": soloCurrentLocation.lat,
                        "longitude": soloCurrentLocation.lon,
                        "altitude": soloCurrentLocation.alt,
                    })
                if remainingDistance <= targetDistance * 0.05:
                    #here the code for taking picture
                    socketio.emit('Update Live Location', {
                        "name": name,
                        "status": "reached"
                    })
                    break
                eventlet.sleep(2)
        #self.drones[name].vehicle = connect('udpout:10.1.1.10:14560', wait_ready=True)
        self.drones[name].vehicle.mode = VehicleMode('RTL')
Пример #35
0
def is_connected_to_network():
    """Check to see if connected to WeyeFeye network with name like 'WeyeFeyeb17d8a'"""
    w = Wireless()
    network_name = w.current()
    connected = bool(network_name and "WeyeFeye" in network_name)
    return connected
Пример #36
0
def getNetworkInfo():
	global IP, ssid
	wireless = Wireless()
	ssid = wireless.current()
	p = subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
	IP, err = p.communicate()