Ejemplo n.º 1
0
static gboolean get_prot_desc_entry(sdp_data_t *entry, int type, guint16 *val)
{
	sdp_data_t *iter;
	int proto;

	if (entry == NULL || !SDP_IS_SEQ(entry->dtd))
		return FALSE;

	iter = entry->val.dataseq;
	if (!(iter->dtd & SDP_UUID_UNSPEC))
		return FALSE;

	proto = sdp_uuid_to_proto(&iter->val.uuid);
	if (proto != type)
		return FALSE;

	if (val == NULL)
		return TRUE;

	iter = iter->next;
	if (iter->dtd != SDP_UINT16)
		return FALSE;

	*val = iter->val.uint16;

	return TRUE;
}
Ejemplo n.º 2
0
static int get_prot_desc_entry(sdp_data_t *entry, int type, guint16 *val)
{
	sdp_data_t *iter;
	int proto;

	if (!entry || !SDP_IS_SEQ(entry->dtd))
		return -1;

	iter = entry->val.dataseq;
	if (!(iter->dtd & SDP_UUID_UNSPEC))
		return -1;

	proto = sdp_uuid_to_proto(&iter->val.uuid);
	if (proto != type)
		return -1;

	if (!val)
		return 0;

	iter = iter->next;
	if (iter->dtd != SDP_UINT16)
		return -1;

	*val = iter->val.uint16;

	return 0;
}
Ejemplo n.º 3
0
static gboolean get_prot_desc_entry(sdp_data_t *entry, int type, guint16 *val)
{
		DBG("");
	sdp_data_t *iter;
	int proto;

	if (!entry || (entry->dtd != SDP_SEQ8 && entry->dtd != SDP_SEQ16 &&
						entry->dtd != SDP_SEQ32))
		return FALSE;

	iter = entry->val.dataseq;
	if (!(iter->dtd & SDP_UUID_UNSPEC))
		return FALSE;

	proto = sdp_uuid_to_proto(&iter->val.uuid);
	if (proto != type)
		return FALSE;

	if (!val)
		return TRUE;

	iter = iter->next;
	if (iter->dtd != SDP_UINT16)
		return FALSE;

	*val = iter->val.uint16;

	return TRUE;
}
Ejemplo n.º 4
0
Archivo: blue.c Proyecto: aelane/TeddyB
int main(void) {
	int i, j, err, sock, dev_id = -1;
	struct hci_dev_info dev_info;
	inquiry_info *info = NULL;
	bdaddr_t target;
	char addr[19] = { 0 };
	char name[248] = { 0 };
	uuid_t uuid = { 0 };
	//Change this to your apps UUID
	char *uuid_str="4e5d48e0-75df-11e3-981f-0800200c9a66";
	uint32_t range = 0x0000ffff;
	sdp_list_t *response_list = NULL, *search_list, *attrid_list;
	int s, loco_channel = -1, status;
	struct sockaddr_rc loc_addr = { 0 };
	pthread_t blueThread;
	
	FILE *fp_Setting;
	char message_Buffer[64];
	char mode[30], language[16], topic[16], topicLen[16];
	size_t len = 16;
	(void) signal(SIGINT, SIG_DFL);
	
	changeTopic_flag = 1;
///////////////////////////MRAA/////////////////////////////	
	//Initialize MRAA
        mraa_init();
        
        //Initialize MRAA Pin 8 == IO8 == GP49
        mraa_gpio_context BearButton = mraa_gpio_init(8);

        //Check for successful initialization or else return
        if (BearButton == NULL){
                printf("Error initializing Push to Talk Pin, IO2\n");
                return -1;
        }
        
		//Set pin to an input
		mraa_gpio_dir(BearButton, MRAA_GPIO_IN);
		printf("Set Pin to an input\n");
 
        
        int curr_pin = mraa_gpio_get_pin(BearButton);
        printf("The current pin number is %d\n", curr_pin);
        int curr_raw = mraa_gpio_get_pin_raw(BearButton);
        printf("The raw pin number is %d\n", curr_raw);

        printf("Going to start reading the button via polling\n");
	
//////////////////////AWS///////////////////////////////////
	aws_flag = 0;	
	IoT_Error_t rc = NONE_ERROR;
	char HostAddress[255] = AWS_IOT_MQTT_HOST;
	char certDirectory[PATH_MAX + 1] = "/AWS/SDK/certs/";
	uint32_t port = AWS_IOT_MQTT_PORT;
	
	MQTTMessageParams Msg = MQTTMessageParamsDefault;
	Msg.qos = QOS_0;
	char cPayload[100];
	Msg.pPayload = (void *) cPayload;
	
	char rootCA[PATH_MAX + 1];
	char clientCRT[PATH_MAX + 1];
	char clientKey[PATH_MAX + 1];
	
	char cafileName[] = AWS_IOT_ROOT_CA_FILENAME;
	char clientCRTName[] = AWS_IOT_CERTIFICATE_FILENAME;
	char clientKeyName[] = AWS_IOT_PRIVATE_KEY_FILENAME;
	
	sprintf(rootCA, "/%s/%s", certDirectory, cafileName);
	sprintf(clientCRT, "/%s/%s", certDirectory, clientCRTName);
	sprintf(clientKey, "/%s/%s", certDirectory, clientKeyName);
	
	MQTTConnectParams connectParams = MQTTConnectParamsDefault;

	connectParams.KeepAliveInterval_sec = 14000;
	connectParams.isCleansession = true;
	connectParams.MQTTVersion = MQTT_3_1_1;
	connectParams.pClientID = "TED";
	connectParams.pHostURL = HostAddress;
	connectParams.port = port;
	connectParams.isWillMsgPresent = false;
	connectParams.pRootCALocation = rootCA;
	connectParams.pDeviceCertLocation = clientCRT;
	connectParams.pDevicePrivateKeyLocation = clientKey;
	connectParams.mqttCommandTimeout_ms = 2000;
	connectParams.tlsHandshakeTimeout_ms = 5000;
	connectParams.isSSLHostnameVerify = true;// ensure this is set to true for production
	connectParams.disconnectHandler = disconnectCallbackHandler;
	
	MQTTPublishParams CurriculumParams = MQTTPublishParamsDefault;
	CurriculumParams.pTopic = "Bear/Curriculum/Request";
	
	
	MQTTPublishParams MetricsParams = MQTTPublishParamsDefault;
	MetricsParams.pTopic = "Bear/Curriculum/Metrics";

///////////////////////////////////////////////////////////////////////////////////////
	dev_id = hci_get_route(NULL);
	if (dev_id < 0) {
		perror("No Bluetooth Adapter Available");
		exit(1);
	}

	if (hci_devinfo(dev_id, &dev_info) < 0) {
		perror("Can't get device info");
		exit(1);
	}



	sock = hci_open_dev( dev_id );
	if (sock < 0) {
		perror("HCI device open failed");
		free(info);
		exit(1);
	}

	
	if( !str2uuid( uuid_str, &uuid ) ) {
		perror("Invalid UUID");
		free(info);
		exit(1);
	}

	do {
		printf("Scanning ...\n");
		
			sdp_session_t *session;
			int retries;
			int foundit, responses;
			str2ba(TABLET_ADDRESS,&target); 
			memset(name, 0, sizeof(name));
			if (hci_read_remote_name(sock, &target, sizeof(name), name, 0) < 0){
				strcpy(name, "[unknown]");
			}
			
			printf("Found %s  %s, searching for the the desired service on it now\n", addr, name);
			// connect to the SDP server running on the remote machine
sdpconnect:
			session = 0; retries = 0;
			while(!session) {
				session = sdp_connect( BDADDR_ANY, &target, SDP_RETRY_IF_BUSY );
				if(session) break;
				if(errno == EALREADY && retries < 5) {
					perror("Retrying");
					retries++;
					sleep(1);
					continue;
				}
				break;
			}
			if ( session == NULL ) {
				perror("Can't open session with the device");
				continue;
			}
			search_list = sdp_list_append( 0, &uuid );
			attrid_list = sdp_list_append( 0, &range );
			err = 0;
			err = sdp_service_search_attr_req( session, search_list, SDP_ATTR_REQ_RANGE, attrid_list, &response_list);
			sdp_list_t *r = response_list;
			sdp_record_t *rec;
			// go through each of the service records
			foundit = 0;
			responses = 0;
			for (; r; r = r->next ) {
				responses++;
				rec = (sdp_record_t*) r->data;
				sdp_list_t *proto_list;
					
				// get a list of the protocol sequences
				if( sdp_get_access_protos( rec, &proto_list ) == 0 ) {
				sdp_list_t *p = proto_list;

					// go through each protocol sequence
					for( ; p ; p = p->next ) {
						sdp_list_t *pds = (sdp_list_t*)p->data;

						// go through each protocol list of the protocol sequence
						for( ; pds ; pds = pds->next ) {

							// check the protocol attributes
							sdp_data_t *d = (sdp_data_t*)pds->data;
							int proto = 0;
							for( ; d; d = d->next ) {
								switch( d->dtd ) { 
									case SDP_UUID16:
									case SDP_UUID32:
									case SDP_UUID128:
											proto = sdp_uuid_to_proto( &d->val.uuid );
											break;
									case SDP_UINT8:
										if( proto == RFCOMM_UUID ) {
												printf("rfcomm channel: %d\n",d->val.int8);
												loco_channel = d->val.int8;
												foundit = 1;
										}
										break;
								}
							}
						}
						sdp_list_free( (sdp_list_t*)p->data, 0 );
					}
					sdp_list_free( proto_list, 0 );

				}
				if (loco_channel > 0)
					break;

			}
			printf("No of Responses %d\n", responses);
			if ( loco_channel > 0 && foundit == 1 ) {
				printf("Found service on this device, now gonna blast it with dummy data\n");
				s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
				loc_addr.rc_family = AF_BLUETOOTH;
				loc_addr.rc_channel = loco_channel;
				loc_addr.rc_bdaddr = *(&target);
				status = connect(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
				if( status < 0 ) {
					perror("uh oh");
				}

				
				rc = pthread_create(&blueThread, NULL, threadListen, (void *)s);
					if (rc){
						printf("ERROR: %d\n", rc);
						exit(1);
					}
				MQTTSubscribeParams subParams = MQTTSubscribeParamsDefault;
				//Loop through trying to subscribe to AWS incase the first attempt fails, so will keep trying until the app sends the edison proper network info.
				do{
					INFO("Connecting...");
					rc = aws_iot_mqtt_connect(&connectParams);
					
					if (NONE_ERROR != rc) {
						ERROR("Error(%d) connecting to %s:%d", rc, connectParams.pHostURL, connectParams.port);
					}
					
					subParams.mHandler = MQTTcallbackHandler;
					subParams.pTopic = "Bear/Curriculum/Response";
					subParams.qos = QOS_0;

					if (NONE_ERROR == rc) {
						INFO("Subscribing...");
						rc = aws_iot_mqtt_subscribe(&subParams);
						if (NONE_ERROR != rc) {
							ERROR("Error subscribing");
						}
					}
					sleep(1);
				}while(NONE_ERROR != rc);
				aws_flag = 1;
//////////////////////////Start of teaching stuff//////////////////////////////////////////
				do {
					
				
					if(changeTopic_flag){
					
						sprintf(cPayload, "{\"BearID\":\"%s\"}",BEARID);
						Msg.PayloadLen = strlen(cPayload) + 1;
						CurriculumParams.MessageParams = Msg;
						rc = aws_iot_mqtt_publish(&CurriculumParams);
						while(rc == NONE_ERROR && changeTopic_flag){
							rc = aws_iot_mqtt_yield(100);
							INFO("-->sleep");
							sleep(1);
						}								
						changeTopic_flag = 0;
					}
					
					
					fp_Setting = fopen("/Curriculum/BearSettings.txt", "r");
					fgets(language, sizeof(language), fp_Setting);
					fgets(mode, sizeof(mode), fp_Setting);
					fgets(topic, sizeof(topic), fp_Setting);
					fgets(topicLen, sizeof(topicLen), fp_Setting);
					language[strlen(language)-1] = 0;
					mode[strlen(mode)-1] = 0;
					topic[strlen(topic)-1] = 0;
					topicLen[strlen(topicLen)-1] = 0;
					fclose(fp_Setting);

					//Wait for the tablet to tell the edison to start the lesson
					while(strcmp(threadMessage, "learning")){
						printf("Waiting for learning, got: %s\n", threadMessage);
						if(!strcmp(threadMessage, "crash")){
							memset(threadMessage, 0, sizeof(threadMessage));
							goto CRASHED;
						}
						memset(threadMessage, 0, sizeof(threadMessage));
						sleep(1);
					}

					
					printf("Current Mode: %s\n", mode);
					printf("Current Language: %s\n", language);
					printf("Current topic: %s\n", topic);

					//Call a different function depending on what teaching mode it is, also write to the tablet based on the topic info and lesson
					if(!strcmp(mode, "Repeat After Me")){
						sprintf(message_Buffer,"%s,1,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						if(!strcmp(language, "English")){
							status = repeat_after_me_english(s, topic, MetricsParams, BearButton);
						}
						else{
							status = repeat_after_me_foreign(s, language, topic, MetricsParams, BearButton);
						}
					}
					else if(!strcmp(mode, "English to Foreign")){
						sprintf(message_Buffer,"%s,3,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						status = english_to_foreign(s, language, topic, MetricsParams, BearButton);
					}
					else if(!strcmp(mode, "Foreign to English")){
						sprintf(message_Buffer,"%s,2,%s",language, topicLen);
						status = write(s,message_Buffer,sizeof(message_Buffer));
						status = foreign_to_english(s, language, topic, MetricsParams, BearButton);
					}
					
					
					changeTopic_flag = 1;
					printf("Changing Topic");
					sleep(5);
				} while (status > 0);
CRASHED:
				printf("\nBluetooth Disconnected\n");
				close(s);
				sdp_record_free( rec );
			}

			sdp_close(session);
			if (loco_channel > 0) {
				goto sdpconnect;
				//break;
			}
		sleep(1);
	} while (1);

	printf("Exiting...\n");
}
int main(int argc, char **argv)
{
    /* on Samsung Galaxy S3
    Service Name: LIVIO_CONNECT
    Service RecHandle: 0x1000a
    Service Class ID List:
      UUID 128: fbe4be12-374a-486b-a473-24e39408a24d
    Protocol Descriptor List:
      "L2CAP" (0x0100)
      "RFCOMM" (0x0003)
    */ 
   uint8_t svc_uuid_int[] = { 0xfb, 0xe4, 0xbe, 0x12, 0x37, 0x4a, 0x48, 0x6b,
                               0xa4, 0x73, 0x24, 0xe3, 0x94, 0x08, 0xa2, 0x4d}; 
    uuid_t svc_uuid;
    int err;
    bdaddr_t target;
    sdp_list_t *response_list = NULL, *search_list, *attrid_list;
    sdp_session_t *session = 0;

    if(argc < 2)
    {
      printf("usage: %s <bt-addr> \n",argv[0]);
			exit(1);
    }

    str2ba( argv[1], &target );

    // connect to the SDP server running on the remote machine
    session = sdp_connect( BDADDR_ANY, &target, SDP_RETRY_IF_BUSY );

    // specify the UUID of the application we're searching for
    sdp_uuid128_create( &svc_uuid, &svc_uuid_int );
    search_list = sdp_list_append( NULL, &svc_uuid );
    // specify that we want a list of all the matching applications' attributes
    uint32_t range = 0x0000ffff;
    attrid_list = sdp_list_append( NULL, &range );
		printf("starting search...\n");
    // get a list of service records that have UUID 0xabcd
    err = sdp_service_search_attr_req( session, search_list, \
            SDP_ATTR_REQ_RANGE, attrid_list, &response_list);


    sdp_list_t *r = response_list;
		printf("search completed\n");
    // go through each of the service records
    for (; r; r = r->next ) {
        sdp_record_t *rec = (sdp_record_t*) r->data;
        sdp_list_t *proto_list;
        
        // get a list of the protocol sequences
        if( sdp_get_access_protos( rec, &proto_list ) == 0 ) {
        sdp_list_t *p = proto_list;

        // go through each protocol sequence
        for( ; p ; p = p->next ) {
            sdp_list_t *pds = (sdp_list_t*)p->data;

            // go through each protocol list of the protocol sequence
            for( ; pds ; pds = pds->next ) {

                // check the protocol attributes
                sdp_data_t *d = (sdp_data_t*)pds->data;
                int proto = 0;
                for( ; d; d = d->next ) {
                    switch( d->dtd ) { 
                        case SDP_UUID16:
                        case SDP_UUID32:
                        case SDP_UUID128:
                            proto = sdp_uuid_to_proto( &d->val.uuid );
                            printf("\tproto: 0x%x\n", proto);
                            break;
                        case SDP_UINT8:
                            if( proto == RFCOMM_UUID ) {
                                printf("rfcomm channel: %d\n",d->val.int8);
                            }
                            break;
                    }
                }
            }
            sdp_list_free( (sdp_list_t*)p->data, 0 );
        }
        sdp_list_free( proto_list, 0 );

        }

        printf("found service record 0x%x\n", rec->handle);
        sdp_record_free( rec );
    }

    sdp_close(session);
}
Ejemplo n.º 6
0
uint8_t sdp_lookup_uuid_rfcomm_channel(bdaddr_t *addr, uint16_t wanted_uuid)
{
	uuid_t uuid;
	sdp_list_t *sdp_res, *sdp_search, *sdp_wanted_attr;
	sdp_session_t *sdp_session;
	uint32_t wanted_attr_range = 0xFFFF;
	bdaddr_t bdaddr = *addr;
	uint8_t rfcomm_channel = 0;
	int err;

	sdp_session = sdp_connect(BDADDR_ANY, &bdaddr, SDP_RETRY_IF_BUSY);

	if (NULL != sdp_session)
		printf("Connected to target SDP server\n");

	sdp_uuid16_create(&uuid, wanted_uuid);

	sdp_search = sdp_list_append( NULL, &uuid );
    	sdp_wanted_attr = sdp_list_append( NULL, &wanted_attr_range );

	// get a list of service records that have UUID 0xabcd
	err = sdp_service_search_attr_req(sdp_session, sdp_search, SDP_ATTR_REQ_RANGE, sdp_wanted_attr, &sdp_res);
	
	printf("SDP service search result: %p\n", sdp_res);

	sdp_list_t *r = sdp_res;

	// go through each of the service records
	for (; r; r = r->next ) 
	{
		sdp_record_t *rec = (sdp_record_t*) r->data;
		sdp_list_t *proto_list;
		
		// get a list of the protocol sequences
		if( sdp_get_access_protos( rec, &proto_list ) == 0 ) {
		sdp_list_t *p = proto_list;

		// go through each protocol sequence
		for( ; p ; p = p->next ) {
		    sdp_list_t *pds = (sdp_list_t*)p->data;

		    // go through each protocol list of the protocol sequence
		    for( ; pds ; pds = pds->next ) {

		        // check the protocol attributes
		        sdp_data_t *d = (sdp_data_t*)pds->data;
		        int proto = 0;
		        for( ; d; d = d->next ) {
		            switch( d->dtd ) { 
		                case SDP_UUID16:
		                case SDP_UUID32:
		                case SDP_UUID128:
		                    proto = sdp_uuid_to_proto( &d->val.uuid );
					printf("Proto: %d\n", proto);
		                    break;
		                case SDP_UINT8:
		                    if( proto == RFCOMM_UUID ) 
				    {
					rfcomm_channel = d->val.int8;
		                        printf("Found RFCOMM channel: %d\n",d->val.int8);
		                    }
		                    break;
		            }
		        }
		    }

		    sdp_list_free( (sdp_list_t*)p->data, 0 );
		}
		
		sdp_list_free( proto_list, 0 );

		}

		sdp_record_free( rec );
	}

	sdp_close(sdp_session);

	return rfcomm_channel;
}
Ejemplo n.º 7
0
int discover_sdp(char* remote) {
  int channel = 0;

  // returns rfcomm channel
  uuid_t svc_uuid;
  int err;
  bdaddr_t target;
  sdp_list_t *response_list = NULL, *search_list, *attrid_list;
  sdp_session_t *session = 0;
  
  str2ba( remote , &target );
  
  // connect to the SDP server running on the remote machine
  if (D) printf("connecting..\n");
  session = sdp_connect( BDADDR_ANY, &target, SDP_RETRY_IF_BUSY );
  
  // specify the UUID of the application we're searching for
  if (D) printf("uuid\n");
  sdp_uuid128_create( &svc_uuid, &service_uuid_int );
  search_list = sdp_list_append( NULL, &svc_uuid );
  
  // specify that we want a list of all the matching applications' attributes
  uint32_t range = 0x0000ffff;
  attrid_list = sdp_list_append( NULL, &range );
  
  // get a list of service records that have UUID 0xabcd
  err = sdp_service_search_attr_req( session, search_list,	\
				     SDP_ATTR_REQ_RANGE, attrid_list, &response_list);
  sdp_list_t *r = response_list;
  
  // go through each of the service records
  for (; r; r = r->next ) {
    sdp_record_t *rec = (sdp_record_t*) r->data;
    sdp_list_t *proto_list;
    
    // get a list of the protocol sequences
    if( sdp_get_access_protos( rec, &proto_list ) == 0 ) {
      sdp_list_t *p = proto_list;
      
      // go through each protocol sequence
      for( ; p ; p = p->next ) {
	sdp_list_t *pds = (sdp_list_t*)p->data;
	    
	// go through each protocol list of the protocol sequence
	for( ; pds ; pds = pds->next ) {

	  // check the protocol attributes
	  sdp_data_t *d = (sdp_data_t*)pds->data;
	  int proto = 0;
	  for( ; d; d = d->next ) {
	    switch( d->dtd ) { 
	    case SDP_UUID16:
	    case SDP_UUID32:
	    case SDP_UUID128:
	      proto = sdp_uuid_to_proto( &d->val.uuid );
	      break;
	    case SDP_UINT8:
	      if( proto == RFCOMM_UUID ) {
		printf("rfcomm channel: %d\n",d->val.int8);
                channel = (int)d->val.int8;
	      }
	      break;
	    }
	  }
	}
	sdp_list_free( (sdp_list_t*)p->data, 0 );
      }
      sdp_list_free( proto_list, 0 );

    }

    printf("found service record 0x%x\n", rec->handle);
    sdp_record_free( rec );
  }

  sdp_close(session);
  return channel;
}
Ejemplo n.º 8
0
void *main_bluetooth(void *arg) {
    int i, err, sock, dev_id = -1;
    int num_rsp = 0, max_rsp = 5, flags = 0, length = 4;  /* [1.28 *<length>]seconds [1.28*4 = 5.12] seconds */
    char addr[19] = {0};
    char cmd[100], cmd1[50];
    char name[248] = {0}, bt_mac[19] = "00:00:00:00:00:00";
    uuid_t uuid = {0};
    int application_id = (int) *(int *) arg;
    char uuid_str[50];
    FILE *fd = NULL;
    if (application_id == 2) {
        printf("\nOpen application: Android Locomate Messaging\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a901");
    }
    else if (application_id == 3) {
        printf("\nOpen application: Spat Andriod Application\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a903");
    }
    else if (application_id == 4) {
        printf("\nOpen application: Bluetooth CAN application\n");
        strcpy(uuid_str, "00001101-0000-1000-8000-00805F9B34FB");
        fd = popen("cat /var/can.conf | grep BTCAN_MAC= | cut -d '=' -f 2", "r");
        if (fd != NULL) {
            fscanf(fd, "%s", bt_mac);
            pclose(fd);
            printf("Mac from conf file: %s\n", bt_mac);
        }
    }
    else {
        printf("\nOpen application: Locomate Safety Application\n");
        strcpy(uuid_str, "66841278-c3d1-11df-ab31-001de000a902");
    }
    uint32_t range = 0x0000ffff;
    sdp_list_t *response_list = NULL, *search_list, *attrid_list;
    int status;
    int responses;
    int retries = 0;
    struct sockaddr_rc loc_addr = {0};
    signal(SIGINT, (void *) sig_int);

    /* find the bluetooth device is available or not */
    sprintf(cmd, "/usr/local/bin/hciconfig hci0 up");
    system(cmd);
    for (retries = 0; retries < 5; retries++) {
        dev_id = hci_get_route(NULL);
        if (dev_id < 0) {
            perror("No Bluetooth Adapter Available\n");
            sprintf(cmd, "/usr/local/bin/hciconfig hci0 down");
            system(cmd);
            sprintf(cmd1, "/usr/local/bin/hciconfig hci0 up");
            system(cmd1);
            printf("\nretry getting adapter : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -1;
        return NULL;
    }

    for (retries = 0; retries < 5; retries++) { //check for the socket
        sock = hci_open_dev(dev_id);
        if (sock < 0) {
            perror("HCI device open failed");
            retries++;
            printf("\nretries sock : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -2;
        return NULL;
    }

    for (retries = 0; retries < 5; retries++) { //check uuid is correct or not
        if (!str2uuid(uuid_str, &uuid)) {
            perror("Invalid UUID");
            retries++;
            printf("\nretries str2 uuid : %d\n", retries);
        }
        else
            break;
    }
    if (retries == 5) {
        Btooth_forward = -3;
        return NULL;
    }

    //printf("\nBluetooth Adapter Found \n");
    info = (inquiry_info *) malloc(MAX_RSP * sizeof(inquiry_info));

    while (1) { // loop to check and establish connection with other device

        while (connection_established == FALSE) {
            bzero(info, (MAX_RSP * sizeof(inquiry_info)));

            num_rsp = hci_inquiry(dev_id, length, max_rsp, NULL, &info,
                                  flags); // inquire for how many devices are available
            if (num_rsp < 0) {
                perror("Inquiry failed");
                sched_yield();
                sleep(1);
                continue;
            }
            printf("Inquiry devices found : %d\n", num_rsp);

            loco_channel = -1;
            for (i = 0; i < num_rsp; i++) {
                sdp_session_t *session;
                ba2str(&(info + i)->bdaddr, addr);
                printf("\nFound Mac: %s ", addr);
                if (application_id == 4 && strcmp("00:00:00:00:00:00", bt_mac)) // check for appid and mac_id
                if (strcasecmp(addr, bt_mac))
                    continue;
                memset(name, 0, sizeof(name));

                if (hci_read_remote_name(sock, &(info + i)->bdaddr, sizeof(name), name, 8000) < 0) //get devices by name
                    strcpy(name, "[unknown]");


                printf("Found : %s name : [[ %s ]]\n", addr, name);
                // connect to the SDP server running on the remote machine
                session = NULL;
                retries = 0;
                while (!session) {
                    session = sdp_connect(BDADDR_ANY, &(info + i)->bdaddr, 0);
                    if (session) break;
                    if (errno != 0) {
                        fprintf(stderr, "sdp_connect failed error no %d : %s \n", errno, strerror(errno));
                    }
                    if ((retries < 2) && ((errno == EALREADY))) {
                        retries++;
                        fprintf(stderr, "Retry sdp_connect %d\t", retries);
                        sched_yield();
                        usleep(300000);//300 ms
                        continue; //continue till 3 times
                    }
                    break;
                } /* while(!session) */
                if (session == NULL) {
                    if (i < (num_rsp - 1))
                        printf("Trying next device -> %d\n", i + 2);
                    continue;
                }

                search_list = NULL;
                attrid_list = NULL;
                response_list = NULL;

                search_list = sdp_list_append(NULL, &uuid); //append list of uuids
                attrid_list = sdp_list_append(NULL, &range); // append list of attributes
                err = 0;
                err = sdp_service_search_attr_req(session, search_list, SDP_ATTR_REQ_RANGE, attrid_list,
                                                  &response_list); //search for attributes from list
                sdp_list_t *r = response_list;
                responses = 0;


                // go through each of the service records
                for (; r; r = r->next) {
                    responses++;
                    sdp_record_t *rec = (sdp_record_t *) r->data;
                    sdp_list_t *proto_list;

                    // get a list of the protocol sequences
                    if (sdp_get_access_protos(rec, &proto_list) == 0) {
                        sdp_list_t *p = proto_list;

                        // go through each protocol sequence
                        for (; p; p = p->next) {
                            sdp_list_t *pds = (sdp_list_t *) p->data;

                            // go through each protocol list of the protocol sequence
                            for (; pds; pds = pds->next) {

                                // check the protocol attributes
                                sdp_data_t *d = (sdp_data_t *) pds->data;
                                int proto = 0;
                                for (; d; d = d->next) {
                                    switch (d->dtd) {
                                        case SDP_UUID16:
                                        case SDP_UUID32:
                                        case SDP_UUID128:
                                            proto = sdp_uuid_to_proto(&d->val.uuid);
                                            break;
                                        case SDP_UINT8:
                                            if (proto == RFCOMM_UUID) {
                                                printf("rfcomm channel: %d\n", d->val.int8);
                                                loco_channel = d->val.int8;
                                            }
                                            break;
                                    } /* switch(t->dtd) */
                                } /* for( ; d; d = d->next) */
                            } /* for( ; pds ; pds = pds->next) */
                            sdp_list_free((sdp_list_t *) p->data, 0);
                        } /* for( ; p; p = p->next) */
                        sdp_list_free(proto_list, 0);
                    } /* if(sdp_get_access_protos(rec, &proto_list)) */
                    sdp_record_free(rec);
                    if (loco_channel > 0) {
                        break;
                    }
                } /* for (; r; r = r->next) */


                sdp_list_free(response_list, 0);
                sdp_list_free(search_list, 0);
                sdp_list_free(attrid_list, 0);
                printf("No of services= %d on device %d \n", responses, i + 1);
                if (loco_channel > 0) {
                    // printf("Found Locomate Safety Application on device: name [%s], sending message now\n",name);
                    btooth_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
                    loc_addr.rc_family = AF_BLUETOOTH;
                    loc_addr.rc_channel = loco_channel;
                    loc_addr.rc_bdaddr = (info + i)->bdaddr;
                    status = connect(btooth_socket, (struct sockaddr *) &loc_addr, sizeof(loc_addr));
                    if (status < 0) {
                        perror("\nuh oh: Btooth socket not created\n");
                        Btooth_forward = -5;
                    }
                    else {
                        sdp_close(session);
                        Btooth_forward = 1;
                        connection_established = TRUE;
                        break;
                    }
                }
                sdp_close(session);
            } /* for (i = 0; i < num_rsp; i++) */
            if (connection_established == FALSE) {
                printf("Scanning again\n");
                //sprintf(cmd, "/usr/local/bin/hciconfig hci0 down");
                //system(cmd);
                sprintf(cmd1, "/usr/local/bin/hciconfig hci0 up");
                system(cmd1);
                sched_yield();
                sleep(1);
            }
            else {
                printf("***Connection established***\n");
            }
        } /* while(connection_established == ...) */
        sched_yield();
        sleep(3); // wait for 3seconds, before next check
    }

}