Skip to content

Instantly share code, notes, and snippets.

@bertrandmartel
Created October 14, 2020 23:29
Show Gist options
  • Save bertrandmartel/d3eb069740b5e4263c944025e8742499 to your computer and use it in GitHub Desktop.
Save bertrandmartel/d3eb069740b5e4263c944025e8742499 to your computer and use it in GitHub Desktop.
#compile with : g++ -o scan scan.cpp -lbluetooth
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <cerrno>
int main(int argc, char **argv)
{
char buf[1024] = {0};
int bluetoothSocket, client, bytes_read;
struct sockaddr_rc loc_addr = {0};
struct sockaddr_rc client_addr = {0};
socklen_t opt = sizeof(client_addr);
bdaddr_t my_bdaddr_any = {0, 0, 0, 0, 0, 0};
bluetoothSocket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = (bdaddr_t)my_bdaddr_any;
loc_addr.rc_channel = (uint8_t) 1;
int ret = -1;
if ((ret = bind(bluetoothSocket, (struct sockaddr *)&loc_addr, sizeof(loc_addr))) == -1)
{
printf("Bluetooth bind failed. ERRNO=%d\n", errno);
char *errorMessage = strerror_r(errno, buf, 1024);
printf("%s\n", errorMessage);
return 0;
}
ret = -1;
if((ret = listen(bluetoothSocket, 1)) == -1)
{
printf("Bluetooth listen failed. ERRNO=%d\n", errno);
char *errorMessage = strerror_r(errno, buf, 1024);
printf("%s\n", errorMessage);
return 0;
}
bool stopThread = false;
while (stopThread == false)
{
printf("Waiting for new client to connect.\n");
client = accept(bluetoothSocket, (struct sockaddr *)&client_addr, &opt);
if (client == -1)
{
printf("Bluetooth connect failed.\n");
close(client);
usleep(1000000);
//delay(1000);
continue;
}
printf("Bluetooth connection made.\n");
ba2str(&loc_addr.rc_bdaddr, buf);
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
// read data from the client
bytes_read = read(client, buf, sizeof(buf));
if (bytes_read > 0)
{
printf("Bluetooth bytes received [%s]\n", buf);
for (int i = 0; i < bytes_read;i++){
printf("%d\n", buf[i]); }
}
}
close(client);
close(bluetoothSocket);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment