raspberry pi bluetooth 连接android手机

15 篇文章 2 订阅
板子:树莓派 zero wifi
系统:yocto编出的core-image-sato

安装python-pybluez:

dnf install python-pybluez

这样我们就可以:

import bluetooth
让树莓派可见并起名字为raspberry
hciconfig hci0 name "raspberry"
hciconfig hci0 down
hciconfig hci0 up
hciconfig hci0 piscan

关键的一步:注册 Serial Port service

sudo sdptool add SP

树莓派作为server端的代码:

from bluetooth import *

server_sock = BluetoothSocket(RFCOMM)
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service(server_sock, "TestServer", service_id=uuid,service_classes=[uuid,SERIAL_PORT_CLASS],profiles=[SERIAL_PORT_PROFILE],)

client_sock, client_info=server_sock.accept()

print client_info

try:
    while True:
        data=client_sock.recv(1024)
        print("received [%s]" % data)
except IOError:
    pass

print("disconnected")

client_sock.close()
server_sock.close()
print("all done")

Android 端:

package com.example.wrsadmin.maker_raspberry;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    ArrayList mDevicesName = new ArrayList();
    ArrayList<BluetoothDevice> mArrayListDevices;
    ArrayAdapter mArrayAdapter;
    Button b1;
    TextView tv_main;

    BluetoothAdapter mBluetoothAdapter;
    BluetoothDevice raspberry;
    BluetoothSocket raspberry_socket;
    ListView lv;
    UUID uuid=UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");

    BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getName()!=null) {
                    if (!mDevicesName.contains(device.getName())) {
                        mDevicesName.add(device.getName());
                        mArrayListDevices.add(device);
                        if (device.getName().contains("raspberry"))
                        {
                            raspberry=device;
                        }
                        MainActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                lv.setAdapter(mArrayAdapter);
                            }
                        });
                    }
                }
            }
        }
    };




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        lv = (ListView)findViewById(R.id.lv);
        b1 = (Button)findViewById(R.id.button);
        tv_main = (TextView)findViewById(R.id.textView);

        mArrayListDevices = new ArrayList<BluetoothDevice>();
        mArrayAdapter = new ArrayAdapter(this, R.layout.listview,R.id.textView2,mDevicesName);

        // Enable Bluetooth
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!mBluetoothAdapter.isEnabled())
        {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent,1);
        }

        // Get Location Permissions
        if (Build.VERSION.SDK_INT >= 23)
        {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            };
        }

        // Register for broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver,filter);

        lv.setAdapter(mArrayAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }

    public void discoveryDevices(View view) {
        mDevicesName.clear();
        mArrayListDevices.clear();
        MainActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                lv.setAdapter(mArrayAdapter);
            }
        });

        if (mBluetoothAdapter.isDiscovering())
        {
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothAdapter.startDiscovery();
        }
        else {
            mBluetoothAdapter.startDiscovery();
        }
    }

    public void connectToRasp(View view) {
        if (raspberry!=null)
        {
            if (raspberry_socket==null) {
                try {
                    raspberry_socket = raspberry.createInsecureRfcommSocketToServiceRecord(uuid);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (!raspberry_socket.isConnected()) {
                try {
                    raspberry_socket.connect();
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv_main.setText("Connected to raspberry!\n");
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void Turnleft(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "left";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void Turnright(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "right";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void duojiStop(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "duojistop";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void Forward(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "forward";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void Back(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "back";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public void dianjiStop(View view)
    {
        if(raspberry_socket!=null) {
            if (raspberry_socket.isConnected())
            {
                String s = "dianjistop";
                byte[] buffer = s.getBytes();
                try {
                    OutputStream os=raspberry_socket.getOutputStream();
                    os.write(buffer);
                    os.flush();
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}

关于问题:Failed to connect to SDP server on FF:FF:FF:00:00:00: No such file or directory的解法
https://bbs.archlinux.org/viewtopic.php?id=201672

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值