1

Intel Edison で動作する C 言語で「レース ボックス」を作成しています。Bluetooth チャットに基づく Android アプリで Bluetooth データを送受信できます。すべて正常に動作します。送受信できます。接続を失って再取得すると、接続が回復し、C プログラムから Android アプリにデータが流れます。再接続すると、CからAndroidにデータを送信できなくなることを除けば、すべて問題ありません。これを read ステートメントまでたどりましたが、 while ループを終了しないため、値を返さないと思います。具体的には、次の行:

while(bluetooth_up == 1 && (read(client, &aa, 1) == -1) ){

bluetooth_up == 0 を知っていても終了しません (別のスレッドが bluetooth_up を出力し、bluetooth がダウンしている場合は 0 です)。私の結論は、読み取りがブロックされているということでしたので、次の行でそれを修正しようとしました

fcntl(s, F_SETFL,sock_flags|O_NONBLOCK);

Bluetooth 接続は、Bluetooth 書き込みスレッドにあります。しかし、私が言ったように、bluetooth_up が 0 のときにこの while ループが終了しないことを除いて、すべてが機能します。

私が理解できるのは、読み取りがブロックされていることだけであり、ブロックしないようにする方法がわからないため、-1 が返され、while ループは bluetooth_up == 0 を認識して終了します。

bluetooth_up のグローバル定義は次のとおりです。

volatile int bluetooth_up = 0;

堅牢である必要があり、ブルートゥースを再び機能させるためにレースボックスの電源を入れ直す必要はありませんが、これは機能します。

    void *blueRead(void *arg){
    blue_read_up = 1;
    char aa;
    char buffer[500];
    int idx = 0;
    printf("\nBlue Read started\n");
    fcntl(s, F_SETFL,sock_flags|O_NONBLOCK);
    while(bluetooth_up == 1){
        if (new_blue_read_sentence == 0 && bluetooth_up == 1){
            while(bluetooth_up == 1 && (read(client, &aa, 1) == -1) ){
                    if(bluetooth_up == 0){
                        printf("\nExiting blue read\n");
                        blue_read_up = 0;
                        return NULL;
                    }
            }
            printf("%i",aa);
            if(aa != '\n')
            {
                buffer[idx++] = aa;
            }
            else
            {
                buffer[idx] = '\n';
                buffer[idx + 1] = '\0';
                idx = 0;
                strcpy( blue_read_buffer, buffer);
                new_blue_read_sentence = 1;
            }
        }
    }
    printf("\nExiting blue read 2\n");
    blue_read_up = 0;
    return NULL;
}

Bluetooth接続コードはかなり標準的だと思いますが、ここにあります

        // allocate socket
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    printf("\nsocket = %i\n", s);

    // bind socket to port 1 of the first available local bluetooth adapter
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t)1;
    retval = bind(s, (struct sockaddr*)&loc_addr, sizeof(loc_addr));
    printf("\nbind = %i\n", retval);

    // put socket into listening mode
    //listen(s, 1);
    retval = listen(s, 1);
    printf("\nlisten = %i\n", retval);

    // accept one connection
    client = accept(s, (struct sockaddr*)&rem_addr, &opt);

    sock_flags = fcntl(s,F_GETFL,0);
    fcntl(s, F_SETFL,sock_flags|O_NONBLOCK);

    printf("\n1 - client connect = %i socket %i\n", client, s);
4

1 に答える 1

0

リッスンしているソケットに O_NONBLOCK を設定しています。代わりに、実際に読み取られている受け入れソケット (クライアント) を試してください。

于 2014-12-12T00:10:37.913 に答える