bda3c988be0c662862017920f4ad862ed9249131
[remotepc] / pcremote-server-desktop / connection / .svn / text-base / bluetoothconnectionmanager.py.svn-base
1 # -*- coding: utf-8 -*-
2
3 #  ****************************************************************************
4 #  Copyright (c) 2008 INdT/Fucapi.
5 #  This program is free software: you can redistribute it and/or modify
6 #  it under the terms of the GNU Lesser General Public License as published by
7 #  the Free Software Foundation, either version 3 of the License, or
8 #  (at your option) any later version.
9 #
10 #  This program is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #  GNU Lesser General Public License for more details.
14 #
15 #  You should have received a copy of the GNU Lesser General Public License
16 #  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 #  ============================================================================
19 #  Project Name : PC Remote
20 #  Author       : Jônatas Isvi
21 #  Email        : jonatas.nona@gmail.com
22 #  Reviewer     : 
23 #  Email        :
24 #  Version      : 1.0
25 #  Package      : connection
26 #  Description  : BluetoothConnectionManager
27 #  ============================================================================
28
29 import bluetooth
30 from exceptions import *
31 from genericconnectionmanager import *
32
33 class BluetoothConnectionManager(GenericConnectionManager):
34
35     """ BluetoothConnectionManager
36     manages objects and operations for bluetooth connection.
37     Subclass of GerericConnectionManager.
38     """
39
40     def __init__(self): 
41         GenericConnectionManager.__init__(self)
42         self.sock           =    None
43         self.port           =    None
44         self.address        =    None
45         self.client_sock    =    None
46         self.client_address =    None           
47
48     # fast way to create a simple server
49     def create_server(self, protocol, port):
50         self.create_socket(protocol)
51         self.set_port(port)
52         self.bind()
53         self.listen()
54         self.accept()
55
56     # fast way to create a simple client        
57     def create_client(self, protocol, address, port):
58         self.create_socket(protocol)
59         self.set_address(address)
60         self.set_port(port)
61         self.connect()
62
63     # search for all devices
64     def find_devices(self, time=8):
65         list_devices = bluetooth.discover_devices(lookup_names = True, duration=time)
66         if list_devices:
67             return list_devices
68         else:
69             raise BluetoothConnectionError, "Device were not found." 
70         
71     # search the device port
72     def find_port(self, addr):
73         port = None
74         aux = addr.split(":")
75         if len(aux) == 6:
76             services = bluetooth.find_service(address=addr)
77             for i in range(len(services)):
78                 port = services[i]['port']
79                 
80             if port != None:        
81                 return port
82             else:
83                 raise BluetoothConnectionError, "Port not found."
84                                 
85         else:
86             raise BluetoothConnectionError, "Invalid address."
87         
88     # search device services
89     def find_services(self, service=None, addr=None):
90         if service == None and addr == None:
91             list = bluetooth.find_service()
92             return list
93         elif service != None and addr == None:
94             list = bluetooth.find_service(name=service)
95             if list != []:
96                 return list
97             else:
98                 raise BluetoothConnectionError, "Name of the service does not exist."
99         elif service == None and addr != None:
100             number = addr.split(":")
101             if(len(number) == 6):
102                 list = bluetooth.find_service(address=addr)
103                 if list != []:
104                     return list
105                 else:
106                     raise BluetoothConnectionError, "Services not found."
107             else:
108                 raise BluetoothConnectionError, "Invalid address."
109         elif service != None and addr != None:
110             number = addr.split(":")
111             if(len(number) == 6):
112                 list = bluetooth.find_service(name=service, address=addr)
113                 if list != []:
114                     return list
115                 else:
116                     raise BluetoothConnectionError, "Services not found."
117             else:
118                 raise BluetoothConnectionError, "Invalid address."
119         
120
121     # search the device indicated by name
122     def find_device_address_by_name(self, device_name): 
123         list = bluetooth.discover_devices()
124         addr = None
125                 
126         for address in list:
127             if device_name == bluetooth.lookup_name(address):
128                 addr = address
129                 break
130         if addr:
131             return addr
132         else:
133             raise BluetoothConnectionError, "Device name not found."
134         
135     # search only device names
136     def find_devices_only_names(self):
137         list = self.find_devices()
138         list_names = []
139         for address, names in list:
140             list_names += [names]
141         
142         if list_names:
143             return list_names
144         else:
145             raise BluetoothConnectionError, "Devices were not found."
146
147     # get the client address
148     def get_client_address(self):
149         return self.client_address      
150
151     # set the port to communicate
152     def set_port(self, port):
153         self.port = port
154
155     # get the port to communicate
156     def get_port(self):
157         return self.port
158
159     # set the device address
160     def set_address(self, address):
161         aux = address.split(":")
162         if len(aux) == 6:
163             self.address = address
164         else:
165             raise BluetoothConnectionError, "Invalid address."
166
167     # get the device address
168     def get_address(self):
169         return self.address
170
171     # create a socket with a determinated protocol
172     def create_socket(self, protocol=None):
173         if protocol == 'rfcomm' or protocol == 'RFCOMM':
174             self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
175         elif protocol == 'l2cap' or protocol == 'L2CAP':
176             self.sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
177         else:   
178             raise BluetoothConnectionError, "Undefined Protocol."
179
180     # bind the communication
181     def bind(self):
182         self.sock.bind(("", self.get_port()))
183
184     # just listen the tube, only to server
185     def listen(self):
186         self.sock.listen(1)
187
188     # accept the client communication 
189     def accept(self):
190         self.client_sock, self.client_address = self.sock.accept()
191                 
192     # connect devices
193     def connect(self):
194         self.sock.connect((self.get_address(), self.get_port()))
195
196     # send string message               
197     def send_message(self, msg=None):
198         self.sock.send(msg)
199
200     # receive string message
201     def received_message(self):
202         return self.client_sock.recv(1024)
203
204     # close connection
205     def close(self):
206         if self.sock != None and self.client_sock != None:
207             self.client_sock.close()
208             self.sock.close()   
209         elif self.sock != None and self.client_sock == None:
210             self.sock.close()
211         else:
212             self.client_sock.close()
213