2015年3月27日 星期五

RaspBerryPi-運用 Python 操控 GPIO

首先 Terminal 下
sudo apt-get install python-rpi.gpio

之前有介紹過有兩種執行方式
為了加速時間,就先捨去第一方法
直接使用第二種方法
1) sudo nano led.py
2)
import time, RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM);
GPIO.setup(4, GPIO.OUT);
while True:
    ledOn = GPIO.output(4,0);
    time.sleep(1);
    ledOff = GPIO.output(4,1);
    time.sleep(1);
3) ctrl + O
4) enter
5) python led.py












不知道各位大大是否有遇過以下的情形
RuntimeError : No access to /dev/mem. Try running as root!
原因是權限不足
無法更改操作硬體

6) sudo python led.py

歡迎轉載,請註明出處。


RaspBerryPi-基本 Python 使用

最近剛好有需求
所以利用時間來整理
樹莓派可以支援多個語言
但Python是最直接的
只需要文字編輯器!!!

確認Python步驟( 不要跳步驟 ) :

  1. sudo apt-get update( 更新系統安裝檔案 )
  2. sudo apt-get upgrade( 更新系統安裝檔案 )
  3. sudo apt-get install python2.7( 確認是否安裝 Python )


















執行 Python 有兩種方式 :

1 . 直接在Termainl進入 Python 編輯模式寫程式
EX : 
1) python
2) print('Hello Python!');
Hello Python

雖然可以很快速地去執行,但如果是大量程式編寫。

2 . 透過文字編輯器編寫後執行
1) sudo nano hello.py
2)直接在裡面輸入 : print('Hello Python!');
3)Ctrl + O
4)Enter
5)Ctrl + X
6)Enter
7)python hello.py
Hello Python

看似非常的麻煩,但是在編寫的過程中較能掌握流程。

歡迎轉載,請註明出處。


2015年3月25日 星期三

Android-用 HttpURLConnection 取代 Parse SDK 查詢功能

更改日期 :
20150706 避免傳送中文造成的Exception

前幾天實作直接利用 HttpClient 取得資料回饋
但發現雖然都可以正常執行
但發現到這個要準備去棄用了
以下是官方的圖示















以下是連線到 Parse 並且取得資料
以下 ID 、 KEY 是連接Parse必給的參數
若沒需求可把附加的方法去除
以下是利用HttpURLConnection連線

public class TodoTask extends AsyncTask<Void,Void,String>{
    
    private String _api;
    private String _strJson;

    public TodoTask(String api, String strJson){
        this._api = api;
        this._strJson = strJson;
    }

    @Override
    public void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    public String doInBackground(Void... arg0) {
        URL url;
        HttpURLConnection connection = null;  
        try {
            //Create connection
            url = new URL(_api);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");

            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Content-Length", "" + 
                Integer.toString(_strJson.getBytes().length));
            connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            connection.addRequestProperty("Application-Id","your project id");
            connection.addRequestProperty("API-Key","your project key");

            connection.setUseCaches (false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            connection.setConnectTimeout(5000);

            //Send request
            DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
            wr.write(_strJson.getBytes("utf-8"));
            wr.flush ();
            wr.close ();

            //Get Response    
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer(); 
            
            while((line = rd.readLine()) != null) {
                response.append(line);
                //response.append('\r');
            }
            rd.close();
            return response.toString();

        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {

            if(connection != null) {
                connection.disconnect(); 
            }
        }
    }

    @Override
    public void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d("tagg","onPostExecute : "+result);
        if(result != null && !"".equals(result)){
            
        }
    }
}


參考來源 : 來源

歡迎轉載,請註明出處。

Android-JSON 拆解使用介紹

更改日期 :
20150707_新增JSON字串_更改排版
20150812_新增 JSON.jar 路徑

如果要在一般 JavaProject 底下生成
必定要下載 Jar

以下是寫成JSON的字串,予以下範例無關

String json = "{\"key\":\"123456789\"}"

相信各位大大一定都在用GSON
不僅方便易懂,效率更高
但還是要回歸原本
多多少少一定要了解要如何使用JSON

try {
    
    // 1 . New 一個JSON物件,並把字串帶入
    JSONObject json = new JSONObject(result);
    
    // 2 . 接下來像剝洋蔥般的拆解參數
    Log.d("tag","onpost line : "+json.get("result"));
    String s = json.get("result").toString();
    
    // 
    JSONObject json1 = new JSONObject(s);
    Log.d("tag","onpost line : "+json1.get("code"));
    
    // 
    JSONObject json2 = new JSONObject(s);
    Log.d("tag","onpost line : "+json2.get("data"));
    
    // 3 . 陣列參數
    JSONArray nameList = json2.getJSONArray("data");
    int length = nameList.length(); 
    String aa = "";  
    for(int i = 0; i < length; i++)
    { 
        Log.d("debugTest",Integer.toString(i));  
        JSONObject oj = nameList.getJSONObject(i);  
        aa = aa + oj.getString("DESCRIPTION")+"|";  
        Log.d("tag","---onpost line : "+oj.getString("DESCRIPTION"));
        printMessage(oj.getString("DESCRIPTION"));
    }

} catch (JSONException e) {
    e.printStackTrace();
}


歡迎轉載,請註明出處。

Android-用HttpClient 取代 Parse SDK 查詢功能

Use HttpClient can  repaly Parse SDK inquire function
如果只要連到Parse取得資料還要裝SDK?
SDK程序太複雜( 基本上是不會的 )?
現在只要用簡單的方法就可以取得資料

public class Task extends AsyncTask<Void,Void,String>{
        private String url;
        private String applicationID;
        private String clientKey;
        private List<NameValuePair> list;
        
        public Task(String url, String applicationID, 
                String clientKey, List<NameValuePair> list) {
            this.url = url;
            this.applicationID = applicationID;
            this.clientKey = clientKey;
            this.list = list;
        }

        @Override
        public void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        public String doInBackground(Void... arg0) {
            String result = null;
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost post = new HttpPost(url);

                post.setHeader("X-Parse-Application-Id", applicationID);
                post.setHeader("X-Parse-REST-API-Key", clientKey);

                post.setEntity(new UrlEncodedFormEntity(list));

                HttpResponse response = httpClient.execute(post);

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent()));
                String line;
                StringBuffer responseBuffer = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    responseBuffer.append(line);
                }
                rd.close();
                result = responseBuffer.toString();
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        public void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

調用方法
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("name", "JJ"));
        parameters.add(new BasicNameValuePair("Address", "US"));        
        
        Connection connectioni = new Connection();
        new Task("https://api.parse.com/functions/query85481", 
                "Application-ID", 
                "API-Key", 
                parameters).execute();

 歡迎轉載,請註明出處。

2015年3月23日 星期一

Android-搜尋 Bluetooth Low Energy 頁面

整理出一份
MainActivity.java
package com.lightblue.bluetooth_socket;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{

    private static final int REQUEST_SELECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private BluetoothDevice mDevice = null;
    private BluetoothAdapter mBtAdapter = null;

    private Button btnConnectBlueTooth; 
    private TextView textBlueName;
    private TextView textBlueMac;

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

        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        btnConnectBlueTooth = (Button) findViewById(R.id.connectBlueToothBtn);
        textBlueName = (TextView) findViewById(R.id.bluetoothNameTextView);
        textBlueMac = (TextView) findViewById(R.id.bluetoothMacTextView);

        btnConnectBlueTooth.setOnClickListener(this);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("BLE","requestCode : "+requestCode);
        switch (requestCode) {

        case REQUEST_SELECT_DEVICE:
            if (resultCode == Activity.RESULT_OK && data != null) {
                String deviceAddress = data.getStringExtra(BluetoothDevice.EXTRA_DEVICE);
                mDevice = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(deviceAddress);
                textBlueName.setText("Bluetooth : "+mDevice.getName());
                textBlueMac.setText("Bluetooth Address : "+mDevice.getAddress());
            }
            break;
        case REQUEST_ENABLE_BT:
            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this, "Bluetooth has turned on ", Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(this, "Problem in BT Turning ON ", Toast.LENGTH_SHORT).show();
                finish();
            }
            break;
        default:
            break;
        }
    }

    @Override
    public void onClick(View view) {

        switch(view.getId()){
        case R.id.connectBlueToothBtn:
            Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
            startActivityForResult(newIntent, REQUEST_SELECT_DEVICE);
            break;
        }
    }
}


DeviceListActivity.java
public class DeviceListActivity extends Activity {
    private BluetoothAdapter mBluetoothAdapter;

   // private BluetoothAdapter mBtAdapter;
    private TextView mEmptyList;
    public static final String TAG = "DeviceListActivity";
    
    List<BluetoothDevice> deviceList;
    private DeviceAdapter deviceAdapter;
    private ServiceConnection onService = null;
    Map<String, Integer> devRssiValues;
    private static final long SCAN_PERIOD = 10000; //10 seconds
    private Handler mHandler;
    private boolean mScanning;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar);
        setContentView(R.layout.device_list);
        android.view.WindowManager.LayoutParams layoutParams = this.getWindow().getAttributes();
        layoutParams.gravity=Gravity.TOP;
        layoutParams.y = 200;
        mHandler = new Handler();
        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "不支援BLE裝置", Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "不支援BLE裝置", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        populateList();
        mEmptyList = (TextView) findViewById(R.id.empty);
        Button cancelButton = (Button) findViewById(R.id.btn_cancel);
        cancelButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                
                if (mScanning==false) scanLeDevice(true); 
                else finish();
            }
        });

    }

    private void populateList() {
        /* Initialize device list container */
        Log.d(TAG, "populateList");
        deviceList = new ArrayList<BluetoothDevice>();
        deviceAdapter = new DeviceAdapter(this, deviceList);
        devRssiValues = new HashMap<String, Integer>();

        ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
        newDevicesListView.setAdapter(deviceAdapter);
        newDevicesListView.setOnItemClickListener(mDeviceClickListener);

           scanLeDevice(true);

    }
    
    private void scanLeDevice(final boolean enable) {
        final Button cancelButton = (Button) findViewById(R.id.btn_cancel);
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);                      
                    cancelButton.setText("掃描");

                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
            cancelButton.setText("取消");
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            cancelButton.setText("掃描");
        }

    }

    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    
                      runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              addDevice(device,rssi);
                          }
                      });                  
                }
            });
        }
    };
    
    private void addDevice(BluetoothDevice device, int rssi) {
        boolean deviceFound = false;

        for (BluetoothDevice listDev : deviceList) {
            if (listDev.getAddress().equals(device.getAddress())) {
                deviceFound = true;
                break;
            }
        }
   
        devRssiValues.put(device.getAddress(), rssi);
        if (!deviceFound) {
            deviceList.add(device);
            mEmptyList.setVisibility(View.GONE);          
            deviceAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
       
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    }

    @Override
    public void onStop() {
        super.onStop();
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
    
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            BluetoothDevice device = deviceList.get(position);
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
  
            Bundle b = new Bundle();
            b.putString(BluetoothDevice.EXTRA_DEVICE, deviceList.get(position).getAddress());

            Intent result = new Intent();
            result.putExtras(b);
            setResult(Activity.RESULT_OK, result);
            finish();
            
        }
    };
    
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
    }
    
    class DeviceAdapter extends BaseAdapter {
        Context context;
        List<BluetoothDevice> devices;
        LayoutInflater inflater;

        public DeviceAdapter(Context context, List<BluetoothDevice> devices) {
            this.context = context;
            inflater = LayoutInflater.from(context);
            this.devices = devices;
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public Object getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewGroup vg;

            if (convertView != null) {
                vg = (ViewGroup) convertView;
            } else {
                vg = (ViewGroup) inflater.inflate(R.layout.device_element, null);
            }

            BluetoothDevice device = devices.get(position);
            final TextView tvadd = ((TextView) vg.findViewById(R.id.address));
            final TextView tvname = ((TextView) vg.findViewById(R.id.name));
            final TextView tvpaired = (TextView) vg.findViewById(R.id.paired);
            final TextView tvrssi = (TextView) vg.findViewById(R.id.rssi);

            tvrssi.setVisibility(View.VISIBLE);
            byte rssival = (byte) devRssiValues.get(device.getAddress()).intValue();
            if (rssival != 0) {
                tvrssi.setText("Rssi = " + String.valueOf(rssival));
            }

            tvname.setText(device.getName());
            tvadd.setText(device.getAddress());
            if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                Log.i(TAG, "device::"+device.getName());
                tvname.setTextColor(Color.BLACK);
                tvadd.setTextColor(Color.BLACK);
                tvpaired.setTextColor(Color.GRAY);
                tvpaired.setVisibility(View.VISIBLE);
                tvpaired.setText("paired");
                tvrssi.setVisibility(View.VISIBLE);
                tvrssi.setTextColor(Color.BLACK);
                
            } else {
                tvname.setTextColor(Color.BLACK);
                tvadd.setTextColor(Color.BLACK);
                tvpaired.setVisibility(View.GONE);
                tvrssi.setVisibility(View.VISIBLE);
                tvrssi.setTextColor(Color.BLACK);
            }
            return vg;
        }
    }
}


activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/connectBlueToothBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ConnectBluetooth" />

    <TextView
        android:id="@+id/bluetoothNameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/bluetoothMacTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>


device_element.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dp" 
    android:textColor="#FF000000"
    >

    <TextView
        android:id="@+id/paired"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:text="paired"
        android:textSize="12dp" />

    <TextView
        android:id="@+id/rssi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_below="@+id/paired"
        android:textSize="12dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:textSize="14dp" />

    <TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:textSize="10dp" />

</RelativeLayout>

device_list.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#666" >

        <TextView
            android:id="@+id/title_devices"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:paddingLeft="12dp"
            android:paddingRight="50dp"
            android:text="選擇裝置"
            android:textColor="#fff"
            android:textSize="15dip" />

        <ImageView
            android:id="@+id/about"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@android:drawable/ic_menu_info_details" />
    </RelativeLayout>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
        <ListView
            android:id="@+id/new_devices"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="2"
            android:stackFromBottom="true" />

        <TextView
            android:id="@+id/empty"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="掃描" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@android:string/cancel" />
    </LinearLayout>
</LinearLayout>

title_bar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView
            android:id="@+id/title_devices"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="@string/app_name">
    </TextView>
</LinearLayout>



























歡迎轉載,請註明出處。

2015年3月19日 星期四

Android-更新 SDK 至 22 導致圖形面板設計例外

Update SDK 22 but has exception in Layout.XML

不知道那位大大有遇到以下狀況
圖形化拖曳設計界面突然出現例外

java.lang.NullPointerException
Exception details are logged in Window > Show View > Error Log
The following classes could not be instantiated:
- android.support.v7.internal.app.WindowDecorActionBar (Open Class, Show Error Log)
- android.support.v7.internal.widget.ActionBarContextView (Open Class, Show Error Log)
- android.support.v7.widget.Toolbar (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.




























沒錯,就以上的 Code。

就在手無寸鐵之際,出現一道曙光。















被這個玩了好久 OTZ

歡迎轉載,請註明出處。