webOS Article/2. Luna Service 활용하기

Luna Service API 이용하기

한형주 2021. 7. 24. 16:16

이 포스트는 webOS OSE 개발자 사이트: WebOSServiceBridge , webOS OSE 개발자 사이트: com.webos.notification을 참고하여 작성되었습니다.

 

 

전체 코드 미리보기


오늘 공부할 Luna Service API, 그 중에서도 toast 사용하기의 전체 코드입니다.

<!--
Copyright (c) 2020 LG Electronics Inc.

SPDX-License-Identifier: Apache-2.0
-->

<!DOCTYPE html>
<html>
<head>
<title>Example Web App</title>
<style type="text/css">
    body {
        background-color:#202020;
        vertical-align: middle;
        height: 100%;
        width: 100%;
    }
    .top {
        margin-top: 200px;
    }
    .mid {
        text-align: center;
    }
    h1 {
        vertical-align: middle;
        text-align:center;
        color:#FFFFFF;
    }
</style>

<script type="text/javascript">
    var bridge = new WebOSServiceBridge();
    function toastCallback(msg) {
        console.log("before-parse-response");
        var response = JSON.parse(msg);
        console.log(response);
    }
    function createToast() {
        var url = 'luna://com.webos.notification/createToast';
        
        bridge.onservicecallback = toastCallback;

        var params = {
            "message":"hello world"
        };
        console.log("before-bridge.call");
        bridge.call(url, JSON.stringify(params));
        console.log("after-bridge.call");  
    }
</script>
</head>
<body>
    <div class="top">
        <h1 id="txt_msg">Hello, Web Application!!</h1>
    </div>
    <div class="mid">
        <button onclick="createToast()">create toast</button>
    </div>
</body>
</html>

 

Luna Service API 호출하기 


먼저 https://webos-supporters.tistory.com/19 페이지를 참고하여 appinfo.json 파일에서 Luna Service API를 호출할 준비를 끝마칩니다.

 

1. WebOSServiceBridge object 생성

webOS OSE 2.0 이상부터는 이전 버전과 달리 WebOSServiceBridge Object를 사용하도록 변경되었습니다. 1.X 버전 사용에 대한 Luna Service API 사용방법은 'Luna Service API 호출하기' 맨 아래를 참고바랍니다.

 

  • WebOSServiceBridge란 웹 앱이 Luna Bus에 액세스 할 수 있도록 제공되는 JavaScript API입니다. 이 API를 이용하여 웹 앱에서 LS2 API method를 호출할 수 있습니다. 
  • WebOSServiceBridge() 코드를 사용하여 bridge를 생성합니다. WebOS ServiceBridge 작성 방식은 아래와 같습니다.
var bridge = new WebOSServiceBridge();
  •  위와 같이 WebOSServiceBridge Object를 한 번 생성한 후, URL 및 매개 변수 값을 변경하여 다시 사용하는 것이 좋습니다. 모든 함수 호출에 대해 WebOSServiceBridge Object를 만들면 메모리가 낭비됩니다.

 

 

 

* 2.0미만 버전에서는 webOS 라이브러리를 사용하면 web app에서 LS2 API method를 호출할 수 있습니다.

더보기
  • webOS 라이브러리 준비
    - CLI(명령줄 인터페이스) 도구의 "기본" 템플릿을 사용하여 웹 앱을 만드는 경우, 웹 앱은 웹에 webOS 라이브러리를 이미 포함합니다. webOSjs-0.1.0 디렉토리로 존재하며, index.html 파일에 라이브러리가 포함되어 있습니다. 이 경우 라이브러리를 가져오기 위해 코드를 추가할 필요가 없으므로 이 단계를 건너뛸 수 있습니다.

 

  • webOS 라이브러리 설치
    1. webOS 라이브러리 파일을 다운로드 및 압축 풀기
    2. index.html 파일에 webOS 라이브러리 추가
<script type="text/javascript" src="webOSjs-0.1.0/webOS.js"></script>​
  • webOS.service.request() 함수 구현
    webOS 라이브러리 포함 후 아래와 같이 webOS.service.request 방법을 사용하여 LS2 API를 호출합니다.
var subscriptionStatus = true; //change this to false to disable subscription
var request =
webOS.service.request("luna://com.webos.service.<required_service>/", {
	method:"<method_to_call>",
	parameters: {foo:"bar"
	},
    onSuccess: function(inResponse) {
    //....
    },
    onFailure: function(inError) {
    //....
    },
    subscribe: subscriptionStatus
});​

 

 

 

Luna Service API : com.webos.notification으로 toast 만들기


1. 서비스 url 불러오기

var url = 'luna://com.webos.notification/( Method name )';

이번 포스팅에서는 Luna Service API 중 notification을 이용하여 실습하기 때문에 url로 com.webos.notification을 추가합니다. Method name에는 사용할 method를 선언합니다.

var url = 'luna://com.webos.notification/createToast';

저희는 createToast method를 사용하여 toast알림을 띄우기 위해 위와 같이 선언해주었습니다.

 

2. method 사용하기

위와 같이 서비스 url을 불러옴으로써 그 서비스 url 안에 포함되어 있는 LS2 API method를 불러와 사용할 수 있습니다.

지금부터 그 방법을 자세하게 알아보겠습니다.

 

  • parameter
var params = {
            "message":"hello world"
        };

createToast method  parameter입니다.

createToast method  의  parameter

이 중 필수로 요구되는 parameter는 Required라고 적혀 있는 message 입니다.

Optional 인 parameter들은 필요할 시에는 params 에 , 로 나누어 넣어주어도 됩니다.

 

이번 실습에서는 필수 parameter만 사용하였습니다.

message라는 parameter는 toast 알림 창에 뜨는 알림 내용으로 ""안에 최대 60자 까지 넣어줄 수 있습니다.

 

  • method 호출
bridge.call(url, JSON.stringify(params));

bridge.call함수를 이용하여 LunaService 호출로 method를 호출합니다.

bridge.call함수에는 method의 url과 parameter값이 object로 저장된 params를 JSON.stringfy을 이용하여 문자열로 바꾼 값이 필요합니다.

 

 

3. callback 함수 등록

  • callback 함수 호출 : line 40
    • onservicecallback : 응답을 처리하기 위한 콜백 루틴을 등록합니다. line 32-36에서 생성한 callback 함수를 호출합니다.
  • 메소드 호출 : line 46
    • call : 루나 서비스를 호출하여 메소드를 호출합니다.
  • callback 함수 : line 32-36
    • call을 통해 루나 서비스로 호출한 응답(response)을 받습니다. 이 toastCallback 함수에서는 JSON.parse를 이용하여 문자열을 object로 변환하여 받습니다.
  • debugging(console.log) : line 33, 35, 45, 47 
    • 오류 발생 시, 빠른 오류 발견을 위해 콘솔창에 원하는 메세지를 띄우는 코드를 추가했습니다.

이번 시간에는 web app에서 Luna Service API 이용하는 방법을 배웠습니다. 다음 시간에는 Enact app에서 Luna Service API를 이용하는 방법을 배웁니다.