Ejemplo n.º 1
0
def main(restart):  #主程式 (是否重啟)
    try:  #避免錯誤,捕抓意外情況
        bsl.server().copyleft_declaration()
        sock = lightblue.socket()  #產生socket物件
        sock.bind(("", 1))  #綁定通道,若通道被占用,綁定通道將出錯
        sock.listen(1)  #聆聽RFCOMM通道1
        lightblue.advertise("EchoService", sock, lightblue.RFCOMM)  #開始廣播服務
        if (restart):  #如果重啟旗標為真
            bsl.server().log(
                R.msg_level.info,
                R.server_msg.info.server_restart_success)  #伺服器重啟成功
        bsl.server().log(R.msg_level.info,
                         R.server_msg.info.brocasting.format(
                             sock.getsockname()[1]))  #告知手機綁定通道
        conn, addr = sock.accept()  #新連線
        bsl.server().log(R.msg_level.info,
                         R.server_msg.info.new_connection.format(addr[0]))
        flag = True

        while (flag):
            data = conn.recv(1024).rstrip()
            #print(data)
            bsl.server().log(R.msg_level.info,
                             "{} {}".format(R.msg_direction.RX, data))
            command_selector(conn, data)
    except KeyboardInterrupt:
        print
        bsl.server().log(R.msg_level.info, R.server_msg.info.user_interrupt)
        exit()
    except Exception as exception:  #捕抓到錯誤
        exceptionString = str(exception)  #錯誤原因字串
        if (debugMode):  #除錯模式?
            exc_type, exc_obj, exc_tb = sys.exc_info()
            fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
            print("{}, {}, {}, {}".format(exc_type, fname, exc_tb.tb_lineno,
                                          exceptionString))
        error_code = bsl.common().GetErrorCode(exceptionString)
        #print('error_code: {}'.format(error_code))
        if (error_code == '98'):  #端口正在被使用中例外
            bsl.server().log(R.msg_level.error,
                             R.server_msg.error.address_or_port_in_use)
            terminated = True
        elif (error_code == '104'):  #使用者離線例外
            bsl.server().log(R.msg_level.info,
                             R.server_msg.info.user_disconnect)
            bsl.server().log(
                R.msg_level.info,
                R.server_msg.warning.server_encountered_fixable_error)
            bsl.server().log(R.msg_level.info,
                             R.server_msg.warning.server_fixing_error)
            conn.close()
            sock.close()
            bsl.server().log(R.msg_level.info,
                             R.server_msg.info.restart_server)
            main(True)
        elif (error_code == '13'):  #權限不足例外
            bsl.server().log(R.msg_level.error, R.local_msg.permission_denied)
            terminated = True
        elif (error_code == '111'):  #連線被拒例外
            bsl.server().log(R.msg_level.error, R.local_msg.connection_refused)
Ejemplo n.º 2
0
def advertise_service(sock, name, service_id="", service_classes=None,
        profiles=None, provider="", description="", protocols=None):

    if protocols is None or protocols == RFCOMM:
        protocols = [lightblue.RFCOMM]

    lightblue.advertise(name, sock, protocols[0], service_id)
Ejemplo n.º 3
0
    def __init__(self, serviceName = u'FluidNexus', database = None, library="e32"):
        """Initialize the server be setting up the server socket and advertising the FluidNexus service."""

        log.write("Starting Fluid Nexus Server")
        # Save our database object 
        self.database = database

        # Save our service name
        self.serviceName = serviceName

        self.mutex = thread.allocate_lock()

        self.library = library

        # Setup our server socket
        if (self.library == "e32"):
            self.serverSocket = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
            self.serverPort = socket.bt_rfcomm_get_available_server_channel(self.serverSocket)
            self.serverSocket.bind(("", self.serverPort))
            self.serverSocket.listen(self.numberConnections)
            socket.bt_advertise_service(self.serviceName, self.serverSocket, True, socket.RFCOMM)

            # Remove security protections
            # @TODO@ Make sure this actually does what we want it to do!
            socket.set_security(self.serverSocket, 0)

        elif (self.library == "lightblue"):
            self.serverSocket = lightblue.socket()
            self.serverSocket.bind(("", 0))
            self.serverSocket.listen(self.numberConnections)
            lightblue.advertise(self.serviceName, self.serverSocket, lightblue.RFCOMM)
Ejemplo n.º 4
0
 def run(self):
     sendSkt = lightblue.socket()
     sendSkt.bind(("", 0))
     sendSkt.listen(1)
     lightblue.advertise("SMS Gateway (Response Thread)", sendSkt,
                         lightblue.RFCOMM)
     db = database()
     conn2, addr2 = sendSkt.accept()
     print "Connected to Response Server", addr2
     while 1:
         time.sleep(1)
         db = database()
         rows = db.popOutboxMsg()
         for row in rows:
             print "Sending Msg -> %s" % (row[0])
             sms = SMS(str(row[0]), row[1], row[2], row[3], str(row[4]))
             toSend = sms.toXML()
             print toSend
             conn2.send(toSend.replace("\n", "\\n"))
             res = conn2.recv(1024)
             print res
             while (res != "1" and res != "2"):
                 res = conn2.recv(1024)
                 print res
             db.setOutboxProcessed(str(row[0]), res)
Ejemplo n.º 5
0
def advertise_service(sock, name, service_id="", service_classes=None,
        profiles=None, provider="", description="", protocols=None):

    if protocols is None or protocols == RFCOMM:
        protocols = [lightblue.RFCOMM]

    lightblue.advertise(name, sock, protocols[0], service_id)
Ejemplo n.º 6
0
Archivo: bt.py Proyecto: xdr1000/codi
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)
Ejemplo n.º 7
0
Archivo: bt.py Proyecto: 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)
Ejemplo n.º 8
0
    def receiveFile(self, channel=0):
        sock = lightblue.socket()
        sock.bind(("", channel))
        channelID = sock._getport()

        print "receivee", sock, channelID
        
        lightblue.advertise("LightBlue example OBEX service", sock, lightblue.OBEX)

        server = lightblue.obex.OBEXServer.alloc().initWithChannel_(channelID)
        
        d_connected = defer.Deferred()
        d_disconnected = defer.Deferred()
        d_putcompleted = defer.Deferred()
        d_putrequested = defer.Deferred()
        d_errored = defer.Deferred()
        
        _fileobj = None

        def _putrequested(session, filename, filetype, filesize):
            print "req"
            _fileobj = open("tmp.tmp", "wb")
            filehandle = Foundation.NSFileHandle.alloc().initWithFileDescriptor_(f.fileno())
            d_putrequested.callback((session, filename, filetype, filesize))
            return filehandle
        
        def _disconnected(session):
            print 'disc'
            d_disconnected.callback(session)
        
        def _putcompleted(session):
            print "aooa"
            d_putcompleted.callback(session)
            _fileobj.close()

        def _errored(session, e, em):
            print session, e, em

        def _connected(session):
            print session
            d_connected.callback(session)

        server.disconnected = _disconnected
        server.putcompleted = _putcompleted
        server.putrequested = _putrequested
        server.errored = _errored
        server.connected = _connected
        
        #d_connected.addCallback(_putFile)
        #d_connected.addErrback(_handleError)
        #d_putcompleted.addCallback(_disconnect)
        #d_putcompleted.addErrback(_handleError)
        #d_disconnected.addBoth(_close)
        
        server.start()
Ejemplo n.º 9
0
def lightblue_server_test():
    # L2CAP server sockets not currently supported :(
    s = lightblue.socket(lightblue.L2CAP)
    s.bind(("", 0x1001))
    s.listen(1)
    lightblue.advertise("Peach", s, lightblue.L2CAP)
    conn, addr = s.accept()
    print("Connected by", addr)
    data = conn.recv(1024)
    print("Received: %s" % data)
    conn.close()
    s.close()
Ejemplo n.º 10
0
 def startAdvertising(self):
     self.cv.acquire()
     if not self.advertising:
         self.devid = self.intrf.request(bandwidth=0)
         self.obexsocket = lightblue.socket()
         self.obexsocket.bind(("", 0))
         lightblue.advertise("OBEX Object Push", self.obexsocket, lightblue.OBEX)
         print "[OXR] Advertising OBEX Object Push on interface hci%d" % self.devid
         self.advertising = True
         self.cv.notify()
     self.cv.release()
     return self.devid
Ejemplo n.º 11
0
def lightblue_server_test():
    # L2CAP server sockets not currently supported :(
    s = lightblue.socket(lightblue.L2CAP)
    s.bind(("", 0x1001))
    s.listen(1)
    lightblue.advertise("Peach", s, lightblue.L2CAP)
    conn, addr = s.accept()
    print("Connected by", addr)
    data = conn.recv(1024)
    print("Received: %s" % data)
    conn.close()
    s.close()
Ejemplo n.º 12
0
    def initMessageAdvertisements(self):
        """Initialize the advertisement of hashes that have been sent to us."""

        # @TODO@ Use the correct database here :-)
        #self.database.query('select * from FluidNexusStigmergy')
        self.database.services()

        self.messageHashes = []

        for item in self.database:
            # @TODO@ This can break if we change the database schema

            # Get the last item (the hash)
            self.messageHashes.append('%s' % item[-1])

        # If there is nothing in the FluidNexusStigmergy database, return now
        if len(self.messageHashes) == 0:
            return

        # @HACK@
        # For some reason we have to do this convoluted process below, otherwise sockets get reused or don't advertise properly.  
        # Meaning, we have to create the sockets beforehand, and then loop through them to advertise with the desired hashes.
        # This seems strange, because we create the sockets anew before we advertise them, so it seems like some kind of race condition.

        # Get the number of hashes to advertise
        numAdvertise = len(self.messageHashes)

        # Create all of our advertisingSockets
        self.advertisingSockets = {}
        for counter in range(0, len(self.messageHashes)):
            if (self.library == "e32"):
                self.advertisingSockets[self.messageHashes[counter]] = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
            elif (self.library == "lightblue"):
                self.advertisingSockets[self.messageHashes[counter]] = lightblue.socket()

        # Now, do what we need to with the sockets
        for item in self.advertisingSockets.items():
            hash = item[0]
            s = item[1]
            
            if (self.library == "e32"):
                tempPort = socket.bt_rfcomm_get_available_server_channel(s)
    
                s.bind(("", tempPort))
                s.listen(1)
                socket.bt_advertise_service(unicode(':' + hash), s, True, socket.RFCOMM)
            elif (self.library == "lightblue"):
                s.bind(("", 0))
                s.listen(1)
                lightblue.advertise(unicode(':' + hash), s, lightblue.RFCOMM)
Ejemplo n.º 13
0
    def run(self):
        server_socket = lightblue.socket(lightblue.RFCOMM)
        server_socket.bind((" ", 0))
        server_socket.listen(1)

        lightblue.advertise("test_service", server_socket, lightblue.RFCOMM)

        self.connected_socket, self.connected_client_address = server_socket.accept(
        )
        print "Connected by ", self.connected_client_address

        connected_thread = BtConnectedThread(
            connected_socket=self.connected_socket,
            connected_client_address=self.connected_client_address)
        connected_thread.start()
        server_socket.close()
Ejemplo n.º 14
0
 def run(self):
     s = lightblue.socket()
     s.bind(("", 0))
     s.listen(2)
     lightblue.advertise("SMS Gateway (Request Thread)", s,
                         lightblue.RFCOMM)
     conn, addr = s.accept()
     print "Connected to Request Server", addr
     while 1:
         resp = conn.recv(1024)
         print resp
         msg = SMS(resp)
         db = database()
         db.pushInboxMsg(msg.id, msg.to, msg.frm, msg.text, msg.timestamp)
     conn.close()
     s.close()
Ejemplo n.º 15
0
def setupBluetooth():
    global conn
    global sock

    # Listen for Bluetooth connections
    sock = lightblue.socket()
    sock.bind(("", 0))    # bind to 0 to bind to a dynamically assigned channel
    sock.listen(1)
    lightblue.advertise("EchoService", sock, lightblue.RFCOMM)
    print "Advertised and listening on channel %d..." % sock.getsockname()[1]

    # Accept the first incoming connection
    conn, addr = sock.accept()
    print "Connected by", addr

    # Send the start command to Glass
    conn.send("start")
Ejemplo n.º 16
0
def bkservice():
    """备份服务"""
    sock_server=lightblue.socket()
    sock_server.bind(('',0))
    sock_server.listen(1)
    lightblue.advertise(u'bkservice',sock_server,lightblue.RFCOMM)
    conn,addr=sock_server.accept()
    print 'Client [%s] connected!'%repr(addr)
    #conn.settimeout(5)
    #print dir(conn)
    try:
        bksession(conn)
    except:
        traceback.print_exc()
    finally:
        conn.close()
    return
Ejemplo n.º 17
0
 def advertiseNewHash(self, hash):
     """Advertise a new hash that we have just received."""
     
     log.write(str(hash))
     if (self.library == "e32"):
         newSocket = socket.socket(socket.AF_BT, socket.SOCK_STREAM)
         self.advertisingSockets[hash] = newSocket
         tempPort = socket.bt_rfcomm_get_available_server_channel(newSocket)
         newSocket.bind(("", tempPort))
         newSocket.listen(1)
         socket.bt_advertise_service(unicode(':' + hash), newSocket, True, socket.RFCOMM)
     elif (self.library == "lightblue"):
         newSocket = lightblue.socket()
         self.advertisingSockets[hash] = newSocket
         newSocket.bind(("", 0))
         newSocket.listen(1)
         lightblue.advertise(unicode(":" + hash), newSocket, lightblue.RFCOMM)
Ejemplo n.º 18
0
    def receive(self):

        self.log("Dump your data...")

        s = lightblue.socket()
        s.bind(("", 0))
        lightblue.advertise("My OBEX Service", s, lightblue.OBEX)

        try:
            while True:
    
                (addr, fname) = lightblue.obex.recvfile(s, "tmp.dat")

                if fname is not None:
                    fullname = serial_filename(settings.MEDIA_ROOT + "incoming/" + fname)
                    fname = "incoming/" + fullname.split("/")[-1]
                    os.rename("tmp.dat", fullname)

                    # find device
                    try:
                        device = Device.objects.get(device_id = addr);
                    except Device.DoesNotExist:
                        device = Device(device_id = id, name = name)
                        self.log("New device: %s" % device)

                    device.save()

                    recv = DeviceReceived(device = device, filename = fname)
                    recv.recv_time = datetime.now()
                    recv.save()
                    
                    self.log("Got %s from %s" % (fname, device))
                else:
                    self.log("Receive error...")
        except Exception, e:
            print e
            print "Bye..."
            s.close()
Ejemplo n.º 19
0
    def run(self):
        
        '''
        server_sock=BluetoothSocket( RFCOMM )
        server_sock.bind(("",PORT_ANY))
        server_sock.listen(1)
        
        port = server_sock.getsockname()[1]
        
        uuid = "00001073-0000-1000-8000-00805F9B34F7"
        
        advertise_service( server_sock, "TTTService",
                           service_id = uuid,
                           service_classes = [ uuid, SERIAL_PORT_CLASS ],
                           profiles = [ SERIAL_PORT_PROFILE ] )
        '''
        
        server_sock = lightblue.socket()
        server_sock.bind(("", 0))    # bind to 0 to bind to a dynamically assigned channel
        server_sock.listen(1)
        lightblue.advertise("TTTService", server_sock, lightblue.RFCOMM)
        port = server_sock.getsockname()[1]
        print "Advertised and listening on channel %d..." % server_sock.getsockname()[1]
        
                           
        while not self.shutdown:
            
            print "Waiting for connection on RFCOMM channel %d" % port
        
            client_sock, client_info = server_sock.accept()
            
            client_thread = ClientThread(self.processClientConnection, client_sock, client_info)
            client_thread.start()
            #client_thread.join()

        server_sock.close()
        print "Bluetooth Sync Server Terminated"
Ejemplo n.º 20
0
"""
Shows how to run a RFCOMM server socket.
"""
import lightblue

# create and set up server socket
sock = lightblue.socket()
sock.bind(("", 0))    # bind to 0 to bind to a dynamically assigned channel
sock.listen(1)
lightblue.advertise("EchoService", sock, lightblue.RFCOMM)
print "Advertised and listening on channel %d..." % sock.getsockname()[1]

conn, addr = sock.accept()
print "Connected by", addr

data = conn.recv(1024)  
print "Echoing received data:", data
conn.send(data)

# sometimes the data isn't sent if the connection is closed immediately after
# the call to send(), so wait a second
import time
time.sleep(1)

conn.close()
sock.close()
Ejemplo n.º 21
0
import lightblue

port = 5
s = lightblue.socket()
s.bind(('', port))
s.listen(1)
print 'Listening on port', port
lightblue.advertise('Arm Launcher', s, lightblue.RFCOMM)
connection, address = s.accept()
print 'Accepted connection from', address

while True:
    data = connection.recv(1024)
    if not data:
        break
    print 'Received [%s]' % data

connection.close()
s.close()
Ejemplo n.º 22
0
#!/usr/bin/env python3
import lightblue

sock = lightblue.socket()
try:
    sock.bind(("localhost", 0))    # bind to 0 to bind to a dynamically assigned channel
    lightblue.advertise("OBEX File Transfer", sock, lightblue.OBEX)

    # Receive a file and save it as MyFile.txt.
    # This will wait and block until a file is received.
    print( "Waiting to receive file on channel %d..." % sock.getsockname()[1])
    lightblue.obex.recvfile(sock, "MyFile.txt")

finally:
    sock.close()

print("Saved received file to MyFile.txt!")
Ejemplo n.º 23
0
"""
Shows how to run a RFCOMM server socket.
"""
import lightblue

# create and set up server socket
sock = lightblue.socket()
sock.bind(("", 0))  # bind to 0 to bind to a dynamically assigned channel
sock.listen(1)
lightblue.advertise("EchoService", sock, lightblue.RFCOMM)
print "Advertised and listening on channel %d..." % sock.getsockname()[1]
conn, addr = sock.accept()
print "Connected by", addr

while (True):

    data = str(conn.recv(1024))
    print "Echoing received data:", data
    conn.send("Server received message!")

    # sometimes the data isn't sent if the connection is closed immediately after
    # the call to send(), so wait a second
    import time
    time.sleep(1)
conn.close()
sock.close()
Ejemplo n.º 24
0
"""
Shows how to receive a file over OBEX.
"""

import lightblue

# bind the socket, and advertise an OBEX service
sock = lightblue.socket()
try:
    sock.bind(("", 0))  # bind to 0 to bind to a dynamically assigned channel
    lightblue.advertise("LightBlue example OBEX service", sock, lightblue.OBEX)

    # Receive a file and save it as MyFile.txt.
    # This will wait and block until a file is received.
    print "Waiting to receive file on channel %d..." % sock.getsockname()[1]
    lightblue.obex.recvfile(sock, "MyFile.txt")

finally:
    sock.close()

print "Saved received file to MyFile.txt!"

# Please note:
#
# To use a file through this example, the other device must send the file to
# the correct channel. E.g. if this example prints "Waiting to receive file on
# channel 5..." the remote device must send the file specifically to channel 5.
#
# * But what if you can't specify a channel or service?
#
#   If you can send a file to a specific channel - e.g. by using
Ejemplo n.º 25
0
# Start servos at center point (90 degrees)
base.start(angleToPos(90))
arm.start(angleToPos(90))
forearm.start(angleToPos(90))
gripper.start(angleToPos(10))

# Initialize bluetooth on a specific port
port = 5
s = lightblue.socket()
s.bind(('', port))
s.listen(1)
print 'Listening on port', port

# Advertise bluetooth connection and wait for connection
lightblue.advertise('Arm Launcher', s, lightblue.RFCOMM)
connection, address = s.accept()
print 'Accepted connection from', address

while True:
    data = connection.recv(1024)
    if data == 'Done':
        print 'Done command received'
        break
    try:
        baseAngle, armAngle, forearmAngle, gripperAngle = (float(angle) for angle in data.split(','))
    except:
        continue
    base.ChangeDutyCycle(angleToPos(baseAngle))
    arm.ChangeDutyCycle(angleToPos(armAngle))
    forearm.ChangeDutyCycle(angleToPos(forearmAngle))
Ejemplo n.º 26
0
"""
Shows how to receive a file over OBEX.
"""

import lightblue

# bind the socket, and advertise an OBEX service
sock = lightblue.socket()
try:
    sock.bind(("", 0))    # bind to 0 to bind to a dynamically assigned channel
    lightblue.advertise("LightBlue example OBEX service", sock, lightblue.OBEX)
    
    # Receive a file and save it as MyFile.txt. 
    # This will wait and block until a file is received.
    print "Waiting to receive file on channel %d..." % sock.getsockname()[1]
    lightblue.obex.recvfile(sock, "MyFile.txt")
    
finally:
    sock.close()
    
print "Saved received file to MyFile.txt!"


# Please note:
#
# To use a file through this example, the other device must send the file to
# the correct channel. E.g. if this example prints "Waiting to receive file on 
# channel 5..." the remote device must send the file specifically to channel 5.
# 
# * But what if you can't specify a channel or service?
#