아두이노용 씨리얼 테스트 코드

|

안드로이드와 하거나 다른 기기와 테스트할때 가능함

아두이노쪽에서 주기적으로 틱이 날라오고 메씨지를 보낼경우 에코해줌





/* Copyright 2012 Google Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * Project home page: http://code.google.com/p/usb-serial-for-android/
 */

// Sample Arduino sketch for use with usb-serial-for-android.
// Prints an ever-increasing counter, and writes back anything
// it receives.

static int counter = 0;
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.print("Tick #");
  Serial.print(counter++, DEC);
  Serial.print("\n");

  if (Serial.peek() != -1) {
    Serial.print("Read: ");
    do {
      Serial.print((char) Serial.read());
    } while (Serial.peek() != -1);
    Serial.print("\n");
  }
  delay(1000);
}



And

How to process argument between js(html5) and cordova 3.x

|

CordovaPlugin 에서 상속받은 클래스의 멤버함수인  excute의 json을 처리할수 있는 스펙은 아래와 같습니다.


public boolean execute(String action, JSONArray args,

final CallbackContext callbackContext)


1. js 에서 넘어온 인자 받기

args 에 배열의 첫번째로 넘겨온 json object를 얻으려면 아래 와 같이 해줍니다.


JSONObject json = args.getJSONObject(0);


get 함수로 각각의 json object 의 멤버변수들을 얻어올수 있습니다.


Log.d(TAG, "pi : " + json.get("pi"));

Log.d(TAG, "number : " + json.get("number"));

Log.d(TAG, "msg : " + json.get("msg"));


각 변수들은 기본적으로 String 형으로 받아지기 때문에 int 형을 처리 해주려면 타입 캐스팅을 해줍니다.


(Integer) json.get("number") + 1 


2. js 로 결과값을 인자로 넘겨주기


먼저 넘겨줄 빈 json 오브잭트를 만듭니다.

JSONObject resultJSON = new JSONObject();


put 함수로 값을 체워 넣습니다.

resultJSON.put("result", "ok");

resultJSON.put("msg", "json echo!!");


전송하기전에 먼저 PluginResult 객체에 담아줍니다.

PluginResult plugin_result = new PluginResult(Status.OK, resultJSON);


콜백컨텍스트의 sendPluginResult 함수로 js 측으로 결과 값을 전달합니다.

callbackContext.sendPluginResult(plugin_result);


3. 예제 실행법


plugin_sample.zip

 파일을 다운받습니다.


코도바 프로잭트를 생성하고  안드로이드 플랫폼을 추가합니다.

압축을 푸시고 로컬에서 다음과 같이 플러그인을 추가 합니다.( 플러그인의 경로가 ../plugin_sample/echo 이라고 가정)

cordova plugin add ../plugin_sample/echo


js 쪽 예제는 첨부된 파일의 index.html을 참고 하시면됩니다.



'html5' 카테고리의 다른 글

cordova-pulgin-whitelist 사용법  (0) 2015.11.29
crosswalk 사용기 1차  (0) 2015.11.22
How to make cordova 3.X plugin (only android)  (0) 2014.06.08
querySelector 팁 몇가지  (0) 2014.04.05
cordova 3.X 사용방법정리  (0) 2014.01.27
And

How to make cordova 3.X plugin (only android)

|

1. 플러그인 저장폴더 만들기(저장소)



다음과 같이 폴더를 구성합니다.



이 연습용 플러인 이름은 echo 입니다.


이렇게 만들어진 플러그인은 echo 폴더를 그대로 업로드 하는 방식으로 웹서버나 git을 통해서 간단하게 배포될수있습니다.


플러그인전체 구성을 정의해주는 plugin.xml 파일을 만들어 보겠습니다.


<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"

        xmlns:rim="http://www.blackberry.com/ns/widgets"

        xmlns:android="http://schemas.android.com/apk/res/android"

        id="플러그인고유식별자"

        version="0.0.1">

    <name>플러그인이름</name>

    <description>플러그인설명</description>

    <license>Apache 2.0</license>

    <keywords>플러그인 검섹키워드</keywords>


    <!-- android -->

    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">

            <feature name="모듈이름(자바클래스이름)" >

                <param name="android-package" value="패키지이름을포함한모듈이름"/>

            </feature>

        </config-file>


        <source-file src="소스파일경로(pluin.xml파일이있는폴더기준)" target-dir="타겟경로(코도바프로잭트루트기준)" />

    </platform>

</plugin>


echo 플러그인을 위한 pulgin.xml 을 다음과 같이 만들어 보았습니다.


<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"

        xmlns:rim="http://www.blackberry.com/ns/widgets"

        xmlns:android="http://schemas.android.com/apk/res/android"

        id="com.gunpower.cordova.echo"

        version="0.0.1">

    <name>echo</name>

    <description>Cordova echo Plugin</description>

    <license>Apache 2.0</license>

    <keywords>cordova,echo</keywords>


    <!-- android -->

    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">

            <feature name="Echo" >

                <param name="android-package" value="com.gunpower.cordova.echo.Echo"/>

            </feature>

        </config-file>


        <source-file src="src/android/Echo.java" target-dir="src/com/gunpower/cordova/echo" />

    </platform>

</plugin>



pluign.xml 파일에서 정의한 대로 src/android/Echo.java 경로로 파일을 작성합니다.


package com.gunpower.cordova.echo;


import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaArgs;

import org.apache.cordova.CordovaInterface;

import org.apache.cordova.CordovaPlugin;

import org.apache.cordova.CordovaWebView;

import org.json.JSONArray;

import org.json.JSONException;


import android.util.Log;


public class Echo extends CordovaPlugin {

public static final String TAG = "Echo";


@Override

public void initialize(CordovaInterface cordova, CordovaWebView webView) {

// TODO Auto-generated method stub

super.initialize(cordova, webView);

Log.d(TAG, "echo pluin initialize");

}


@Override

public boolean execute(String action, String rawArgs,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

return super.execute(action, rawArgs, callbackContext);

}


@Override

public boolean execute(String action, JSONArray args,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

final String result = args.isNull(0) ? null : args.getString(0);

        

        if ("echo".equals(action)) {

        //인자 다시 자바스크립트로 전달하기 

            callbackContext.success(result);

            return true;

        } 

        

return super.execute(action, args, callbackContext);

}


@Override

public boolean execute(String action, CordovaArgs args,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

return super.execute(action, args, callbackContext);

}


}



이상으로 플러그인 저장소가 만들어졌습니다.


2. 프로잭트에 플러그인 설치


cordova create myapp com.gbox.myapp myapp

cordova platform add android


myapp 으로 코도바 프로잭트를 만들고 플랫폼으로 안드로이드를 추가 합니다.




커멘드라인툴로 다음과같이 명령어를 주어서 플러그인을 myapp 프로잭트에 추가합니다.


cd myapp

cordova plugin add ../echo


3. 플러그인사용하기


cordova.exec 함수를 사용합니다.



자바스크립트쪽에서 cordova.exec 함수를 써서 Echo플러그인(service)의 echo 함수(action)를 호출하는 예 입니다.


cordova.exec(function(param) {

            console.log(param);

        }, function(err) {

            console.log('Nothing to echo.');

        }, "Echo", "echo", ['hello plugin!']);











And