Uso do Bluetooth com App Inventor e programa C

De MediaWiki do Campus São José
Revisão de 15h12min de 19 de dezembro de 2012 por Eraldo (discussão | contribs) (Criou página com ' =Programa servidor em C= <syntaxhighlight lang=c> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/socket.h> #include <bluetooth/bluetooth.h> #include <bluetooth/rfcomm...')
(dif) ← Edição anterior | Revisão atual (dif) | Versão posterior → (dif)
Ir para navegação Ir para pesquisar

Programa servidor em C

<syntaxhighlight lang=c>

  1. include <stdio.h>
  2. include <unistd.h>
  3. include <stdlib.h>
  4. include <sys/socket.h>
  5. include <bluetooth/bluetooth.h>
  6. include <bluetooth/rfcomm.h>

int main(int argc, char **argv) {

   struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
   char buf[1024] = { 0 };
   int s, client, bytes_read;
   socklen_t opt = sizeof(rem_addr);
   // allocate socket
   if ((s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM))==-1){

printf("Problemas na criação do socket\n"); exit(-1);

   }
   // bind socket to port 1 of the first available 
   // local bluetooth adapter
   loc_addr.rc_family = AF_BLUETOOTH;
   loc_addr.rc_bdaddr = *BDADDR_ANY;
   //str2ba( endereco, &loc_addr.rc_bdaddr );
   loc_addr.rc_channel = (uint8_t) 1;
   if (bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr))==-1){

printf("Problemas no bind\n"); exit(-1);

   }
   printf("Preparando para listen..\n");
   // put socket into listening mode
   if (listen(s, 1)==-1)

printf("Problemas de listen...\n");

   printf("Preparando para accept..\n");
   // accept one connection
   client = accept(s, (struct sockaddr *)&rem_addr, &opt);
   printf("Preparando para leitura..\n");
   ba2str( &rem_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("received [%s]\n", buf);
   }
   // close connection
   close(client);
   close(s);
   return 0;

}

Antes de executar o programa deve-se incluir o serviço de serial:

sdptool add SP