]> rtime.felk.cvut.cz Git - tiny-bt.git/blob - src2/bt_hw.c
Better coding style and evt_array is setted on zeros in init function
[tiny-bt.git] / src2 / bt_hw.c
1 /*
2 *  C Implementation: bt_hw
3 *
4 * Description: hardweare function for sockets
5 *
6 *
7 * Author: root <root@ubuntu>, (C) 2008
8 *
9 * Copyright: See COPYING file that comes with this distribution
10 *
11 */
12
13 #include <sys/socket.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <sys/ioctl.h>
17 #include <errno.h>
18 #include <string.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21 #include <stdint.h>
22 #include "bt_hw.h"
23 #include "hciembeded.h"
24
25 static int hw_dd; /*TODO: this is only for one socket connection */
26
27 int hw_bt_open_device(__u8 dev_id)
28 {
29         struct sockaddr_hci address;
30         int dd;
31         int oldflag;
32         int err;
33         
34         if ((dd = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0) {
35                 perror("socket no created");
36                 return dd; /*it return -1 when socket isn't created*/
37         }
38         
39         oldflag = fcntl(dd, F_GETFL, 0);
40         if (fcntl(dd, F_SETFL, oldflag | O_NONBLOCK) < 0) {
41                 perror("problem with socket flag setting");
42                 err = -1;
43                 goto close_socket;
44         }
45         
46         memset(&address, 0, sizeof(address));
47         address.hci_family = AF_BLUETOOTH;
48         address.hci_dev = dev_id;
49         if (bind(dd, (struct sockaddr *) &address, sizeof(address)) < 0) {
50                 perror("Socket not binded to hci device");
51                 err = -1;
52                 goto close_socket;
53         }
54         
55         if(ioctl(dd, HCISETRAW, 1) < 0) {
56                 perror("error in ioctl HCISETRAW");
57                 err = -1;
58                 goto close_socket;
59         }
60         
61         hw_dd = dd;
62         return dd;
63 close_socket:
64         close(dd);
65         return err;
66 }
67
68 int hw_bt_close_dev()
69 {
70         return close(hw_dd);
71 }
72
73 int hw_bt_write(__u8 *p_array, __u16 length)
74 {
75         while (write(hw_dd, p_array, length) < 0) {
76                 perror("write interrupted");
77                 if (errno == EAGAIN || errno == EINTR)
78                         continue;
79                 return -1;
80                 
81         }
82         return 0;
83 }
84
85 int hw_bt_read(__u8 *p_recbuf)
86 {
87         int len;
88         
89         while ((len = read(hw_dd, p_recbuf,
90                          sizeof(p_recbuf) * HCI_MAX_EVENT_SIZE)) < 0) {
91                 if (errno == EINTR)
92                         continue;
93                 if (errno == EAGAIN)
94                         return 0;
95                 perror("Problem with reading\n");
96                         return -1;
97         }
98         return len;
99 }
100