Raspberry Pi3和Android应用程序蓝牙发送消息但未接收到

时间:2019-02-25 22:54:43

标签: android bluetooth raspberry-pi bluetooth-lowenergy raspberry-pi3

我正在构建一个通过蓝牙低功耗(BLE)连接到树莓pi3的应用程序。我可以同时连接两个设备,并且android应用程序能够将消息发送到RPi,但是android应用程序根本不接收消息(永远不会调用平均值onDataReceived)。对于Android连接,我使用了SPPLibrary https://github.com/akexorcist/Android-BluetoothSPPLibrary

我认为可能存在格式问题或类似问题,因为我在商店尝试了一个蓝牙终端示例应用程序,并且运行良好。

我的android代码:

public class TerminalActivity extends Activity {
BluetoothSPP bt;

TextView textStatus, textRead;

Menu menu;

Iteration [] schedules;
String TAG = "developer";
String device_name;


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_terminal);

    textRead = findViewById(R.id.textRead);
    textStatus = findViewById(R.id.textStatus);

    bt = new BluetoothSPP(this);

    if(!bt.isBluetoothAvailable()) {
        Toast.makeText(getApplicationContext()
                , "Bluetooth is not available"
                , Toast.LENGTH_SHORT).show();
        finish();
    }

    bt.setOnDataReceivedListener(new OnDataReceivedListener() {
        public void onDataReceived(byte[] data, String message) {
           textRead.append(message + "\n");
            Toast.makeText(TerminalActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    });

    bt.setBluetoothConnectionListener(new BluetoothConnectionListener() {
        public void onDeviceDisconnected() {
            textStatus.setTextColor(Color.RED);
            textStatus.setText("Status : Not connect");
            menu.clear();
            getMenuInflater().inflate(R.menu.menu_connection, menu);
        }

        public void onDeviceConnectionFailed() {
            textStatus.setText("Status : Connection failed");
        }

        public void onDeviceConnected(String name, String address){
            textStatus.setTextColor(Color.GREEN);
            device_name = name;
            textStatus.setText("Status : Connected to " + name);
            menu.clear();
            getMenuInflater().inflate(R.menu.menu_disconnection, menu);
        }
    });
}

public boolean onCreateOptionsMenu(Menu menu) {
    this.menu = menu;
    getMenuInflater().inflate(R.menu.menu_connection, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == R.id.menu_device_connect) {
        bt.setDeviceTarget(BluetoothState.DEVICE_OTHER);
        Intent intent = new Intent(getApplicationContext(), DeviceList.class);
        startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
    } else if(id == R.id.menu_disconnect) {
        if(bt.getServiceState() == BluetoothState.STATE_CONNECTED)
            bt.disconnect();
    }
    else if (id == R.id.schedule) {
        if(bt.getServiceState() == BluetoothState.STATE_CONNECTED){
            Intent intent = new Intent(getApplicationContext(), ScheduleActivity.class);
            intent.putExtra("schedules",schedules);
            startActivity(intent);
        }

    }
    return super.onOptionsItemSelected(item);
}

public void onDestroy() {
    super.onDestroy();
    bt.stopService();
}

public void onStart() {
    super.onStart();
    if (!bt.isBluetoothEnabled()) {
        Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT);
    } else {
        if(!bt.isServiceAvailable()) {
            bt.setupService();
            bt.startService(BluetoothState.DEVICE_ANDROID);
            setup();
        }
    }
}

public void setup() {
    Button btnSend = findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            if(bt.getServiceState() == BluetoothState.STATE_CONNECTED)
                bt.send("shoot", false);
            else
                Toast.makeText(TerminalActivity.this, "Sorry, you need to connect first", Toast.LENGTH_SHORT).show();
        }
    });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) {
        if(resultCode == Activity.RESULT_OK)
            bt.connect(data);
    } else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) {
        if(resultCode == Activity.RESULT_OK) {
            bt.setupService();
            bt.startService(BluetoothState.DEVICE_ANDROID);
            setup();
        } else {
            Toast.makeText(getApplicationContext()
                    , "Bluetooth was not enabled."
                    , Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}

}

我的RPi python3代码:`

# Importing the Bluetooth Socket library
import bluetooth
# Importing the GPIO library to use the GPIO pins of Raspberry pi
import RPi.GPIO as GPIO
import datetime
from datetime import timedelta
import threading
import time


led_pin = 16    # Initializing pin 40 for led
fan_pin = 13
GPIO.setmode(GPIO.BCM)  # Using BCM numbering
GPIO.setup(led_pin, GPIO.OUT)   # Declaring the pin 40 as output pin
GPIO.setup(fan_pin, GPIO.OUT)
host = ""
port = 1    # Raspberry Pi uses port 1 for Bluetooth Communication
# Creaitng Socket Bluetooth RFCOMM communication
server = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
print('Bluetooth Socket Created')
interval = 15
duration = 5  #in seconds
nextShoot = datetime.datetime.now()+timedelta(minutes=interval);
schedule_running = False

def sch_timer(interval):
    print("New thread created")
    global schedule_running
    schedule_running = True
    nextShoot = datetime.datetime.now() + timedelta(minutes=interval)
    print("The next shoot will happen : "+str(nextShoot))
    while schedule_running == True:
        if datetime.datetime.now() > nextShoot:
                print("Schedule shoot!!" + str(datetime.datetime.now()))
                GPIO.output(led_pin, True)
                #print("LED will be up until: "+str(datetime.datetime.now() + timedelta(minutes=duration)))
                print(str(datetime.datetime.now()))
                print(str(datetime.datetime.now() + timedelta(minutes=duration)))
                time.sleep(duration)
                GPIO.output(led_pin, False)
                print("duration has expired, new scheduled shoot is at: " + str(datetime.datetime.now() + timedelta(minutes=interval)))
                nextShoot = datetime.datetime.now() + timedelta(minutes=interval)
    print("End of thread")      
    return

class Schedule():
    def __init__(self):
            try:  #to connect
                    server.bind((host, port))
                    print("Bluetooth Binding Completed")
            except:
                    print("Bluetooth Binding Failed")
            server.listen(1) # One connection at a time
            # Server accepts the clients request and assigns a mac address.
            client, address = server.accept()
            print("Connected To", address)
            print("Client:", client)
            t1 = threading.Thread()
        #   try:
            while True:
                    # Receivng the data.
                    data = client.recv(1024) # 1024 is the buffer size.
                    data = str(data,"utf-8")
                    print(data)

                    if data == "shoot":  #calculate good time to trigger with fans and adjust
                            GPIO.output(led_pin, True) #trigger pin
                            GPIO.output(fan_pin, True)
                            send_data = "Fan On \n"
                    elif data == "release":
                            GPIO.output(led_pin, False)
                            GPIO.output(fan_pin, False)
                            send_data = "Fan Off"
                    elif data == "1min":
                            send_data = "Schedule 1 minute"
                            interval = 1 #in minutes
                     #      dateAndTimeString = str(datetime.datetime.now()).split()
                     #      date,time = dateAndTimeString #split date and time into two strings (date and time)
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()

                    elif data == "2min":
                            send_data = "Schedule 2 minutes"
                            interval = 2 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "5min":
                            send_data = "Schedule 5 minutes"
                            interval = 5 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "10min":
                            send_data = "Schedule 10 minutes"
                            interval = 10 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "15min":
                            send_data = "Schedule 15 minutes"
                            interval = 15 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "30min":
                            send_data = "Schedule 30 minutes"
                            interval = 30 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "45min":
                            send_data = "Schedule 45 minutes"
                            interval = 45 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "60min":
                            send_data = "Schedule 60 minutes"
                            interval = 60 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "90min":
                            send_data = "Schedule 90 minutes"
                            interval = 90 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    elif data == "120min":
                            send_data = "Schedule 120 minutes"
                            interval = 120 #in minutes
                            global schedule_running
                            if schedule_running == False:
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                            else:
                                print("Thread is currently running, waiting for it to end")
                                schedule_running = False
                                t1.join()
                                print("Past thread is dead, creating new thread...")
                                t1 = threading.Thread(target=sch_timer, args=(interval,))
                                t1.start()
                    else:
                            send_data = "Command not recognized. "
                    # Sending the data.
                    #TODO Maybe encode data to UTF-8 before sending
                    client.send(send_data+"\n")
            #~ except:
                    #~ # Making all the output pins LOW
                    #~ GPIO.cleanup()
                    #~ # Closing the client and server connection
                    #~ client.close()
                    #~ server.close()

def main():
    sch = Schedule()

main()

`

1 个答案:

答案 0 :(得分:0)

我找到了答案!我是对的,只需要在要发送的消息末尾附加“ \ r \ n”(send_data)即可。例如:如果我想发送消息,则需要

send_data = "Fan Off\r\n"
client.send(send_data)