feiyushenyou 2021-09-06 16:42 采纳率: 33.3%
浏览 103
已结题

TElink 8278蓝牙模块如何添加G-sensor

TElink 8278如何添加G-sensor,sdk中没有相关支持,需要自行添加支持,sdk仅提供了i2c通信接口,MCU是类单片机微处理器,对于我这有点难度。
哪位添加过吗,是否可以提供samplecode, 或流程伪代码。
感激不尽!

  • 写回答

1条回答 默认 最新

  • 孙叫兽 前端领域优质创作者 2021-09-06 22:43
    关注
    
    package com.bluetoothclient;
    
    
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.os.Vibrator;
    
    import java.util.Calendar;
    
    import com.components.Broadcast.BluetoothPairingReceiver;
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.hardware.Sensor;
    import android.hardware.SensorEvent;
    import android.hardware.SensorEventListener;
    import android.hardware.SensorManager;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    
        private BluetoothAdapter mBluetoothAdapter;
        public static final  String TAG ="BluetoothClient_activity";
        // Member object for the SPP services
        public  static BluetoothSPPService mSPPService = null;
        public  static String  btRemoteAddress = "";
        // Message types sent from the BluetoothChatService Handler
        public static final int MESSAGE_STATE_CHANGE = 1;
        public static final int MESSAGE_READ = 2;
        public static final int MESSAGE_WRITE = 3;
        public static final int MESSAGE_DEVICE_NAME = 4;
        public static final int MESSAGE_TOAST = 5;
        
        public static final int MESSAGE_ADDRESS = 6;
        
        // Key names received from the BluetoothChatService Handler
        public static final String DEVICE_NAME = "device_name";
        public static final String TOAST = "toast";
    
        // Intent request codes
        private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
        private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
        private static final int REQUEST_ENABLE_BT = 3;
        
          public ListenerThread StartListenThread;
        private EditText mEditText;
        private TextView rec_data;
        
        private Button sendBtn;
        
        private String strReceiveData="";
        
        private BluetoothPairingReceiver btPairingReciver;
        //public static String ACTION_PAIRING_REQUEST_AUTO ="android.bluetooth.device.action.PAIRING_REQUEST";
        
        //begin gsensor 
        private SensorManager mSensorManager;   
        private Sensor accelerometer; // 加速度传感器 
    //    private Sensor magnetic; // 地磁场传感器 
        private float[] accelerometerValues = new float[3]; 
        private float[] magneticFieldValues = new float[3]; 
        
        private long lasttimestamp = 0;  
        private Calendar mCalendar; 
        private Vibrator vibrator;
        //end gsensor
        
        private final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
    
                case MESSAGE_READ:
                    byte[] readBuf = (byte[]) msg.obj;
                    // construct a string from the valid bytes in the buffer
                    String readMessage = new String(readBuf, 0, msg.arg1);
                    strReceiveData += readMessage+"\n";
                    System.out.println("rev :"+readMessage);
                    rec_data.setText(strReceiveData);
                   // mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                    break;
                case MESSAGE_ADDRESS:
                    mEditText.setText(btRemoteAddress);
                    break;
                case MESSAGE_TOAST:
                    String toast = msg.getData().getString(TOAST);
                    Toast.makeText(MainActivity.this,toast, Toast.LENGTH_LONG).show();
                    break;
                }
            }
        };
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            mEditText = (EditText)findViewById(R.id.EditText1);
            rec_data  = (TextView)findViewById(R.id.tv_received);
            sendBtn =(Button)findViewById(R.id.button1);
            sendBtn.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    String sendContent = mEditText.getText().toString();
                    if(mSPPService.getState() == BluetoothSPPService.STATE_CONNECTED) 
                    {
                        
                        sendMessage(sendContent);
                        
                    }
                    System.out.println("bluetooth client send data,sendContent= "+sendContent+", "
                            + "mSPPService.getState()="+mSPPService.getState());
                }
            });
            
            // Get local Bluetooth adapter
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
              
            if(mBluetoothAdapter==null)
            {
                 Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
                 return;
            }
            System.out.println("Get local Bluetooth adapter success!");
            
             if(!mBluetoothAdapter.isEnabled())
             {
    
                //弹出对话框提示用户是后打开
                //Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                //startActivityForResult(enabler, REQUEST_ENABLE);
                 
    //             Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    //             discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
    //             startActivity(discoverableIntent);
                 
                 //不做提示,强行打开
                 mBluetoothAdapter.enable();
             }
    
              // Initialize the BluetoothChatService to perform bluetooth connections
    //          ////begin配对广播
    //            btPairingReciver = new BluetoothPairingReceiver();
    //            //IntentFilter filter=new IntentFilter();
    //            IntentFilter filter= new IntentFilter(ACTION_PAIRING_REQUEST_AUTO);//BluetoothDevice.ACTION_PAIRING_REQUEST;
    //            filter.setPriority(Integer.MAX_VALUE);
    //            registerReceiver(btPairingReciver, filter);
                // 注册Receiver来获取蓝牙设备相关的结果  
                 btPairingReciver = new BluetoothPairingReceiver();
                IntentFilter intent = new IntentFilter();  
                intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果  
                intent.addAction(BluetoothPairingReceiver.ACTION_PAIRING_REQUEST_AUTO); 
                intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
                intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);  
    //            intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);  
    //            intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); 
                intent.setPriority(Integer.MAX_VALUE);
                registerReceiver(btPairingReciver, intent);
                
                mSPPService = new BluetoothSPPService(this,mHandler);
                
                // 实例化传感器管理者 
                mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);      
                // 初始化加速度传感器 
                accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
                // 初始化地磁场传感器 
    //            magnetic = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); 
               
                // 注册监听 
                mSensorManager.registerListener(new MySensorEventListener(),accelerometer, Sensor.TYPE_ACCELEROMETER); 
                //mSensorManager.registerListener(new MySensorEventListener(), magnetic,Sensor.TYPE_MAGNETIC_FIELD);
                System.out.println("onCreate,accelerometer = "+accelerometer); 
                
                vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); 
                
                Log.e(TAG, "+ ON Create +");
        }
    
        private void connectDevice(String address ) {
            // Get the device MAC address
       
            // Get the BluetoothDevice object
            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
            // Attempt to connect to the device
            mSPPService.connect(device, false);
        }
    
        @Override
        public synchronized void onResume() {
            super.onResume();
            Log.e(TAG, "+ ON RESUME +");
    
             String address = mBluetoothAdapter.getAddress();
             System.out.println("onResume(),本机蓝牙地址 = "+address+",远程蓝牙地址 = "+ btRemoteAddress 
                     + ", mSPPService.getState()= " + mSPPService.getState() +",mSPPService = "+mSPPService);
            // Performing this check in onResume() covers the case in which BT was
            // not enabled during onStart(), so we were paused to enable it...
            // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
    //        if (mSPPService != null) {
    //            // Only if the state is STATE_NONE, do we know that we haven't started already
    //            if (mSPPService.getState() == BluetoothSPPService.STATE_NONE) {
    //                // Start the Bluetooth SPP services
    //                StartListenThread = new ListenerThread();
    //                StartListenThread.start();
    //              
    //            }
    //        }
        }
        
        /**
         * Sends a message.
         * @param message  A string of text to send.
         */
        private void sendMessage(String message) {
            // Check that we're actually connected before trying anything
            if (mSPPService.getState() != BluetoothSPPService.STATE_CONNECTED) {
                Toast.makeText(this, "未连接", Toast.LENGTH_SHORT).show();
                return;
            }
    
            // Check that there's actually something to send
            if (message.length() > 0) {
                // Get the message bytes and tell the BluetoothChatService to write
                byte[] send = message.getBytes();
                mSPPService.write(send);
                Log.e(TAG, "+ sending Message +");
                // Reset out string buffer to zero and clear the edit text field
               // mOutStringBuffer.setLength(0);
              //  mOutEditText.setText(mOutStringBuffer);
            }
        }
        
        @Override
        public void onDestroy() {
            super.onDestroy();
            
            // Stop the Bluetooth SPP services
            if (mSPPService != null)
                mSPPService.stop();
             Log.e(TAG, "--- ON DESTROY ---");
             // 卸载注册的接收器
             //if(mDiscoveredReceiver!= null)
                 unregisterReceiver(btPairingReciver);
                 //卸载注册的传感器    
             mSensorManager.unregisterListener(new MySensorEventListener()); 
        }
        
        private class ListenerThread extends Thread {
            // The local server socket
    
            public void run()
            {
                //String btRemoteAddress = BluetoothPairingReceiver.btDeviceAddress;
                System.out.println("ListenerThread run() btRemoteAddress = " + btRemoteAddress 
                        +", btPairState = "+BluetoothPairingReceiver.btPairState);
                // Wait for Bluetooth to open, and the pairing is successful. 
                while(true)//for(int i =0;i<100;i++)//
                {
                    System.out.println("ListenerThread run(),mBluetoothAdapter.getState()(12)= "+mBluetoothAdapter.getState()
                            +", btRemoteAddress= "+btRemoteAddress);
                    if((mBluetoothAdapter.getState()== BluetoothAdapter.STATE_ON)&&(!btRemoteAddress.equals("")))
                        //    &&(BluetoothPairingReceiver.btPairState ==BluetoothDevice.BOND_BONDED))
                    {              
                            //String address = "78:F5:FD:FB:1D:FF";
                        System.out.println("ListenerThread run() btRemoteAddress = " + btRemoteAddress);
                            if(!btRemoteAddress.equals("")){
                            //mEditText.setText((CharSequence)btRemoteAddress);
                           Message message = new Message();
                              message.what = MESSAGE_ADDRESS;
                              mHandler.sendMessage(message);
                            }
                        synchronized (this) { 
                            if(mSPPService.getState() != BluetoothSPPService.STATE_CONNECTED)//
                                connectDevice(btRemoteAddress);
                        }
                            break;
                    }
                    else
                    {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
    
            }
    
        }
        
        class MySensorEventListener implements SensorEventListener { 
    
            @Override
            public void onSensorChanged(SensorEvent event) { 
                // TODO Auto-generated method stub 
                if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
                    accelerometerValues = event.values; 
                     
                    float x = accelerometerValues[0]; // x轴方向的重力加速度,向右为正   
                    float y = accelerometerValues[1]; // y轴方向的重力加速度,向前为正   
                    float z = accelerometerValues[2]; // z轴方向的重力加速度,向上为正   
                   // Log.i(TAG, "x轴方向的重力加速度" + x +  ";y轴方向的重力加速度" + y +  ";z轴方向的重力加速度" + z);   
                    // 一般在这三个方向的重力加速度达到40就达到了摇晃手机的状态。   
                    int medumValue = 16;// 如果不敏感请自行调低该数值,低于10的话就不行了,因为z轴上的加速度本身就已经达到10了                
                    
                    mCalendar = Calendar.getInstance();  
                    long stamp = mCalendar.getTimeInMillis() / 1000l;// 1393844912   
                    //int second = mCalendar.get(Calendar.SECOND);// 53  
                    
                    if ((Math.abs(x) > medumValue || Math.abs(y) > medumValue || Math.abs(z) > medumValue)
                        && (stamp - lasttimestamp) > 0.5){ 
                         lasttimestamp = stamp; 
                            vibrator.vibrate(200);   
    //                    Message msg = new Message();   
    //                    msg.what = SENSOR_SHAKE;   
    //                    handler.sendMessage(msg); 
                           String sendContent = "x = "+ x +", y = " + y + ", z = " + z 
                                   + ", mobile is moving..";
                           if(mSPPService.getState() == BluetoothSPPService.STATE_CONNECTED) 
                        {
                            sendMessage(sendContent);
                            
                        }
                        Log.e(TAG, sendContent);
                    }
    
                } 
    //            if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) { 
    //                magneticFieldValues = event.values; 
    //                
    //                String  strMag = "magneticFieldValues: x = "+magneticFieldValues[0]+", y = "
    //                        +magneticFieldValues[1]+", z = "+magneticFieldValues[2];
    //                System.out.println(strMag); 
    //            } 
                //calculateOrientation(); 
            }
            
            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) { 
                // TODO Auto-generated method stub 
     
            } 
        }
        /** 
         * 获取一个最大值 
         *  
         * @param px 
         * @param py 
         * @param pz 
         * @return 
         */  
        public int getMaxValue(int px, int py, int pz) {  
            int max = 0;  
            if (px > py && px > pz) {  
                max = px;  
            } else if (py > px && py > pz) {  
                max = py;  
            } else if (pz > px && pz > py) {  
                max = pz;  
            }  
      
            return max;  
        }  
        
    }
    
    

    蓝牙客户端实现功能有:
    (1) 客户端手机主动发起与服务端手机蓝牙配对,并配对成功后 会主动发起与服务端的 蓝牙链接,若链接成功即可通信。
    (2) 发送消息;
    (3) 监听本地Gsensor,坐标数据,并通过蓝牙传送给服务端;

    蓝牙服务端实现功能有:
    (1) 自动处理 客户端发来的配对请求;
    (2) 监听客户端发来的链接;
    (3) 跟据客户端传来的 gsensor 信息 作相应处理。
    (4) 发送消息给客户端

    评论

报告相同问题?

问题事件

  • 系统已结题 9月14日
  • 创建了问题 9月6日

悬赏问题

  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的