Languages

Menu
Sites
Language
How to use this old bluetooth code?

I found the source codes about bluetooth web app. However when I bulild and run as Tizen web app only I can meet HTML screen. I cannot click anything... such as bluetooth searching, connecting so on...

I already referenced Bluetooth guide. https://developer.tizen.org/ko/development/guides/web-application/connectivity-and-wireless/bluetooth

But it's hard to understand...

How can I use this old codes or the codes on Bluetooth guide?

device version is mobile 2.4 and I use Tizen z3

블루투스 검색 == Bluetooth Searching

블루투스 연결 == Bluetooth connection

주변 기기 찾기 == Finding devices

블루투스 데이터 전송 == Bluetooth data sending

선택된 디바이스 == selected device

디바이스 연결 == Device connect

데이터 보내기 == Send data

index.html

<!DOCTYPE html>
<html>
 
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,user-scalable=no"/>
<script src="lib/jquery.js"></script>
<script type="text/javascript" src="lib/tau/mobile/js/tau.js" data-build-remove="false"></script>
<link rel="stylesheet"  href="lib/tau/mobile/theme/default/tau.css">
 
<script src="js/main.js"></script>
 
<title>Tizen Web IDE - Template - Tizen - Tizen Web UI Framework - Single-Page</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
 
<body>
    <div data-role="page" id="pageList">
        <div data-role="header" data-position="fixed">
            <h1>블루투스검색</h1>
        </div><!-- /header -->
        <div data-role="content">
            <div data-role="button" id="btnCreate">블루투스 연결</div>
            <div id="divAdapter"></div>
            <div data-role="button" id="btnDiscovery">주변기기찾기</div>
            <ul data-role="listview" id="listDevice" data-fastscroll="true">
            </ul>
        </div><!-- /content -->
    </div><!-- /page -->
    <div data-role="page" id="pageDetail">
        <div data-role="header" data-position="fixed">
            <h1>블루투스데이터전송</h1>
        </div><!-- /header -->
        <div data-role="content">
            <label>선택된디바이스</label>
            <input type="text" id="txtDeviceName">
            <input type="text" id="txtDeviceAddress">
            <div data-role="button" id="btnDevice">디바이스연결</div>
            <div id="divDeviceInfo"></div>
            <hr/>
            <input type="text" id="txtSendData">
            <div data-role="button" id="btnSendData">데이터보내기</div>
            <div id="divReceiveData"></div>
        </div><!-- /content -->
    </div><!-- /page -->    
</body>
</html>

main.js

var backEventListener = null;
 
var unregister = function() {
    if ( backEventListener !== null ) {
        document.removeEventListener( 'tizenhwkey', backEventListener ); //뒤로가기
        backEventListener = null;
        window.tizen.application.getCurrentApplication().exit(); //현재 앱 나가기
    }
}
//상단은 반복 코드
var adapter;
var listDeviceElement;
var listDevice;
 
 
var cancelDiscovery = function() {
   adapter.stopDiscovery(function() { //탐색 종료
       console.log("Stop discovery success.");
   },
   function (e) {
       console.log("Error while stopDiscovery:" + e.message);
   });
}
 
var startDiscovery = function() {
var discoverDevicesSuccessCallback = {
        onstarted: function() {
             console.log ("찾기시작") ;
        },
        ondevicefound: function(device) { //디바이스를 찾았음, 리스트에 디바이스 이름, 주소 추가
             listDevice.addItem("<li devicename='" + device.name + "' deviceaddress='" + device.address + "' >Name: " + device.name + ", Address: " + device.address + "</li>");
             listDevice.refresh(); //디바이스 새로고침
             cancelDiscovery(); //탐색 취소
        },
        ondevicedisappeared: function(address) { //디바이스 사라짐
        },
        onfinished: function(devices) { //종료?
        }
     };
 
     // 소캣찾기
     adapter.discoverDevices(discoverDevicesSuccessCallback, function(e) {
         alert("디바이스를 찾을 수 없습니다.")
     });
}
 
var onSetPoweredError = function(e) {
alert(e.message);
}
var onSocketError = function(err){
console.log(err);
alert(err.name);
}
var onSocketConnected = function(socket) {
    console.log ("소켓이 연결됨");
    socket.onmessage = function () {
       document.getElementById("divReceiveData").innerHTML = //HTML의 divReceiveData에 읽어온 문자 넣음
      String.fromCharCode.apply(String, socket.readData()) + "<br/>" + 
      document.getElementById("divReceiveData").innerHTML;
    };
    socket.onclose = function() {
       alert("소켓이 종료되었습니다." + socket.peer.name);
    };
 
    // Sends data to peer. 데이터 전송
    tau.event.on (document.getElementById("btnSendData"),"tap", function(){
    var sendData = document.getElementById("txtSendData").value;
    var sendDataArray = new Array();
    for (var i = 0; i < sendData.length; i++)
    {
    sendDataArray[i] = sendData.charCodeAt(i);
    }
    socket.writeData (sendDataArray);
    });
}
//디바이스가 준비 되었을 경우
onDeviceReady = function(device){
console.log(device);
document.getElementById("divDeviceInfo").innerHTML = 
"uuids:" + device.uuids + "<br>" + 
"name:" + device.name + "<br>" + 
"address:" + device.address + "<br>" + 
"isBonded:" + device.isBonded + "<br>" + 
"deviceClass:" + device.deviceClass + "<br>";
console.log("-----" + device.uuids);
var uuids = "" + device.uuids; // string형태로 변경
if (device.uuids.indexOf(uuids) != -1) {
device.connectToServiceByUUID(uuids, onSocketConnected, onSocketError );
}
else{
alert("연결할수 없습니다.")
}
}
onBondingSuccess = function(device){
console.log("-----")
console.log(device);
document.getElementById("divDeviceInfo").innerHTML = 
"uuids:" + device.uuids + "<br>" + 
"name:" + device.name + "<br>" + 
"address:" + device.address + "<br>" + 
"isBonded:" + device.isBonded + "<br>" + 
"deviceClass:" + device.deviceClass + "<br>";
console.log("-----" + device.uuids);
adapter.registerRFCOMMServiceByUUID(serviceUUID, "My service", 
            registerSuccessCallback, onError);
}
 
//Initialize function
var init = function () {
//반복 코드
    if ( backEventListener !== null ) {
        return;
    }//반복코드
    
    // TODO:: Do your initialization job
    console.log("init() called");
    
    listDeviceElement = document.getElementById("listDevice");
    listDevice = tau.widget.Listview(listDeviceElement);
    //목록에서 디바이스 선택
    tau.event.on(listDeviceElement, "tap", function(event){
    document.getElementById("txtDeviceName").value = 
    event.target.getAttribute("devicename"); //디바이스 이름
    document.getElementById("txtDeviceAddress").value = 
    event.target.getAttribute("deviceaddress"); //디바이스 주소
    tau.changePage("#pageDetail");   
    });
    //어댑터 생성
    tau.event.on(document.getElementById("btnCreate"), "tap", function(){
    adapter = tizen.bluetooth.getDefaultAdapter(); // 기본 어댑터를 가져온다.
    document.getElementById("divAdapter").innerHTML = "어댑터생성";
    });
    //주변 기기 선택
    tau.event.on(document.getElementById("btnDiscovery"), "tap", function(){
    adapter.setPowered(true, startDiscovery, onSetPoweredError);
    });
    //디바이스 생성
    tau.event.on(document.getElementById("btnDevice"), "tap", function(){
    adapter.getDevice(document.getElementById("txtDeviceAddress").value,
    onDeviceReady, 
    function(e) { alert(e.message); });
    })
    //아래는 반복코드
    var backEvent = function(e) {
        if ( e.keyName == "back" ) {
            try {
                if ( $.mobile.urlHistory.activeIndex <= 0 ) {
                    // if first page, terminate app
                    unregister();
                } else {
                    // move previous page
                    $.mobile.urlHistory.activeIndex -= 1;
                    $.mobile.urlHistory.clearForward();
                    window.history.back();
                }
            } catch( ex ) {
                unregister();
            }
        }
    }
    
    // add eventListener for tizenhwkey (Back Button)
    document.addEventListener( 'tizenhwkey', backEvent );
    backEventListener = backEvent;
    //위는 반복코드
};
//아래는 반복코드
$(document).bind( 'pageinit', init );
$(document).unload( unregister );

Responses

2 Replies
Armaan-Ul- Islam

I ran the Project on my Samsung Z3, HTML UI seems okay. But the functions are not working. For my case, When I ran the application on Debug Mode, I found on Console:

 

jQuery.js, tau.js, tau.css files are not found.

Please Create new web app using 'TAU Basic' template, then paste the code. That would give you the tau.js and tau.css. Download jQuery.js from internet and paste on Project Directory. Then Import the jQuey.js script in your index.html.

Now, If the file missing isn't your case then I would suggest the best solution: 'Debug As> Tizen Web Application'.

Then You might debug your app and inspect the issue on Console/Web Inspector.

명훈 심

I thought that I already inserted jquery file in the lib folder... thank you.