def advertise_service(self,name = 'bluetooth_server'):
     bluetooth.advertise_service(self.socket, name,
                       service_id=self.uuid,
                       service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                       profiles=[bluetooth.SERIAL_PORT_PROFILE],
                       #                   protocols = [ OBEX_UUID ]
                       )
Example #2
0
    def handle_disconnection(self, serversocket, condition):
        """
        Handles the shutdown of connections. When the serversocket signals the
        HUP condition.  The handler disconnects from the mainloop by returning
        false.

        This method is called when the connection was shutdown from the
        otherside of the connection. The data handler (L{handle_incoming_data})
        for incoming data is disconnected and the disconnect signal is fired. 
        
        If we are in connectable or filtered mode, we will reattach the
        serversocket watch for gtk.IO_IN with L{handle_connection}) as handler.

        @type   self:           BTServer
        @param  self:           The BTServer object responsible for handling the connection
        @type   serversocket:   bluetooth.BluetoothSocket
        @param  serversocket:   A bluetooth socket responsible for handling incoming connections (server side)
        @type   condition:      integer (gobject.Enum)
        @param  condition:      The condition of the serversocket which caused the handler to be called
                                should always be gobject.IO_HUP (=16)
        @rtype:         bool
        @return:        always False, as we only allow one concurrent connection
        """
        gobject.source_remove(self.client_io_watch)
        self.server_io_watch = None
        self.client_io_watch = None
        self.client_sock = None
        self.emit("disconnect", self.connected[0], self.connected[1])
        self.connected = None
        if self.connectable == 'yes' or self.connectable == 'filtered':
            self.server_io_watch = gobject.io_add_watch(self.server_sock, gobject.IO_IN, self.handle_connection)
            bluetooth.advertise_service(self.server_sock, self.name, self.serverid)
        return False
Example #3
0
def runServer():
	serverSocket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
	port = bluetooth.PORT_ANY
	serverSocket.bind(("", port))
	print "Listening for connections on port: ", port   
	serverSocket.listen(1)
	port=serverSocket.getsockname()[1]

    #the missing piece
	bluetooth.advertise_service( serverSocket, "SampleServer",
					   service_id = uuid,
					   service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
					   profiles = [ bluetooth.SERIAL_PORT_PROFILE ] 
						)

	inputSocket, address=serverSocket.accept()
	print "Got connection with" , address

	last_data = 0.0
	while True:
		data = inputSocket.recv(5)
		if float(data) > 1.29:
			k.tap_key("a")
		elif float(data) < -1.29:
			k.tap_key("d")


		print "received [%s] \n " % data

	inputSocket.close()
	serverSocket.close()  
Example #4
0
 def __init__(self,uuid):
     """
         Permet de créer un socket serveur
     """
     try:
         # initialise un socket RFCOMM
         bluetooth.BluetoothSocket.__init__( self, bluetooth.RFCOMM )
         # applique le socket sur le premier adaptateur trouvé,
         # et le premier port libre
         self.bind( ("",bluetooth.PORT_ANY) )
         # commence l'écoute sur le port, avec une connection
         # en file d'attente au maximum
         self.listen(1)
         # averti le serveur SDP de la présence du serveur
         bluetooth.advertise_service( self, "Paquet",uuid,[uuid])
         #variable interne
         self.creationReussie = True
     except OSError:
         #erreur dûe à pybluez (pas très descriptive...)
         #variable interne
         self.creationReussie = False
         #defini une valeure bidon d'addresse de serveur
         self.getsockname = lambda: ("XX:XX:XX:XX:XX:XX",0)
         #variable interne
         self.actif = True
         return
     #initialise la liste des connections
     self.connections = []
     #variable interne
     self.actif = True
Example #5
0
def advertise(servicename, sock, serviceclass):
    try:
        if serviceclass == _lightbluecommon.RFCOMM:
            bluetooth.advertise_service(sock._sock,
                                servicename,
                                service_classes=[bluetooth.SERIAL_PORT_CLASS],
                                profiles=[bluetooth.SERIAL_PORT_PROFILE])
        elif serviceclass == _lightbluecommon.OBEX:
            # for pybluez, socket do need to be listening in order to
            # advertise a service, so we'll call listen() here. This should be
            # safe since user shouldn't have called listen() already, because
            # obex.recvfile() docs state that an obex server socket should
            # *not* be listening before recvfile() is called (due to Series60's
            # particular implementation)
            if not sock._listening:
                sock.listen(1)

            # advertise Object Push Profile not File Transfer Profile because
            # obex.recvfile() implementations run OBEX servers which only
            # advertise Object Push operations
            bluetooth.advertise_service(sock._sock,
                                servicename,
                                service_classes=[bluetooth.OBEX_OBJPUSH_CLASS],
                                profiles=[bluetooth.OBEX_OBJPUSH_PROFILE],
                                protocols=["0008"])     # OBEX protocol
        else:
            raise ValueError("Unknown serviceclass, " + \
                "should be either RFCOMM or OBEX constants")
        # set flag
        sock._advertised = True
    except bluetooth.BluetoothError, e:
        raise _lightbluecommon.BluetoothError(str(e))
Example #6
0
 def __init__(self,addOrigine,serviceInfo):
     """
         crée le tunnel sur le service de "addOrigine"
     """
     #récupère les infos
     self.origine = addOrigine
     
     if serviceInfo["protocol"] == "RFCOMM":
         self.protocole = bluetooth.RFCOMM
     elif serviceInfo["protocol"] == "L2CAP":
         self.protocole = bluetooth.L2CAP
     
     self.port = serviceInfo["port"]
     
     #crée un service correspondant
     bluetooth.BluetoothSocket.__init__(self, self.protocole)
     try:
         self.bind( ("",bluetooth.PORT_ANY) )
     except OSError:
         print("[retransmission de "+self.origine+"] impossible")
         return
     
     #fais de la pub
     bluetooth.advertise_service(self,serviceInfo["name"],
                                      serviceInfo["service-id"],
                                      serviceInfo["service-classes"],
                                      serviceInfo["profiles"])
Example #7
0
    def try_connect(self):

        try:
            self.server_sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )

            err = self.server_sock.bind(("", bluetooth.PORT_ANY))
            err = self.server_sock.listen(1)
            self.port = self.server_sock.getsockname()[1]

            # advertise our service
            bluetooth.advertise_service( self.server_sock, "Freevused",
                                  service_classes = [ bluetooth.SERIAL_PORT_CLASS ],
                                  profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )

            logger.debug("Waiting for connection on RFCOMM channel %d", self.port)

            self.tx, self.address = self.server_sock.accept()

            logger.debug("Accepted connection")

            self.connected = True

            self.tx_dispatcher.register(self.tx.fileno(), kaa.IO_READ)


        except bluetooth.BluetoothError, e:
            self.connected = False
            logger.debug("broken tooth (try_connect): %s", str(e))

            if self.server_sock:
                self.server_sock.close()

            self.server_sock = None
Example #8
0
 def run(self):
     log.info("btserver running")
     while self.running:
         self.server_sock = None
         try:
             self.server_sock = bt.BluetoothSocket(bt.RFCOMM)
             self.server_sock.setblocking(0)
             self.server_sock.bind(("", self.channel))
             self.server_sock.listen(1)
             
             bt.advertise_service(self.server_sock, config.PNAME,
                       service_classes = [bt.SERIAL_PORT_CLASS],
                       profiles = [bt.SERIAL_PORT_PROFILE])
             
             log.info("Waiting for connections on RFCOMM channel [{}]".format(self.server_sock.getsockname()[1]))
             while self.running:
                 readable, _, _ = select.select([self.server_sock], [], [], 0.1)
                 for s in readable:
                     if s is self.server_sock:
                         client_sock, client_info = self.server_sock.accept()
                         log.info("Accepted connection from: " + str(client_info))
                         client_sock.setblocking(1)
                         client_sock.settimeout(self.timeout)
             
                         if self.running:
                             conn = Connection(client_sock, self)
                             conn.start()
         except:
             if self.running:
                 log.exception("Error while listening for connections")
                 time.sleep(1.0)
         finally:
             self.close()
    def wait_for_connections(self):
        self.video_socket.listen(1)
        self.control_socket.listen(1)
        video_port = self.video_socket.getsockname()[1]
        control_port = self.control_socket.getsockname()[1]
        
        self.video_conn = None
        self.control_conn = None

        print "Listening on bluetooth."
        print "Video channel: %s" % (video_port,)
        print "Control channel: %s" % (control_port,)
        
        try:
            bluetooth.advertise_service(self.video_socket, "BotDriverVideo")
        except bluetooth.btcommon.BluetoothError:
            print ("Failed to advertise service. "
                   "Is the Bluetooth daemon running?")

        # We'll go ahead and wait for connections using select() so we can
        # accept connections in any order.
        available_sockets = [self.video_socket, self.control_socket]
        while self.video_conn == None or self.control_conn == None:
            rlist, wlist, xlist = select.select(
                available_sockets, [], [])
            for sock in rlist:
                if sock == self.video_socket:
                    self.video_conn, address = sock.accept()
                    sock.close()
                    print "Accepted connection from %s." % (address,)
                elif sock == self.control_socket:
                    self.control_conn, address = sock.accept()
                    sock.close()
                    print "Accepted connection from %s." % (address,)
                available_sockets.remove(sock)
Example #10
0
def hostServer(mac,port):
	backlog = 1
	size = 1024
	sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
	sock.bind(("",port))
	sock.listen(backlog)
	bluetooth.advertise_service(sock,'spartacus',description = mac)
	s = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
	s.bind((mac,port))
	s.listen(backlog)
	while True:
		try:
			client, address = s.accept()
			data = client.recv(size)
			if data:
				print(data)
				client.send(data)
		except Exception:
			print("Closing socket")	
			break
	try:
		client.close()
	except Exception:
		pass
	s.close()
	sock.close()
Example #11
0
def createConnection ():
    print ("Tratando de establecer conexion bluetooth")
    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    port = bluetooth.PORT_ANY
    server_sock.bind(("",port))
    server_sock.listen(1)
    bluetooth.advertise_service(server_sock,"",service_classes=[bluetooth.SERIAL_PORT_CLASS],profiles=[bluetooth.SERIAL_PORT_PROFILE])
    client_sock, address = server_sock.accept()
    print ("Conexion satisfactoria",address)
    ser = serial.Serial('COM7', 9600)
    try:
        while(True):
            sensor = ser.readline()
            data = client_sock.recv(1024)
            if sensor=="1":
                room = 1
                client_sock.send('1')
                sendEmail(room)
                
            if sensor=="2":
                room = 2
                client_sock.send('2')
                sendEmail(room)
            if sensor=="2":
                room = 3
                client_sock.send('3')
                sendEmail(room)
            if sensor=="0":
                break

        print ("#conexion terminada")
    except:
        ser.close()
	def connect(self, _localMACAddress):
		self.localMACAddress = _localMACAddress
		try:
			# Creamos un nuevo socket Bluetooth que usa el protocolo de transporte especificado
			self.serverSocketRFCOMM = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
			# Enlazamos al adaptador local algun puerto disponible
			self.serverSocketRFCOMM.bind((self.localMACAddress, bluetooth.PORT_ANY))
			# Especificamos el numero de conexiones permitidas (todavia sin aceptar) antes de rechazar las nuevas entrantes
			self.serverSocketRFCOMM.listen(CONNECTIONS)
			# Especificamos el tiempo de espera de conexiones (funcion 'accept')
			self.serverSocketRFCOMM.settimeout(TIMEOUT)
			# Utilizamos SDP para anunciar nuestro servicio
			bluetooth.advertise_service(self.serverSocketRFCOMM, self.localServiceName,
										service_id = self.localUUID,
										service_classes = [self.localUUID, bluetooth.SERIAL_PORT_CLASS],
										profiles = [bluetooth.SERIAL_PORT_PROFILE])
			# Almacenamos el puerto asignado por el 'bind'
			self.localPortRFCOMM = self.serverSocketRFCOMM.getsockname()[1]
			#######################################################################
			self.bluetoothTransmitter = bluetoothTransmitter.BluetoothTransmitter()
			#######################################################################
			self.successfulConnection = True
			return True
		except bluetooth._bluetooth.error as bluetoothError:
			logger.write('ERROR', '[BLUETOOTH] Código de error %s - %s.' % (bluetoothError[0], bluetoothError[1]))
			self.successfulConnection = False
			return False
Example #13
0
def simpleSPPServer(name, clientHandler):
    """Main loop for a simple single-connection Serial Port Profile server.
       This advertises an SPP service, and waits for clients to connect.
       When a client connects, clientHandler(socket) is invoked.
       Exceptions are logged, and cause the connection to terminate.
       """
    socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    socket.bind(('', bluetooth.PORT_ANY))
    socket.listen(1)

    bluetooth.advertise_service(socket, name,
                                service_classes = [bluetooth.SERIAL_PORT_CLASS],
                                profiles = [bluetooth.SERIAL_PORT_PROFILE])

    while True:
        logger.log("Listening for clients on RFCOMM channel %d" % socket.getsockname()[1])
        clientSocket, clientInfo = socket.accept()
        logger.log("Client %s connected" % clientInfo[0])
        try:
            clientHandler(clientSocket)
        except KeyboardInterrupt:
            pass
        except Exception, e:
            logger.log("*** Unhandled exception\n%s" % traceback.format_exc().strip())
        clientSocket.close()
    def listen_for_rfcomm_connection(self):
        """
        Starts bluetooth interfaces
        """
        # prepare bluetooth server
        self.server_sock = BluetoothSocket(RFCOMM)
        self.server_sock.bind(("", PORT_ANY))
        self.server_sock.listen(1)
        self.rfcomm_channel = self.server_sock.getsockname()[1]

        # start listening for incoming connections
        try:
            advertise_service(
                sock=self.server_sock,
                name=self.service_name,
                service_id=self.service_uuid,
                service_classes=[self.service_uuid, SERIAL_PORT_CLASS],
                profiles=[SERIAL_PORT_PROFILE]
            )
        except:
            LOGGER.exception("[ERROR] failed to advertise service")
            return

        LOGGER.info('waiting for connection on RFCOMM channel %d', self.rfcomm_channel)

        # accept received connection
        self.client_sock, self.client_info = self.server_sock.accept()
        self.state = self.__states__.STATE_CONNECTED
        LOGGER.info('accepted connection from %r', self.client_info)

        # start listening for data
        self.consume_bus()
def main_server():
    server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    #port = bluetooth.get_available_port(bluetooth.RFCOMM)
    server_sock.bind(("",0))
    server_sock.listen(1)
    port = server_sock.getsockname()[1]
    print "listening on port %d" % port
    uuid = "00001101-0000-1000-8000-00805F9B34FB"
    bluetooth.advertise_service( server_sock, "Copy-Sync-Paste", service_id=uuid )
    client_sock,address = server_sock.accept()
    print "Accepted connection from ",address
    clip_text = ""
    while True:
        try:
            text = client_sock.recv(1024)
            if len(text)!=0:
                clip_text=clip_text + text
            else:
                break
        except Exception as e:
            pass
            break
    print clip_text
    bluetooth.stop_advertising(server_sock)
    server_sock.close()
    client_sock.close()
    setClipBoardContents(clip_text)
    print getClipBoardContents()
    print "Done."
Example #16
0
def runServer():
	serverSocket=bluetooth.BluetoothSocket(bluetooth.RFCOMM)
	port=bluetooth.PORT_ANY
	serverSocket.bind(("",port))
	print "Listening for connections on port: ", port   
	serverSocket.listen(1)
	port=serverSocket.getsockname()[1]

	#the missing piece
	bluetooth.advertise_service( serverSocket, "SampleServer",
					   service_id = uuid,
					   service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
					   profiles = [ bluetooth.SERIAL_PORT_PROFILE ] 
						)

	inputSocket, address=serverSocket.accept()
	print "Got connection with" , address

	while 1:
		data = inputSocket.recv(1024)
		print "Received: %s" % data
		if (data == "0"):    #if '0' is sent from the Android App, turn OFF the LED
			print "0 is pressed"

		if (data == "1"):    #if '1' is sent from the Android App, turn OFF the LED
			print "1 is pressed" 
	 
		if (data == "q"):
			print "Quit"
			break
		
	inputSocket.close()
	serverSocket.close()  
Example #17
0
	def bind(self):
		AuthenticatedTransport.bind(self)
		self._adapter.SetProperty('Discoverable', self._address is None, signature='sv')
		self._serverSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
		self._serverSocket.bind(('', bluetooth.PORT_ANY))
		self._serverSocket.listen(self['socketConnectionBacklog'])
		bluetooth.advertise_service(self._serverSocket, 'kozo', service_id=self._uuid, service_classes=[self._uuid, bluetooth.SERIAL_PORT_CLASS], profiles=[bluetooth.SERIAL_PORT_PROFILE])
		infoTransport(self, 'Bound on port', self._serverSocket.getsockname()[1], 'with UUID', self._uuid)
 def __init__(self, storage_queue):
     global server_port, server_uuid, android_queue
     android_queue = storage_queue
     self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
     self.server_sock.bind(("", server_port))
     self.server_sock.listen(1)
     bluetooth.advertise_service(self.server_sock, "MDP Group 7 RPi", server_uuid)
     print "[BluetoothAPI] Accepting bluetooth connection on Port %s..." % server_port
Example #19
0
File: bt.py Project: 0xheart0/xbmc
def bt_advertise(name, uuid, socket):
    if BLUEZ:
        bluetooth.advertise_service( socket, name,
                           service_id = uuid,
                           service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
                           profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )
    else:
        lightblue.advertise(name, socket, lightblue.RFCOMM)
Example #20
0
 def __switch_connectable(self):
     if (self.connectable == 'yes' or self.connectable == 'filtered') and not self.server_io_watch:
         self.server_io_watch = gobject.io_add_watch(self.server_sock, gobject.IO_IN, self.handle_connection)
         bluetooth.advertise_service(self.server_sock, self.name, self.serverid)
     elif self.connectable == 'no' and not self.connected:
         bluetooth.stop_advertising(self.server_sock)
         gobject.source_remove(self.server_io_watch)
         self.server_io_watch = None
     self.emit('connectable_event', self.connectable)
    def run(self):

        if self.jr.communication_style == "WIFI":

            while 1:

                success, d = self.jr.camera_driving_socket.receiveData()
                if success:
                    self.updateValues(success,d[0].split('/'))
                else:
                    self.updateValues(success, None)

        else:

            bluetooth.advertise_service(self.jr.camera_driving_socket, "jr_camera_driving_service",
                                        service_id=self.jr.CAMERA_DRIVING_SERVICE_UUID,
                                        service_classes=[self.jr.CAMERA_DRIVING_SERVICE_UUID, bluetooth.SERIAL_PORT_CLASS],
                                        profiles=[bluetooth.SERIAL_PORT_PROFILE],
                                        #                   protocols = [ OBEX_UUID ]
                                        )

            try:
                [addr, port] = self.jr.camera_driving_socket.getsockname()
                print "Advertising CAMERA DRIVING service on address" + str(addr) + " and port: " + str(port)
                self.jr.camera_driving_socket_client_sock, self.jr.camera_driving_socket_client_sock_info = self.jr.camera_driving_socket.accept()
                print "Connection established for CAMERA DRIVING service, acceptd from", self.jr.camera_driving_socket_client_sock_info
            except IOError:
                print "IOError in driving accepting connection"

            timeout = 0.05
            self.jr.camera_driving_socket_client_sock.settimeout(timeout)
            while True:
                try:
                    d = self.jr.camera_driving_socket_client_sock.recv(1024)
                    self.jr.camera_driving_socket_client_sock.send("received")
                    if len(d) > 0:
                        self.updateValues(True, d.split('/'))
                    else:
                        print "wrong command sent to DRIVING service"
                except IOError, e:
                    if str(e) == "timed out":
                        self.updateValues(False, None)
                    else:

                        print "CAMERA DRIVING connection lost with: ", self.jr.driving_socket_client_sock_info
                        print "Error number:", e.errno
                        print "Error:", e

                        connected = False
                        while not connected:
                            try:
                                self.jr.camera_driving_socket_client_sock, self.jr.camera_driving_socket_client_info = self.jr.camera_driving_socket.accept()
                                self.jr.camera_driving_socket_client_sock.settimeout(timeout)
                                print "Connection established for DRIVING service, acceptd from", self.jr.camera_driving_socket_client_info
                                connected = True
                            except IOError:
                                print "IOError in driving accepting connection"
Example #22
0
    def start_rfcomm_server(event):
        """Starts a threaded RFCOMM server, which keeps listening
            to incoming data."""
        global client_sock, self_sock, abort_connection, connection_active
        if sys.platform == 'linux':
            # saves users the horrible pain of making their device discoverable
            code = subprocess.call(['sudo', 'hciconfig', 'hci0', 'piscan'])
            if not code:
                print("enabled bluetooth")
            else:
                print("failed to enable bluetooth")
        connection_active = True
        self_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        port = 0
        data_size = 1024
        self_sock.bind(("", port))
        self_sock.listen(1)

        uuid = "bcfa2015-0e37-429b-8907-5b434f9b9093"
        bt_service_name = "PiWatch Android Connection Service"
        bluetooth.advertise_service(self_sock, bt_service_name,
                                    service_id=uuid,
                                    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                                    profiles=[bluetooth.SERIAL_PORT_PROFILE])
        print("Advertising bt service: ", bt_service_name)

        try:
            global client_address
            client_sock, client_address = self_sock.accept()
        except OSError:
            if abort_connection:
                print('bt connection aborted')
                service.eventqueue.add(Event('bt connection aborted'))
            else:
                print('bt connection failed')
                service.eventqueue.add(Event('bt connection failed'))
            bt_clean_up()
        except:
            print('bt connection failed')
            service.eventqueue.add(Event('bt connection failed'))
            bt_clean_up()
        else:
            print("Accepted connection from ", client_address[0])
            service.eventqueue.add(Event('bt connection active', data=bluetooth.lookup_name(client_address[0])))
            try:
                client_sock.send("Hey There!")
                while True:
                    print(abort_connection)
                    data = client_sock.recv(data_size)
                    if data:
                        service.eventqueue.add(Event('bt data received', data=data))
                        print("Received bluetooth data: " + str(data))
            except:
                pass
            finally:
                bt_clean_up()
                service.eventqueue.add(Event('bt connection aborted'))
Example #23
0
def make_socket():
    s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

    s.bind(("", bluetooth.PORT_ANY))
    s.listen(1)

    bluetooth.advertise_service(s, SERVICE_NAME, '', service_classes=[bluetooth.SERIAL_PORT_CLASS], profiles=[bluetooth.SERIAL_PORT_PROFILE])

    return s
Example #24
0
    def __init__(self):
        threading.Thread.__init__(self)
        self.running = True
        self.server_sock = bt.BluetoothSocket(bt.RFCOMM)
        self.server_sock.bind(('', bt.PORT_ANY))
        self.server_sock.listen(1)

        self.sock = None

        bt.advertise_service(self.server_sock, "RemoteAlarm", server_uuid)
def server():
    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    server_sock.bind(("", 0))
    server_sock.listen(1)
    print "Listening on port 0"
    
    bluetooth.advertise_service(server_sock, "DroidPad Service", UUID)
    client_sock,address = server_sock.accept()
    print "Accepted connection from ", address
    
    return client_sock
Example #26
0
    def start(self):
        try:
            self.server_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
            self.server_socket.bind(("", bluetooth.PORT_ANY))
            self.server_socket.listen(1)
            self.server_socket.settimeout(5)
            bluetooth.advertise_service(self.server_socket, "pyTwinkle", service_classes = [ bluetooth.SERIAL_PORT_CLASS ], profiles = [ bluetooth.SERIAL_PORT_PROFILE ] )
	    super(self.__class__, self).start()
        except:
            print >>sys.stderr, "Could not start a bluetooth server."
            sys.stdout.flush()
Example #27
0
 def __init__(self):
   self._server_socket = s = bt.BluetoothSocket(bt.RFCOMM)
   s.bind(("",bt.PORT_ANY))
   s.listen(5)
   self._port = s.getsockname()[1]
   D("Advertising service %s" % SERVICE)
   bt.advertise_service(s,SERVICE,
     service_id = UUID,
     service_classes = [UUID, bt.SERIAL_PORT_CLASS],
     profiles = [bt.SERIAL_PORT_PROFILE]
     )
Example #28
0
	def start(self):
		assert self._socket is None and self._incomingId is None
		self._socket = bluetooth.BluetoothSocket(self._protocol["transport"])
		self._socket.settimeout(self._timeout)
		self._socket.bind(("", bluetooth.PORT_ANY))
		self._socket.listen(1)
		self._incomingId = gobject.io_add_watch(
			self._socket, gobject.IO_IN, self._on_incoming
		)

		bluetooth.advertise_service(self._socket, self._protocol["name"], self._protocol["uuid"])
		self.emit("start_listening")
    def waitRequisition(self):
        """Método que aguarda a requisição do cliente bluetooth
        """
        self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
        self.server_sock.bind(("", 3))

        self.server_sock.listen(1)
        bluetooth.advertise_service(self.server_sock, self.name, self.uuid)

        print ("Waiting for connection on RFCOMM")
        self.client_sock, self.client_info = self.server_sock.accept()
        print (self.client_info, ": connection accepted")
Example #30
0
    def handle_connection(self, serversocket, condition):
        """
        Handles incoming connections. The handler disconnects from the mainloop
        by returning false. 
        
        The function checks whether we are in connectable or filtered mode.
        
        If we are in connectable mode or the remote device is allowed to
        connect, when in filter mode, a client connection is established, the
        corresponding signal is fired, the disconnect handler
        (L{handle_disconnection}) coupled to the serversocket and the client
        handler coupled to the client socket (L{handle_incoming_data}).

        When we are in not-connectable mode or the device is not allowed to
        connect in filtered mode, we close the client socket. If we are in
        filtered mode we reattach this  watch to the mainloop and advertise our
        socket.

        @type   self:           BTServer
        @param  self:           The BTServer object responsible for handling the connection
        @type   serversocket:   bluetooth.BluetoothSocket
        @param  serversocket:   A bluetooth socket responsible for handling incoming connections
        @type   condition:      integer (gobject.Enum)
        @param  condition:      The condition of the serversocket which caused the handler to be called
                                should always be gobject.IO_IN (=1)
        @rtype:         bool
        @return:        always False, as we only allow one concurrent connection
        """
        bluetooth.stop_advertising(self.server_sock)

        self.client_sock,client_address = self.server_sock.accept()        
        logging.debug("Serversocket: " + str(self.server_sock.getsockname()))

        if ( self._check_pairing(client_address) and
            (self.connectable == 'yes' or 
            (self.connectable == 'filtered' and client_address[0] in self.filter))):

            self.connected = client_address
            self.emit("connect", client_address[0], client_address[1])

            self.bluetooth_connection = BTConnection(self.client_sock)
            self.bluetooth_keycode = self.bluetooth_connection.connect(
                                                   "keycode", lambda btc, mp, kc: self.emit("keycode", mp, kc))
            
            self.server_io_watch = gobject.io_add_watch(self.client_sock, gobject.IO_HUP, self.handle_disconnection)
        else:
            logging.debug("BTServer: Closing remote connection")
            self.client_sock.close()
            self.client_sock = None
            if self.connectable == 'filtered':
                self.server_io_watch = gobject.io_add_watch(self.server_sock, gobject.IO_IN, self.handle_connection)
                bluetooth.advertise_service(self.server_sock, self.name, self.serverid)
        return False
lcd = Adafruit_CharLCD()
lcd.begin(16, 1)
buzzer = Buzzer(17)

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 1
server_socket.bind(("", port))
server_socket.listen(1)
uuid = "94f39d29-7d6d-497d-973b-fba39e49d4ee"
bluetooth.advertise_service(
    server_socket,
    "samepleServer",
    service_id=uuid,
    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
    profiles=[bluetooth.SERIAL_PORT_PROFILE],
)

realTime_Hour = ""
realTime_Minute = ""
str_hour = ""
str_minute = ""
alarmFlag = 1

getCurrentTime.TaskCurrentTime()


def alarm_On():
    print('Alarm on')
Example #32
0
#!/usr/bin/env python3
"""PyBluez ble example beacon.py
Advertises a bluethooth low energy beacon for 15 seconds.
"""
import time

import bluetooth

sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
bluetooth.advertise_service(sock, 'Location Hub', description='garage')

while True:
    pass

Example #33
0
import bluetooth
import os

server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "93fd0c34-5cf0-4c07-8b12-06fcc82e17f0"

bluetooth.advertise_service(server_sock, "Lno", service_id=uuid)

print("Waiting for connection on RFCOMM channel", port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if not data:
            print("not data")
            break
        if data == b'record':
            os.system("echo Record start")
        elif data == b'stop':
            os.system("echo Record stop")

        print(data)
except OSError:
import configparser as ConfigParser

import pdb

import wifiScript as w 
import dioScript as d

server_sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )

port = 0
server_sock.bind(("",port))
server_sock.listen(1)
print("listening on port %d" % port)

uuid = "00001101-0000-1000-8000-00805F9B34FB"
bluetooth.advertise_service( server_sock, "Inspirado Service", uuid )

app_key = "1mqt8n70964mn8n"
app_secret = "3p9t99oz4i9cgg3"

"""
Network Objects:
ID                  [int]
SSID                [string]
SecurityType        [string]
ServiceKey          [string] <- specific to conmanctl
ConnectionStatus    [string]
"""

def handleCommand(cmd, parameters = ""):
    # Switch for handling various commands with associated parameters
Example #35
0
    while (buzz > 0):
        if buzz > 0:
            print("xd")
            GPIO.setmode(GPIO.BCM)
            GPIO.output(buzzerPin, GPIO.HIGH)
            sleep(length)
            GPIO.output(buzzerPin, GPIO.LOW)
            sleep(length)
            buzz = buzz - 1
        else:
            break


#enabledAlert(0.1, 3)
bluetooth.advertise_service(server_socket,
                            "SampleServer",
                            service_classes=[bluetooth.SERIAL_PORT_CLASS],
                            profiles=[bluetooth.SERIAL_PORT_PROFILE])
print("Bluetooth device Is connected!2")

client_socket, address = server_socket.accept()
print("Bluetooth device Is connected!3")
#server_socket.send('\x1a')
print("Bluetooth device Is connected!4")
#enabledAlert(0.2, 2)


def return_data():
    try:
        while True:
            data = client_socket.recv(1024)
            if not data:
Example #36
0
    def __init__(self, hardware, parameters, parent):
        QtCore.QThread.__init__(self, parent)
        halModule.HalModule.__init__(self)

        self.click_step = 1.0
        self.click_timer = QtCore.QTimer(self)
        self.click_x = 0.0
        self.click_y = 0.0
        self.client_sock = False
        self.connected = False
        self.default_image = QtGui.QImage("bt_image.png")
        self.drag_gain = 1.0
        self.drag_multiplier = 100.0
        self.drag_x = 0.0
        self.drag_y = 0.0
        self.filming = False
        self.image_is_new = True
        self.images_sent = 0
        self.is_down = False
        self.is_drag = False
        self.lock_jump_size = 0.025
        self.messages = []
        self.mutex = QtCore.QMutex()
        self.send_pictures = hardware.send_pictures
        self.show_camera = True
        self.start_time = 0
        self.which_camera = "camera1"

        # Set current image to default.
        self.current_image = self.default_image

        # Setup bluetooth socket.
        have_bluetooth = True
        try:
            self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            self.server_sock.bind(("", bluetooth.PORT_ANY))
            self.server_sock.listen(1)

            port = self.server_sock.getsockname()[1]
            hdebug.logText(
                "Bluetooth: Listening on RFCOMM channel {0:d}".format(port))

            uuid = "3e1f9ea8-9c11-11e3-b248-425861b86ab6"

            bluetooth.advertise_service(
                self.server_sock,
                "halServer",
                service_id=uuid,
                service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                profiles=[bluetooth.SERIAL_PORT_PROFILE],
            )
        except:
            print traceback.format_exc()
            hdebug.logText("Failed to start Bluetooth")
            have_bluetooth = False

        if have_bluetooth:

            # Setup timer.
            self.click_timer.setInterval(200)
            self.click_timer.timeout.connect(self.handleClickTimer)
            self.click_timer.setSingleShot(True)

            # Connect signals.
            self.newData.connect(self.handleNewData)

            self.start(QtCore.QThread.NormalPriority)
Example #37
0
def main():
    #ctx = SSL.Context(SSL.TLSv1_METHOD)
    #server_sock = SSL.Connection(ctx, bluetooth.BluetoothSocket(bluetooth.RFCOMM))
    #server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

    tanCounter = 0
    aid = "2"
    port = 19
    server_sock.bind(("", port))
    server_sock.listen(5)
    i = 0
    j = 0
    k = 0

    print "Listening to port %d" % port

    uuid = "8ce255c0-200a-11e0-ac64-0800200c9a66"
    bluetooth.advertise_service(server_sock, "Kaffeeautomat", uuid)

    while 1:
        client_sock, address = server_sock.accept()
        print "Accepted connection from ", address

        while 1:
            try:
                data = client_sock.recv(1024)
                print "received [%s]" % data

                if data.startswith("ACCEPT"):
                    check[i] = data.split("T")[1]
                    i += 1

                    client_sock.send("OKSTOP")

                elif data.startswith("BUY"):
                    print data
                    tmp = data.split(":")
                    print tmp[1] + "; " + tmp[2]
                    j = i

                    while j >= 0:
                        print j
                        if check[j] == tmp[1]:
                            print "IN"
                            if tan[j] == tmp[2]:
                                check[j] = "done"
                                tan[j] = "done"
                                GPIO.output(23, GPIO.HIGH)
                                time.sleep(5)
                                GPIO.output(23, GPIO.LOW)
                                print "Threw out"
                                client_sock.send("OKSTOP")
                                j = 0
                                break

                            else:
                                print "NOHIT"

                        j -= 1

                    if j == -1:
                        client_sock.send("ERRORSTOP")
                    j = 0

            except:
                print "Connection lost"
                break

    client_sock.close()
    server_sock.close()
Example #38
0
import bluetooth

server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

#port = bluetooth.get_available_port( bluetooth.RFCOMM )
port = 1
server_sock.bind(("", port))
server_sock.listen(1)
print("listening on port %d" % port)

uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
bluetooth.advertise_service(server_sock, "FooBar Service", uuid)

client_sock, address = server_sock.accept()
print("Accepted connection from ", address)

data = client_sock.recv(1024)
print("received [%s]" % data)

client_sock.close()
server_sock.close()
Example #39
0
    def start(self):
        '''
        Serves a socket on the default port, listening for clients.  Upon client connection, runs a loop to 
        that receives period-delimited messages from the client and calls the sub-class's 
        handleMessage(self, message) method.   Sub-class can call send(self, message) to send a 
        message back to the client.   Begins listening again after client disconnects.
        '''

        # Make device visible
        os.system("hciconfig hci0 piscan")

        # Create a new server socket using RFCOMM protocol
        server_sock = bt.BluetoothSocket(bt.RFCOMM)

        # Bind to any port
        server_sock.bind(("", bt.PORT_ANY))  #
        #server_sock.find(("", 1))#

        # Start listening
        server_sock.listen(1)

        # Get the port the server socket is listening
        port = server_sock.getsockname()[1]

        # Start advertising the service
        bt.advertise_service(server_sock,
                             "RaspiBtSrv",
                             service_id=self.uuid,
                             service_classes=[self.uuid, bt.SERIAL_PORT_CLASS],
                             profiles=[bt.SERIAL_PORT_PROFILE])

        # Outer loop: listen for connections from client
        while True:
            print("Waiting for connection on RFCOMM channel %d" % port)
            try:
                # This will block until we get a new connection
                self.client_sock, client_info = server_sock.accept()
                print("Accepted connection from " + str(client_info))

                # Track strings delimited by '.'
                s = ''
                try:
                    on = open(pathON, 'r')
                    neededContents = on.read()
                    nC = neededContents.split('|')[:-1]

                    op = open(pathOP, 'r')
                    presentContents = op.read()
                    pC = presentContents.split('|')[:-1]

                    bl = open(pathBL, 'r')
                    bp = bl.read()  # bp - battery percentage

                    print("Sending List of Objects missing")
                    for need in nC:
                        if need not in pC:
                            print(need)
                            self.send("OM:" + need)

                    print("Sending List of Objects present ")
                    for present in pC:
                        print(present)
                        self.send("OP:" + present)

                    print("Sending battery level of Pi")
                    print(bp)
                    self.send("BL:" + bp)

                except IOError:
                    print("Trouble reading file. Trying again after 5 seconds")
                time.sleep(5)
        #while True:
        #self.send("Object Missing");
        #self.send("U|0|1")
        #c = self.client_sock.recv(1).decode('utf-8')
        #if c == '.' and len(s) > 0:
        #    self.handleMessage(s)
        #self.send(s)
        #print(s)
        # self.handleMessage(s)
        #    s = ''
        #else:
        #    s += c

            except IOError:
                pass

            except KeyboardInterrupt:

                if self.client_sock is not None:
                    self.client_sock.close()

                server_sock.close()

                print("Server going down")
                break
Example #40
0
 def advertise_service(self):
     bluetooth.advertise_service(self.server_sock, self.name, self.uuid)
Example #41
0
#GPIO.setmode(GPIO.BOARD)
#inputPin = 7
#GPIO.setup(inputPin, GPIO.IN)

## Setup Socket
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

## How to read and write through bluetooth
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
bluetooth.advertise_service(server_sock, "SampleServer", service_id=uuid,
                            service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                            profiles=[bluetooth.SERIAL_PORT_PROFILE],
                            #protocols=[bluetooth.OBEX_UUID]
                            )

print("Waiting for connection on RFCOMM channel", port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from", client_info)

try:
    while True:
        sendMessage = "bye jake"
        print(sendMessage)
        client_sock.send(sendMessage)
        data = client_sock.recv(1024)
        if not data:
Example #42
0
    def __init__(self, config=None, **kwds):
        super().__init__(**kwds)

        self.cfv_fn = None
        self.click_step = 1.0
        self.click_timer = QtCore.QTimer(self)
        self.click_x = 0.0
        self.click_y = 0.0
        self.client_sock = False
        self.connected = False
        self.default_image = QtGui.QImage("bt_image.png")
        self.drag_gain = 1.0
        self.drag_x = 0.0
        self.drag_y = 0.0
        self.filming = False
        self.image_is_new = True
        self.images_sent = 0
        self.is_down = False
        self.is_drag = False
        self.messages = []
        self.mutex = QtCore.QMutex()
        self.offset_min = None
        self.offset_max = None
        self.parameters = params.StormXMLObject()
        self.qpd_fn = None
        self.running = False
        self.send_pictures = config.get("send_pictures")
        self.show_camera = True
        self.stage_fn = None
        self.start_time = 0
        self.sum_min = None
        self.sum_max = None

        self.parameters.add(
            params.ParameterRangeFloat(description="Drag multiplier",
                                       name="d_mult",
                                       value=100.0,
                                       min_value=0.1,
                                       max_value=1000.0))

        self.parameters.add(
            params.ParameterRangeFloat(description="Z step size in um",
                                       name="z_step",
                                       value=0.1,
                                       min_value=0.0,
                                       max_value=5.0))

        # Set current image to default.
        self.current_image = self.default_image

        # Setup bluetooth socket.
        have_bluetooth = True
        try:
            self.server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            self.server_sock.bind(("", bluetooth.PORT_ANY))
            self.server_sock.listen(1)

            port = self.server_sock.getsockname()[1]
            print("Bluetooth: Listening on RFCOMM channel {0:d}".format(port))

            uuid = "3e1f9ea8-9c11-11e3-b248-425861b86ab6"

            bluetooth.advertise_service(
                self.server_sock,
                "halServer",
                service_id=uuid,
                service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                profiles=[bluetooth.SERIAL_PORT_PROFILE])

        except bluetooth.btcommon.BluetoothError:
            print(traceback.format_exc())
            print("Failed to start Bluetooth")
            have_bluetooth = False

        if have_bluetooth:

            # Setup timer.
            self.click_timer.setInterval(200)
            self.click_timer.timeout.connect(self.handleClickTimer)
            self.click_timer.setSingleShot(True)

            # Connect signals.
            self.newMessage.connect(self.handleNewMessage)
            self.start(QtCore.QThread.NormalPriority)
Example #43
0
        localhost - locally advertised SDP

'''
import bluetooth
from time import time
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

# Use SDP
port = 0

server_sock.bind(("",port))
server_sock.listen(1)

# Not works totally, just use uuid
uuid = "1e0ca4ea-299d-4335-93eb-27fcfe7fa848"
bluetooth.advertise_service(server_sock, "Foobar Service",\
    service_classes=[bluetooth.SERIAL_PORT_CLASS],\
    profiles=[bluetooth.SERIAL_PORT_PROFILE])

while True:
    client_sock, address = server_sock.accept()
    print("Accepted connection from ", address)

    try:
        data = client_sock.recv(1024)
        print("Received [%s]" % data)
    except Exception as e:
        print("[{}] {}".format(time(),repr(e)))
    finally:
        client_sock.close()
        server_sock.close()
Example #44
0
###########################################################################################################
## main function/ code

if __name__ == "__main__":

    print("Starting server...")
    #create bluetooth socket and acept connection from master
    server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    server.bind(("", BTPortNo))
    server.listen(1)

    strin = "Chip device"
    myinfo = sensor_top.detectall()

    bluetooth.advertise_service(server,strin,service_classes = [bluetooth.SERIAL_PORT_CLASS],\
        profiles=[bluetooth.SERIAL_PORT_PROFILE]\
        , description = str(myinfo))
    try:
        print("Waiting for connection from master [RFCOMM port=%d]" % BTPortNo)
        while (1):
            try:
                client, client_info = server.accept()
                print("Connected to", client_info)
                thread_name = '_' + client_info[0]
                thread.start_new_thread(new_client,
                                        (thread_name, 0, client, client_info))

            #handle exceptions/ctrl + c
            except KeyboardInterrupt:
                print("Shutting down...")
                client.close()
Example #45
0
    # Scrive un file.
    out_file = open(fileout, "w")
    out_file.write(text)
    out_file.close()


server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

port = 3

server_sock.bind(("", port))
server_sock.listen(1)

myUuid = "94f39d29-7d6d-437d-973b-fba39e49d4ef"
bluetooth.advertise_service(server_sock,
                            "SampleServerL2CAP",
                            service_id=myUuid,
                            service_classes=[myUuid])

while True:
    try:
        client_sock, address = server_sock.accept()
        print("Accepted connection from ", address)

        strInput = ''
        data = ''
        try:
            data = client_sock.recv(1)
            strInput = data
            while (data != '&'):
                data = client_sock.recv(1)
                if (data != '&'):
def runServer():

    global x
    global servoPin1
    global servoPin2
    global servoPin3
    global servoPin4
    global servoPin5
    

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)
    
    GPIO.setup(servoPin1, GPIO.OUT)
    GPIO.setup(servoPin2, GPIO.OUT)
    GPIO.setup(servoPin3, GPIO.OUT)
    GPIO.setup(servoPin4, GPIO.OUT)
    GPIO.setup(servoPin5, GPIO.OUT)
    
    pwm1 = GPIO.PWM(servoPin1, 50)
    pwm1.start(5)

    pwm2 = GPIO.PWM(servoPin2, 50)
    pwm2.start(5)

    pwm3 = GPIO.PWM(servoPin3, 50)
    pwm3.start(5)

    pwm4 = GPIO.PWM(servoPin4, 50)
    pwm4.start(5)

    pwm5 = GPIO.PWM(servoPin5, 50)
    pwm5.start(5)

    serverSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    port = bluetooth.PORT_ANY
    serverSocket.bind(("", port))
    print "Servo Server"
    print "Listening for connections on port: ", port

    while 1:
        # wait for a message to be sent
        serverSocket.listen(0)
        port = serverSocket.getsockname()[1]

        bluetooth.advertise_service(serverSocket, "BluetoofServer",
                                    service_id=uuid,
                                    service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
                                    profiles=[bluetooth.SERIAL_PORT_PROFILE]
                                    )

        inputSocket, address = serverSocket.accept()
        print "Got connection with ", address
        while 1:
            try:
                data = inputSocket.recv(1024)
                data = data.split("}")[0] + "}"
                data = dict(ast.literal_eval(data))
                
                servo = data["servo"]; 
                pos = data["position"]
              
                print(str(servo) + " : " + str(pos))                

                if (servo == "s1"):
                   targetPwm = pwm1
		if (servo == "s2"):
		   targetPwm = pwm2
                if (servo == "s3"):
		   targetPwm = pwm3
		if (servo == "s4"):
		   targetPwm = pwm4
		if (servo == "s5"):
		   targetPwm = pwm5
                
		targetPwm.ChangeDutyCycle(convertToDegrees(pos))
                
                   
            except bluetooth.btcommon.BluetoothError:
                print("Exception thrown: quitting...")
                break
def main():
    # Defining Dynamixel IDs (Input for control)
    # Bluetooth Functions
    server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
    server_sock.bind(("", bluetooth.PORT_ANY))
    server_sock.listen(1)

    port = server_sock.getsockname()[1]

    uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

    bluetooth.advertise_service(
        server_sock,
        "SampleServer",
        service_id=uuid,
        service_classes=[uuid, bluetooth.SERIAL_PORT_CLASS],
        profiles=[bluetooth.SERIAL_PORT_PROFILE],
        # protocols=[bluetooth.OBEX_UUID]
    )

    print("Waiting for connection on RFCOMM channel", port)

    client_sock, client_info = server_sock.accept()
    print("Accepted connection from", client_info)
    # After connected to device receive data and print data
    # we need to integrate the app we will be developing to the data here
    # We might need another way to bluetooth connect, not sure how the mit app inventor bluetooth connection work, but should work
    # Refer to https://github.com/pybluez/pybluez for more examples and more functions that we can use

    try:
        while True:
            data = client_sock.recv(1024)
            if not data:
                break
            print(data)
            # Do we want to implement check for busy arm and queue system for order drink?
            # We probably can do that by implementing a variable state which stores the number of drinks in queue and run a check
            # For non busy easy. For queue, arm would store the order and return to app queue number etc.
            data = data.decode('utf-8').split("\"")  # Formatting Output

            # Number of drinks
            n = int((len(data) - 1) / 6)
            print("Number of drinks", n)

            # Formatting Data for use
            arr = []
            for x in range(1, len(data), 2):
                arr1 = [data[x]]
                arr = arr + arr1
                print(arr
                      )  # Array of drinks e.g. [coffee,cold,0%,coffee,cold,0%]

            for x in range(1, n + 1):
                print("Serving Drink ", x, arr[0 + 3 * (x - 1)])
                # Added timer delay for testing in app, please remove after added sequence for moving arm
                drink = arr[3 * (x - 1)]
                temp = arr[3 * (x - 1) + 1]
                sugar = arr[3 * (x - 1) + 2]
                print("Drink details:", drink, temp, sugar)

                print("Moving arm to ", drink, "dispenser")
                time.sleep(5)
                print("Dispensing Drink", x, drink)
                client_sock.send(
                    ("Dispensing Drink " + str(x) + ":" + drink).encode())
                time.sleep(5)
                print("Delivering Drink", x, drink)
                client_sock.send(
                    ("Delivering Drink " + str(x) + ":" + drink).encode())
                time.sleep(5)
                print("Delivered")
                client_sock.send(("Drink " + str(x) + " delivered").encode())
    except OSError:
        pass

    print("Disconnected.")

    client_sock.close()
    server_sock.close()
    print("All done.")
Example #48
0
def launch_hub_bluetooth_server(config_file_path):
    ''' 
    Launches the Tremium Hub bluetooth server which the Tremium Nodes connect to.

    Parameters
    ----------
    config_file_path (str) : path to the hub configuration file
    '''

    # loading Tremium Hub configurations
    config_manager = HubConfigurationManager(config_file_path)
    log_file_path = os.path.join(
        config_manager.config_data["hub-file-transfer-dir"],
        config_manager.config_data["bluetooth-server-log-name"])

    # setting up logging
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    log_handler = logging.handlers.WatchedFileHandler(log_file_path)
    log_handler.setFormatter(
        logging.Formatter('%(name)s - %(levelname)s - %(message)s'))
    logger.addHandler(log_handler)

    # defining container for connection handler handles
    connection_handlers_h = []

    try:

        # creating socket to listen for new connections
        listener_s = BluetoothSocket()
        listener_s.bind(
            (config_manager.config_data["bluetooth-adapter-mac-server"],
             config_manager.config_data["bluetooth-port"]))
        listener_s.listen(1)

        # advertising the listenning connection
        advertise_service(listener_s, config_manager.config_data["hub-id"])

        bind_address = listener_s.getsockname()
        time_str = datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d_%H-%M-%S')
        logging.info(
            "{0} - Hub Bluetooth server listening on address : {1}".format(
                time_str, bind_address))

    except Exception as e:
        time_str = datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d_%H-%M-%S')
        logging.error(
            "{0} - Hub Bluetooth server failed to create listener socket : {1}"
            .format(time_str, e))
        raise

    while True:

        try:

            # blocking until a new connection occurs, then create connection handler
            client_s, remote_address = listener_s.accept()
            client_s.settimeout(
                config_manager.config_data["bluetooth-comm-timeout"])
            connection_handler = HubServerConnectionHandler(
                config_file_path, client_s, remote_address)

            # launching connection handler in a seperate process
            process_h = Process(target=connection_handler.handle_connection,
                                args=())
            process_h.start()
            connection_handlers_h.append(process_h)

            time_str = datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d_%H-%M-%S')
            logging.info(
                "{0} - Hub Bluetooth server accepted and is handling connection from remote : {1}\
                         ".format(time_str, remote_address))

            #regular check to clear dead handles
            for handler_h in connection_handlers_h:
                if handler_h is not None:
                    connection_handlers_h.remove(handler_h)

        except Exception as e:

            # killing all connection handler processes still running
            for handler_h in connection_handlers_h:
                if handler_h.exitcode is None:
                    handler_h.terminate()

            time_str = datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d_%H-%M-%S')
            logging.error(
                "{0} - Hub Bluetooth server failed to handle incoming connection : {1}"
                .format(time_str, e))
            raise
def main():
    
        
    while True:
        network = getCurrentNetwork()
        print(network)
        if not network:
            #Bluetooth setup routine via android
            print("In android setup")    
            while not getCurrentNetwork():
                server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM )
                server_sock.bind(("",bluetooth.PORT_ANY))
                server_sock.listen(3)
                server_sock.settimeout(10)
                port = server_sock.getsockname()[1]

                uuid = "SECRETDUUID"

                bluetooth.advertise_service(server_sock, "Bluetooth-network-beacon",
                            service_id = uuid,
                            service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
                            profiles = [ bluetooth.SERIAL_PORT_PROFILE ],
                            )
                
               
                try:
                    client, addr = server_sock.accept()
                    client.settimeout(10)
                    inc = client.recv(1024)
                    credentials = inc.decode("UTF-8").split(" ")
                    print(credentials)
                    client.close()
                    server_sock.close()
                    connectWifi(str(credentials[0]), str(credentials[1]))
                    print(getKnownNetworks())
                except Exception as e:
                    print(e)
        else:    
            subprocess.call(["rfkill","unblock", "bluetooth"])
           
            try:
                nearby_devices = bluetooth.discover_devices(lookup_names = True)
               
                for baddr,name in nearby_devices:
                    print(name)
                    if "ESP32" in name:
                        port = 1
                        bSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)

                        try:
                            print('Trying to connect')
                            bSocket.connect((baddr, port))
                            inputString = returnInfo();
                            print(inputString)
                            add = 16 - len(inputString) % 16
                            out = inputString + add * ' ';
                            print(generateHash((out).encode("ASCII")))
                            bSocket.sendall(generateHash((out).encode("ASCII")))
                            bSocket.close()
                            
                        except Exception as e:
                            bSocket.close();
                            print(e)
            except Exception as e:
                print(e)
        
        #subprocess.call(["rfkill","block", "bluetooth"])       
        time.sleep(0.5)
Example #50
0
import json
import pyowm #Python Open Weather Map
import bluetooth # Python bluetooth tools 

server_sock=bluetooth.BluetoothSocket(bluetooth.RFCOMM )

port = 1
server_sock.bind(("",port))
server_sock.listen(1)

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
bluetooth.advertise_service(server_sock, "nexus", uuid)

client_sock,address = server_sock.accept()
print "Accepted connection from ",address

data = client_sock.recv(1024)
print "received [%s]" % data

client_sock.close()
server_sock.close()

try:
# Register API Key with source
 API_key = '89cb9b3c8c3c1ee033be08ffcfd26076'
 owm = pyowm.OWM(API_key)

# Register a location: city,state AND print
 location = 'Philadelphia,PA'
 print('Location:', location)
Example #51
0
    signal_json = Path("../common/signal.json")
    # signal_wav = Path("../common/signal.wav")
    # if not (signal_json.exists() and signal_wav.exists()) :
    create_signal()
    with open(signal_json, "r") as json_file:
        signal = json.loads(json_file.read())["signal"]

    server_sock = bt.BluetoothSocket(bt.RFCOMM)
    server_sock.bind(("", bt.PORT_ANY))
    server_sock.listen(1)
    port = server_sock.getsockname()[1]
    uuid = "ae465fd9-2d3b-a4c6-4385-ea69b4c1e23c"
    bt.advertise_service(
        server_sock,
        "LocalisationServer",
        service_id=uuid,
        service_classes=[uuid, bt.SERIAL_PORT_CLASS],
        profiles=[bt.SERIAL_PORT_PROFILE],
    )
    if SIMULATION:
        emission_offset = 500 + np.random.randint(500)
        record = simulate_record(emission_offset + 500, emission_offset, 0.5,
                                 signal)
        t1 = get_time(record, signal, emission_offset)
        d1 = t1 * SOUND_CELERITY
        response = {"accepted": False}
        if d1 < 1:
            response["accepted"] = True
        print("test : {}\noffset: {}\ntime: {}\ndistance: {}".format(
            "ACCEPTED" if response["accepted"] else "REFUSED",
            emission_offset,
Example #52
0
# $Id: rfcomm-server.py 518 2007-08-10 07:20:07Z albert $
import bluetooth
import bluetooth as bt


server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
server_sock.bind(("", bluetooth.PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

bt.advertise_service( server_sock, "SampleServer",
                   service_id = uuid,


#                   protocols = [ OBEX_UUID ]
                    )

print("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)

try:
    while True:
        data = client_sock.recv(1024)
        if len(data) == 0: break
        print("received [%s]" % data)
except IOError:
    pass