Esempio n. 1
0
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()
Esempio n. 2
0
def get_wifi_devs():
    try:
        from wireless import Wireless
        w = Wireless()
        return w.interfaces()
    except:
        return []
Esempio n. 3
0
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..."
Esempio n. 4
0
    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}
Esempio n. 5
0
def getMyMac():
	try:
		wireless = Wireless()
		ifaces = wireless.interfaces()
		iface = ifaces[-1]
		mac = (netifaces.ifaddresses(iface)[netifaces.AF_LINK][0]['addr'])
		return mac
	except:
		print("Please manually select your interface using ifconfig or ipconfig using the -i flag")
		sys.exit(-1)
Esempio n. 6
0
 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
Esempio n. 7
0
 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)
Esempio n. 8
0
    def get_networks(self):
        wireless = Wireless()
        ifs = wireless.interfaces()
        if len(ifs) == 0:
            return []

        res = []
        for c in Cell.all(ifs[0]):
            res.append(c.ssid)

        return res
Esempio n. 9
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'
Esempio n. 10
0
File: 1.py Progetto: imkalyan/I-BOT
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]
Esempio n. 11
0
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
Esempio n. 12
0
def main():
    import argparse

    parser = argparse.ArgumentParser("A watcher for ping")
    parser.add_argument("--testing", action="store_true")

    args = parser.parse_args()

    logging.basicConfig(level=logging.DEBUG if args.testing else logging.INFO)
    client = ActivityWatchClient("aw-watcher-network", testing=args.testing)

    bucketname = "{}_{}".format(client.client_name, client.client_hostname)
    eventtype = "ping"
    client.create_bucket(bucketname, eventtype)
    logger.info("Starting to log ping")

    while True:
        t = datetime.utcnow()
        sleeptime = 60 - (t.second + t.microsecond / 1000000.0)
        sleep(sleeptime)
        timestamp = datetime.now(pytz.utc)
        wifiname = Wireless().current()
        try:
            out = ping(30)
            client.send_events(bucketname,
                               createEvents(out, timestamp, wifiname))
            logger.info("Sent events")

        except Exception as e:
            import sys, traceback
            traceback.print_exc()
            logger.error("Exception thrown while pinging {}".format(e))
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
Esempio n. 14
0
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)
Esempio n. 15
0
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")
Esempio n. 16
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
Esempio n. 17
0
class WirelessUser(models.Model):
    wifi = Wireless()
    name = models.CharField(max_length=50, default="Home")
    ssid = models.CharField(max_length=20)
    password = models.CharField(max_length=20)
    is_on = models.BooleanField(default=False)

    def __str__(self):
        return self.name

    def start_wifi_check(self):
        self.is_on = self.have_internet()
        return self.is_on

    def connectus(self):
        self.is_on = self.wifi.connect(ssid=self.ssid, password=self.password)
        print("First try...")
        if self.is_on == False:
            print("Second try...")
            self.is_on = self.wifi.connect(ssid=self.ssid,
                                           password=self.password)
        if self.is_on == True:
            print(self.ssid, self.password)
            print("run worker")
            #sleep(2)
            os.system('sudo supervisorctl start motherworker')
        self.save()
        return self.is_on

    def wifi_check(self):
        #print (self.wifi.current())
        #if self.wifi.current() == None:
        if self.have_internet() != True:
            if self.is_on == True:
                os.system('sudo supervisorctl stop motherworker')
                self.is_on = False
        else:
            if self.is_on == False:
                self.is_on = True
                os.system('sudo supervisorctl start motherworker')
        self.save()
        return self.is_on

    def have_internet(self):
        conn = httplib.HTTPConnection('www.google.com', timeout=5)
        try:
            conn.request("HEAD", "/")
            conn.close()
            print("We have true internet")
            return True
        except:
            conn.close()
            print("No internet connection!")
            return False

    def refresh_worker(self):
        os.system('sudo supervisorctl stop motherworker')
        os.system('sudo supervisorctl start motherworker')
        print("worker has been restarted!")
Esempio n. 18
0
    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'])
        }
Esempio n. 19
0
def connect_wifi(ssid: str, password: Optional[str] = None) -> bool:
    UTIL_LOGGER.debug(f"connecting to {ssid}")
    if sys.platform == 'linux':
        from wireless import Wireless
        return Wireless().connect(ssid=ssid, password=password)
    elif sys.platform == 'win32' or sys.platform == 'cygwin':
        import winwifi
        return winwifi.WinWiFi.connect(ssid)
    else:
        UTIL_LOGGER.error(f"Can't auto-connect to wifi on {sys.platform}")
        return False
Esempio n. 20
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
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)
Esempio n. 22
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
Esempio n. 23
0
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 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)
Esempio n. 25
0
    def __init__(self):
        self.disp = Display(Pin(DC), Pin(RES), Pin(CS), W, H, B)
        self.disp.show_progress('Start', 3)
        self.th = TempHumi(Pin(DHT))
        self.sgp = CO2TVOC(Pin(SCL), Pin(SDA))
        self.wireless = Wireless(WIFI_NAME, WIFI_PASSWORD)
        self.datetime = DateTime(self.wireless)
        self.logger = Logger(LOG_FILENAME)
        self.logger.write_startlog('\nSTART\n')
        self.pubcli = MQTT_CLI(self.wireless, MQTT_CLIENT_NAME, MQTT_SEVER_IP)

        self._count = 0
        self._boarder_state = True
Esempio n. 26
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
Esempio n. 27
0
    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 = []
Esempio n. 28
0
    def callback(self):
        if 'wifi_list' not in self.mongo_document:

            def blacklisted(iface):
                """
                    Checks if interface starts with
                        - smoothie
                        - mon
                """
                return iface.startswith('smoothie') or iface.startswith('mon')

            ifaces = [a for a in Wireless().interfaces() if not blacklisted(a)]

            self.update({'$set': {'wifi_list': ifaces}})
            self.stop()
Esempio n. 29
0
	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'])
		}
Esempio n. 30
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
Esempio n. 31
0
    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)
Esempio n. 32
0
def add_to_file(network_data):
        os.system("echo '"+str(network_data)+"' >> /home/pi/Desktop/networks.txt")

serialSocket = serial.Serial(      
        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")
Esempio n. 33
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"
Esempio n. 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')









		
Esempio n. 35
0
from wireless import Wireless
import wifi
import time
import socket
wifilist = []
wireless=Wireless()
interface=wireless.interface()
Zentri_ssid_string='ZentriOS'

def Search():
    cells = wifi.Cell.all(interface)

    for cell in cells:
        wifilist.append(cell)

    return wifilist


def FindFromSearchList(ssid):
    wifilist = Search()

    for cell in wifilist:
        if ssid in cell.ssid:
            return cell

    return False


def FindFromSavedList(ssid):
    cell = wifi.Scheme.find(interface, ssid)
Esempio n. 36
0
 def getSSID():
   from wireless import Wireless
   wireless = Wireless()
   return  wireless.current()
Esempio n. 37
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()
Esempio n. 38
0
import Adafruit_Nokia_LCD as LCD
import Adafruit_GPIO.SPI as SPI
import psutil
import math
import requests
import json


from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from subprocess import check_output
from gpiozero import CPUTemperature
from wireless import Wireless

wireless = Wireless()


# Raspberry Pi software SPI config:
SCLK = 17
DIN = 18
DC = 27
RST = 23
CS = 8

# Software SPI usage (defaults to bit-bang SPI interface):
disp = LCD.PCD8544(DC, RST, SCLK, DIN, CS)

# Initialize library.
disp.begin(contrast=100)
Esempio n. 39
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)
Esempio n. 40
0
reload(sys)
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:
Esempio n. 41
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)
Esempio n. 42
0
    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()
Esempio n. 43
0
def update_current_connection():
    global wifi, current
    wifi = Wireless()
    current = wifi.current()
Esempio n. 44
0
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read("/usr/local/mindsensors/conf/msdev.cfg")
homefolder = config.get("msdev", "homefolder")
currentdir = os.path.join(homefolder, "programs")

# Globals
config_file = "/etc/wpa_supplicant/wpa_supplicant.conf" # Config file for Wi-Fi
wifi = None
wlan_inteface = "wlan0"
psm = PiStorms_GRX()

# 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)
Esempio n. 45
0
File: ip.py Progetto: terrabite3/460
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        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)
Esempio n. 46
0
#Bullet Time!!! 90 degrees GIF

import time
import sys
import requests
import re
import urllib
import os

from wireless import Wireless

#Iniciando la clase para conexion con camaras
wifi = Wireless('wlan0')

#Lista con ssid de camaras
cameras = ['Bullet_5', 'Bullet_6']

#Funcion para descargar las ultimas 10 imagenes de la camara seleccionada

def getImages(cam):
	
	image = urllib.URLopener()
	
	#Variable con la direccion donde se encuentran las fotos
	adress = "http://10.5.5.9/videos/DCIM/100GOPRO/"
	
	#Descargando toda la informacion desplegada en el url
	r = requests.get(adress)
	
	#Variable con caracteres que forman parte del nombre de las imagenes
	expression = r'"(\w+.JPG)"'
Esempio n. 47
0
from wireless import Wireless

# Enter the password for your gopro and make sure you are connected to the wifi network
PASSWORD = ""
GOPRO_NETWORK = "as-gopro"
UPLOAD_NETWORK = "Nifi"
SLEEP_TIME = 360
MAX_ERRORS = 10
LOCAL_DIR = "/Users/andrew/Pictures/"

CAMERA_ON = "http://10.5.5.9/bacpac/PW?t={}&p=%01"
DELETE_LAST_PHOTO = "http://10.5.5.9/camera/DL?t={}"
CAMERA_PHOTO_MODE_ON = "http://10.5.5.9/camera/CM?t={}&p=%01"
CAMERA_RESOLUTION_MEDIUM = "http://10.5.5.9/camera/PR?t={}&p=%06"

wireless = Wireless()

error_count = 0


def run_command(url):
    global error_count
    try:
        resp = requests.get(url.format(PASSWORD))
        if resp.status_code != 200:
            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
Esempio n. 48
0
from wireless import Wireless
import random

wireless = Wireless()
name = input("enter the name of network(ssid)")

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:
Esempio n. 49
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))
Esempio n. 50
0
from wireless import Wireless

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

# python3 -m pip install wireless
#only MAC
Esempio n. 51
0
	if (internet_off()):
		os.system("echo \"$(date '+%Y/%M/%D %H:%M:%S')-> Red: Iniciando daemon bluetooth\" >> /home/pi/Desktop/log.txt")
		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
				
Esempio n. 52
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
Esempio n. 53
0
 def __init__(self, ssid, password):
     self.ssid = ssid
     self.password = password
     self.wireless = Wireless()
     self.system = platform.system()
Esempio n. 54
0
        self.status = "Off"
        print "Apagar"
        return


# Hacemos las asignaciones de los pines fisicos
pin_rele = 25

# Establecemos el valor del TOKEN facilitado por The BotFather
TOKEN = "289317488:AAEpHlZCmDrndtD_zxbFp1YVkQXuDgZ9zFc"

# Creamos una instancia tipo rele para el enchufe
plug = rele(pin_rele)

# Creamos objeto para manejar estado de la conexion
wifi = Wireless()

# Creamos conexion con bot de telegram
bot = telebot.TeleBot(TOKEN)

# Definimos identificadores de usuarios
cesar_id = 9519882


# Definimos funcion para comprobar la identidad de los usuarios
def check_security(message):
    print message.chat.username
    print message.from_user.id
    print message.chat.id
    if message.chat.type == "group":
        return True
Esempio n. 55
0
    def __init__(self):
        self.network = Wireless()
        self.networkLock = threading.Lock()

        self.defaultNetwork = config.getDefaultNetwork()