commit do server
[remotepc] / pcremote-server / connection / bluetoothconnectionmanager.py
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
37     manages objects and operations for bluetooth connection.
38     Subclass of GerericConnectionManager.
39     """
40
41     def __init__(self): 
42         GenericConnectionManager.__init__(self)
43         self.sock           =    None
44         self.port           =    None
45         self.address        =    None
46         self.client_sock    =    None
47         self.client_address =    None           
48
49     # fast way to create a simple server
50     def create_server(self, protocol, port):
51         self.create_socket(protocol)
52         self.set_port(port)
53         self.bind()
54         self.listen()
55         self.accept()
56
57     # fast way to create a simple client        
58     def create_client(self, protocol, address, port):
59         self.create_socket(protocol)
60         self.set_address(address)
61         self.set_port(port)
62         self.connect()
63
64     # search for all devices
65     def find_devices(self, time=8):
66         list_devices = bluetooth.discover_devices(lookup_names = True, duration=time)
67         if list_devices:
68             print list_devices
69             return list_devices
70         else:
71             raise BluetoothConnectionError, "Device were not found." 
72         
73     # search the device port
74     def find_port(self, addr):
75         port = None
76         aux = addr.split(":")
77         if len(aux) == 6:
78             services = bluetooth.find_service(address=addr)
79             for i in range(len(services)):
80                 port = services[i]['port']
81                 
82             if port != None:        
83                 return port
84             else:
85                 raise BluetoothConnectionError, "Port not found."
86                                 
87         else:
88             raise BluetoothConnectionError, "Invalid address."
89         
90     # search device services
91     def find_services(self, service=None, addr=None):
92         if service == None and addr == None:
93             list = bluetooth.find_service()
94             return list
95         elif service != None and addr == None:
96             list = bluetooth.find_service(name=service)
97             if list != []:
98                 return list
99             else:
100                 raise BluetoothConnectionError, "Name of the service does not exist."
101         elif service == None and addr != None:
102             number = addr.split(":")
103             if(len(number) == 6):
104                 list = bluetooth.find_service(address=addr)
105                 if list != []:
106                     return list
107                 else:
108                     raise BluetoothConnectionError, "Services not found."
109             else:
110                 raise BluetoothConnectionError, "Invalid address."
111         elif service != None and addr != None:
112             number = addr.split(":")
113             if(len(number) == 6):
114                 list = bluetooth.find_service(name=service, address=addr)
115                 if list != []:
116                     return list
117                 else:
118                     raise BluetoothConnectionError, "Services not found."
119             else:
120                 raise BluetoothConnectionError, "Invalid address."
121         
122
123     # search the device indicated by name
124     def find_device_address_by_name(self, device_name): 
125         list = bluetooth.discover_devices()
126         addr = None
127                 
128         for address in list:
129             if device_name == bluetooth.lookup_name(address):
130                 addr = address
131                 break
132         if addr:
133             return addr
134         else:
135             raise BluetoothConnectionError, "Device name not found."
136         
137     # search only device names
138     def find_devices_only_names(self):
139         list = self.find_devices()
140         list_names = []
141         for address, names in list:
142             list_names += [names]
143         
144         if list_names:
145             return list_names
146         else:
147             raise BluetoothConnectionError, "Devices were not found."
148
149     # get the client address
150     def get_client_address(self):
151         return self.client_address      
152
153     # set the port to communicate
154     def set_port(self, port):
155         self.port = port
156
157     # get the port to communicate
158     def get_port(self):
159         return self.port
160
161     # set the device address
162     def set_address(self, address):
163         aux = address.split(":")
164         if len(aux) == 6:
165             self.address = address
166         else:
167             raise BluetoothConnectionError, "Invalid address."
168
169     # get the device address
170     def get_address(self):
171         return self.address
172
173     # create a socket with a determinated protocol
174     def create_socket(self, protocol=None):
175         if protocol == 'rfcomm' or protocol == 'RFCOMM':
176             self.sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
177         elif protocol == 'l2cap' or protocol == 'L2CAP':
178             self.sock = bluetooth.BluetoothSocket(bluetooth.L2CAP)
179         else:   
180             raise BluetoothConnectionError, "Undefined Protocol."
181
182     # bind the communication
183     def bind(self):
184         self.sock.bind(("", self.get_port()))
185
186     # just listen the tube, only to server
187     def listen(self):
188         self.sock.listen(1)
189
190     # accept the client communication 
191     def accept(self):
192         self.client_sock, self.client_address = self.sock.accept()
193                 
194     # connect devices
195     def connect(self):
196         self.sock.connect((self.get_address(), self.get_port()))
197
198     # send string message               
199     def send_message(self, msg=None):
200         self.sock.send(msg)
201
202     # receive string message
203     def received_message(self):
204         return self.client_sock.recv(1024)
205
206     # close connection
207     def close(self):
208         if self.sock != None and self.client_sock != None:
209             self.client_sock.close()
210             self.sock.close()   
211         elif self.sock != None and self.client_sock == None:
212             self.sock.close()
213         else:
214             self.client_sock.close()
215