/* * (c) 2011 Siegen, Germany by Nils Faerber * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. */ #include #include #include #include #include #include #include #include #include #include #include #include #include int open_socket(bdaddr_t *bdaddr, uint8_t channel) { struct sockaddr_rc addr; int sk, opt; sk = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); if (sk < 0) { fprintf(stderr, "Can't create socket: %s (%d)\n", strerror(errno), errno); return -1; } memset(&addr, 0, sizeof(addr)); addr.rc_family = AF_BLUETOOTH; bacpy(&addr.rc_bdaddr, BDADDR_ANY); if (bind(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { fprintf(stderr, "Can't bind socket: %s (%d)\n", strerror(errno), errno); close(sk); return -1; } /* Set link mode */ opt = 0; opt |= RFCOMM_LM_MASTER; opt |= RFCOMM_LM_AUTH; /* opt |= RFCOMM_LM_ENCRYPT; opt |= RFCOMM_LM_SECURE; */ if (opt && setsockopt(sk, SOL_RFCOMM, RFCOMM_LM, &opt, sizeof(opt)) < 0) { fprintf(stderr, "Can't set RFCOMM link mode: %s (%d)", strerror(errno), errno); close(sk); return -1; } memset(&addr, 0, sizeof(addr)); addr.rc_family = AF_BLUETOOTH; bacpy(&addr.rc_bdaddr, bdaddr); addr.rc_channel = channel; if (connect(sk, (struct sockaddr *) &addr, sizeof(addr)) < 0) { fprintf(stderr, "Can't connect: %s (%d)\n", strerror(errno), errno); close(sk); return -1; } return sk; } static void mbaswap(bdaddr_t *dst, const bdaddr_t *src) { register unsigned char *d = (unsigned char *) dst; register const unsigned char *s = (const unsigned char *) src; register int i; for (i = 0; i < 6; i++) d[i] = s[5-i]; } static int mbachk(const char *str) { if (!str) return -1; if (strlen(str) != 17) return -1; while (*str) { if (!isxdigit(*str++)) return -1; if (!isxdigit(*str++)) return -1; if (*str == 0) break; if (*str++ != ':') return -1; } return 0; } int str2ba(const char *str, bdaddr_t *ba) { bdaddr_t b; int i; if (mbachk(str) < 0) { memset(ba, 0, sizeof(*ba)); return -1; } for (i = 0; i < 6; i++, str += 3) b.b[i] = strtol(str, NULL, 16); mbaswap(ba, &b); return 0; }