검색어 mqtt에 대한 글을 관련성을 기준으로 정렬하여 표시합니다. 날짜순 정렬 모든 글 표시
검색어 mqtt에 대한 글을 관련성을 기준으로 정렬하여 표시합니다. 날짜순 정렬 모든 글 표시

2013년 5월 6일 월요일

MQTT (Message Queue Telemetry Transport) 설명 및 관련 solution

이전 블로그에서 이전 함 (원본 글 2013/05/06 작성)

MQTT (Message Queue Telemetry Transport)


Presentations:

Aticles:


[Introduction]

- History  
1999년 Dr. Andy Stanford-Clark(IBM)와 Arlen Nipper of Arcom (Cirrus Link Solution)에 의해 만들어짐
2010년 royalty-free license로 publish됨.
2013년 5월 M2M telemetry data communication으로 OASIS 표준화 작업 시작.

아래에서 보겠지만 간략한 format의 protocol로 인해 M2M의 protocol로 자리매김 한 것으로 보임. 하지만 이 프로토콜이 자연스럽게 IOT 영역에서도 받아지는 분위기인지는 잘 모르겠음 워낙 다들 자신들이 IOT의 시작이라 외치니..

-  A lightweight network protocol used for publish/subscribe messaging between devices.
- MQTT is designed to be opensimple and easy to implement, allowing thousands of lightweight clients to be supported by a single server.
 : ideal for use in constrained environments or low-bandwidth networks with limited processing capabilities, small memory capacities and high latency
 : The MQTT design minimizes network bandwidth requirements while attempting to ensure reliability of delivery.




[MQTT Design Principles and Assumptions]

아래 굵은 글씨들이 특징들이겠지만 위에서 말했다시피 low-bandwidth/low performanced device에서의 사용성과 high latency 가 핵심이다.

1. Simplicity, simplicity, simplicity! 
2. Publish/subscribe messaging. 
3. Zero administration (or as close as possible). Behave sensibly in response to unexpected actions and enable applications to “just work” 
4. Minimize the on-the-wire footprint
5. Expect and cater for frequent network disruption (for low bandwidth, high latency, unreliable, high cost-to-run networks)… → Last Will and Testament
6. Continuous session awareness → Last Will and Testament
7. Expect that client applications may have very limited processing resources available.
8. Provide traditional messaging qualities of service where the environment allows. 
9. Data agnostic. Don't mandate content formats, remain flexible.


[Specification]

* specification 보면 protocol 설계 자체가 bit 단위다.. 경량화될 수 밖에..

- Fixed header



- 주요 Message Type 별 header
CONNECT
CONNACK
PUBLISH
SUBSCRIBE
UNSUBSCRIBE
PINGREQ
PINGRESP
DISCONNECT


[Quality of Service]

나름대로 간단한 방식의 QoS rule로 message delivery 방법을 지정하고 전달을 guarantee 하게 할 수 있다.

- QoS 0 - At most once delivery
 : 한번 전달 하고 마는 방식으로 시간, packet 사용량은 적으나 메세지 전달은 guarantee 할 수 없음.
 * deliver the message once, with no confirmation.
 : A response is not expected and no retry semantics are defined in the protocol. 
 : This is the least level of Quality of Service and from a performance perspective, adds value as it’s the fastest way to send a message using MQTT. 
 : A QoS 0 message can get lost if the client unexpectedly disconnects or if the server fails.

The table below shows the QoS level 0 protocol flow.
ClientMessage and directionServer
QoS = 0PUBLISH
---------->
Action: Publish message to subscribers


- QoS 1 - At least Once Delivery
 : 메세지 전달 후 server에서 수신확인 메세지를 받아 처리하는 방식으로 메세지 전달 여부는 확인 가능.
 * deliver the message at least once, with confirmation required.
 : For this level of service, the MQTT client or the server would attempt to deliver the message at-least once. But there can be a duplicate message.

 The table below shows the QoS level 1 protocol flow.
ClientMessage and directionServer
QoS = 1
DUP = 0
Message ID = x
Action: Store message
PUBLISH
---------->
Actions:
  • Store message
  • Publish message to subscribers
  • Delete message
Action: Discard messagePUBACK
<----------


- QoS 2 - Exactly once delivery
 : 메세지 전달(publish), 수신 확인, 메세지 삭제, 메시지 전달 완료의 절차로 message 전달(publish)을 확인하는 거침으로 메세지 전달을 최대한 guarantee함.
 * deliver the message exactly once by using a four step handshake
 : This is the highest level of Quality of Service. 
 : Additional protocol flows ensure that duplicate messages are not delivered to the receiving application. The message is delivered once and only once when QoS 2 is used.
  
ClientMessage and directionServer
QoS = 2
DUP = 0
Message ID = x
Action: Store message
PUBLISH
---------->
Action: Store message
or
Actions:
  • Store message ID
  • Publish message to subscribers
PUBREC
<----------
Message ID = x
Message ID = xPUBREL
---------->
Actions:
  • Publish message to subscribers
  • Delete message
or
Action: Delete message ID
Action: Discard messagePUBCOMP
<----------
Message ID = x




[Topic]
* UTF-8 encoded string
* 모든 MQTT Message는 topic 기반으로 publish되며 별도 설정 방법이 필요하지 않고 message를 publish하는 것으로 topic 설정
* topic들은 계층형 구조를 가질 수 있으며 topic level separator(/)를 통해서 계층이 구분되어 진다.
 ex)  sensors/COMPUTER_NAME/temperature/HARDDRIVE_NAME

* client들은 subscriptions을 생성하여 message를 전달 받을 수 있고 특정 topic을 선택할 수도 wildcards(+, #)를 사용해서 다수 topic들에 대해서 subscriptions을 생성할 수 있다. 
topic 관련하여 MQTT specification에서 설명하는 rule은 다음과 같다. 


= Topic semantics and usage 
When you build an application, the design of the topic tree should take into account the
following principles of topic name syntax and semantics:
 - A topic must be at least one character long.
 - Topic names are case sensitive. For example, ACCOUNTS and Accounts are two different topics.
 - Topic names can include the space character. For example, Accounts payable is a valid topic.
 - A leading "/" creates a distinct topic. For example, /finance is different from finance. /finance matches "+/+" and "/+", but not "+".
 - Do not include the null character (Unicode \x0000) in any topic.

The following principles apply to the construction and content of a topic tree:
 - The length is limited to 64k but within that there are no limits to the number of levels in a topic tree.
 - There can be any number of root nodes; that is, there can be any number of topic trees.


= Appendix A - Topic wildcards
- Topic level separator (/) 

- Multi-level wildcard 
 : The number sign (#) is a wildcard character that matches any number of levels within a topic
  . finance/stock/ibm/#
    => (O) finance/stock/ibm
    => (O) finance/stock/ibm/closingprice
    => (O) finance/stock/ibm/currentprice
    => (O) finance/stock/ibm/currentprice/test

  . The Multi-level wildcard(#) can be specified only on its own or next to the topic level separator(/)
    => (O) # 
    => (O) finance/# 
    => (X) finance#
  . The Multi-level wildcard(#) must be the last character used within the topic tree
    => (O) finance/#
    => (X) finance/#/closingprice
  . finance/# == finance
  
- single-level wildcard 
 : The plus sign (+) is a wildcard character that matches only one topic level.

  . finance/stock/+ 
    => (O) matches finance/stock/ibm
    => (O) finance/stock/xyz
    => (X) finance/stock/ibm/closingprice
  . The single-level wildcard(+) must be used next to the topic level separator(/)
    => (O) finance/+ 
    => (O) finance/+/ibm 
    => (X) finance+    
  . finance/+  !=  finance

* Topic에 대한 간단한 설명


122811_0619_FacebookM3.png






[MQTT realted software]


Capabilities

ServerQoS 0QoS 1QoS 2authbridge$SYSSSLdynamic topics
Mosquitto
RSMB
WebSphere MQ
Apache Apollo
Apache ActiveMQ?????
webMethods Nirvana Messaging§
RabbitMQ
MQTT.js§
moquette?????
Key: ✔ supported ✘ not supported ? unknown § see limitations


[Examples of MQTT Usage]

관련 기사

2018년 4월 18일 수요일

Socket.io, MQTT 관련 대충 정리

아 짜증나.. 쓰던글 다 날라감..
대충 다시 씀.

web server에서 mobile app으로 push를 보내야할 필요가 있어 이것 저것 찾아봄.

Push를 구현하기 위해서는 다양한 기술들이 있고 다양하게 쓰이는 듯 함.
Long polling, Web socket, Socket.IO, Server side event, messaging queue 등..

notification를 위해 요구되는 사항들로는
- Web server에서의 mobile app으로 push
- 100자 미만의 메세지 포함 가능
- 수초 정도의 delay 상관없음.
- client는 c/c++ 기반 mobile app


----------------------------------------------------------------------------------
Socket.io
----------------------------------------------------------------------------------

Socket.io 관련해서 아주 좋은 글이 여기 있었음.

실시간 서비스 경험기(배달운영시스템), 우아한형제들 기술 블로그
: http://woowabros.github.io/woowabros/2017/09/12/realtime-service.html

너무 자세히 삽질하셨던 내용이 정리되어 이대로 따라가기만 해도 좋을 듯.
c/c++ 기반의 mobile app으로 server로 접속해야 하므로 client는 Socket.IO C++ client를 사용함.

Socket.IO C++ Client
: https://github.com/socketio/socket.io-client-cpp

일단 socket.io 서버에 접속하는 client는 c/c++ 기반의 app이므로
위 Socket.IO C++ Client를 사용해서 테스트 앱을 빌드 했음.

위 library는 Boost library를 사용하므로 windows에서 빌드해서 설치했음.
빌드하는데 시간이 상당히 소요되며 최신 boost library를 사용할 경우 일부 수정이 필요함.
하지만 mobile platform이 boost library를 가지고 있다면 빌드해서 사용할 필요는 없겠지만 필요하다면 boost.asio 및 관련 header와 library들을 추출해서 사용해야 할 듯 하다.

언급한 boost 컴파일을 위해 수정한 부분을 적어 두었는데.. 날라가서 기억을 못하겠음.


그리고 Socket.io 사용 시 connection이 어떻게 될지 궁금해서 일단 테스트를 해봄.
Node.js + Socket.IO C++ Client 로 laptop(i5-6200U@2.30GHz, 8G)에서 naive하게 테스트를 해봄.

Node.js에서는 connection & ping 수신 log만 찍고
Socket.IO C++ client에서는 300개 connection을 만들고 10초 마다 10자리 내의 문자열과 함께 ping을 보냄.

이상하게 client에서 300개 이상을 보내게 되면 boost에서 exception이 발생해서 테스트 앱에서 300개 정도로 connection을 제한하고 test app을 하나씩 증가시키며 테스트 해봄.

laptop의 resource 한계로 인해 대략 6300개 정도의 connection(client 21개)이 연결되고 ping을 받는 것을 확인하긴 하였지만 뭐 거의 의미 없는 테스트니.. 그냥 참고만.

글구 실제 6300개 connection과 ping을 받는 node.js 서버의 경우 동작에 무리가 있어 제대로 동작한다고는 보기는 어려웠음. client들을 종료할 때 disconnection callback 처리도 거의 1분 정도 소요 되었음.. 하지만 실제 cloud 기반의 server들을 붙여서 테스트 해야 할 것 같음.

그래도 Connection을 지속적으로 유지하며 disconnect 되었을 때 다시 연결한다는 점에서는 적절한 notification을 위해 사용하기에는 괜찮아 보임.
다만 socket.IO가 boost.asio를 사용하고 raw socket보다는 사용하기 무겁다는 것과 connection 수가 단점이 되지 않을까 생각됨.


---------------------------------------------------------------------------------
MQTT
---------------------------------------------------------------------------------


MQTT 관련 글들.

MQTT 설명
https://www.joinc.co.kr/w/man/12/MQTT/Tutorial
http://charlie0301.blogspot.kr/search?q=mqtt


MQTT 적용을 통한 중계시스템 개선, 우아한형제들 기술 블로그
: http://woowabros.github.io/experience/2017/08/11/ost_mqtt_broker.html

MQTT 프로토콜 분석과 테스트
http://www.hardcopyworld.com/ngine/aduino/index.php/archives/2562

mosquitto를 windows 설치하기 위해서는 좀 까다롭다.
아래 블로그 참조.
: http://blog.naver.com/PostView.nhn?blogId=cjc07&logNo=220441942108&parentCategoryNo=&categoryNo=&viewDate=&isShowPopularPosts=false&from=postView

단 openssl 설치 시 좀 예전 버전을 설치해야 함.
처음에 Win32OpenSSL_Light-1_1_0h를 설치하였으나 원하는 파일들이 없어서 Win32OpenSSL_Light-1_0_2o를 설치하여 찾음.


Eclipse Paho MQTT C client
: https://github.com/hallower/paho.mqtt.c

마찬가지 이유로 c/c++ 기반의 app이므로 Paho MQTT C client를 사용함.
빌드를 하다보니 openssl을 사용해야 하는것 같은데 그냥 환경 설정하기 귀찮아서 주석처리하여 빌드함.

근데 Paho MQTT C client를 사용해서 복수의 connection을 생성하여 connect할 때마다 기존 것들에서 connection lost가 발생함. connection, connection option들을 모두 각각 사용하여 각 connection들이 상관이 없을 텐데.
sync sample, async sample들을 각각 테스트 해봐도 2개 이상 connection을 생성하면 앞의 connection이 connection lost 발생.. 원인을 모르겠음. 이것저것 바꿔보고 했지만 소용이 없었음.

그래서 Mosquitto와 함께 빌드된 mosquitto_sub를 windows shell script로 여러개를 실행하도록 하였는데 600개 정도를 만들다가 mosquitto server가 죽어버린다.
windows에서 connection 제약이 1024개 정도 된다고 하던데 그 이유는 아닌것 같고 심지어 subscribe 하는 간격을 1초 마다 시도해도 600개를 넘어서지 못한다.

하지만 600개를 만들면서 cpu 사용이나 메모리는 상당히 낮은 편이다. subscribe client의 footprint가 작아서 그런지 모르겠지만..

찾다 보니 mosquitto에서 1024개 이상 센싱 데이터를 처리할 경우 에러가 발생했다는 논문 문구가 있었음.
출처 : http://www.engineeringcode.net/1045


혹시나 몰라 test.mosquitto.org를 대상으로 subscribe를 시도해봤는데 하나의 IP에서 10개 정도의 connection을 제한하는 것처럼 보인다. 11개 이상을 subscribe할 경우 서버에서 연결을 거부한다.


그래서 mosca로 테스트 해봄.
: https://github.com/mcollina/mosca

mosca로 테스트 해보니 5300개 정도 subscribe하니 cpu, memory가 거의 full이 되어 더이상 subscribe, publish가 어렵다. 그래도 mosquitto보다는 훨씬 잘 동작하는 것 같음.
그리고 mosca를 standalone broker로 실행하여 테스트 한것이고 node.js와 함께 실행한 것은 아님.

MQTT는 별도의 broker를 준비해야한다는 점이 좀 단점이지만 pub-sub 구조의 형태 인점이 notification을 전달하기 위해 사용하기는 편리할것으로 보임.



그리고 이건 혹시나 나중에 사용할 지 몰라 남겨둠.

@echo off
echo ==============================
echo subscribe test
echo ==============================
echo.

for /L %%i in (1,1,1000) do call :sss %%i

pause>nul

:sss
  echo %~1
  START /B mosquitto_sub.exe -t csk
  
  set /a sum=%~1%%10
  if %sum% equ 0 (
echo "sleep"
ping 127.0.0.1 -n 2 > nul
  )


2014년 7월 14일 월요일

Tizen상에서 MQTT client 컴파일 하기 (with OpenSSL library)

Tizen 상에서 MQTT client들 중에서 C/C++ API들을 제공하는 solution 들을 테스트 하려 함.

대표적인 것은 Eclipse Paho와 libmosquitto 이며  (http://mqtt.org/wiki/doku.php/libraries)
대략 봤을 때는 두 solution들의 feature는 거의 유사하지만
코드 상으로는 libmosquitto가 다소 simple한 것 같아보임
(libmosquitto LOC 대략 7264, Paho LOC 대략 18395)..
(하지만 Paho도 simple한 것은 사실, 하지만 워낙 MQTT protocol 자체가 simple 하니...)

MQTT client를 테스트 해보려면
. 위 client library를 컴파일 해야 하고
. library 컴파일에 필요한 OpenSSL library를 컴파일 해야 하고
. application을 만들어 sample code를 포팅해야 함.



[MQTT client library compile]

1. Paho, libmosquitto를 tizen shared library로 컴파일 하기 위해서는
tizen sdk > File > New > Tizen Native Project > Library > Shared Library 프로젝트를 생성한다.


2. library 파일들을 inc, src 폴더로 복사한다.
 . Paho : sample 을 제외한 library 파일들을 복사
 . libmosquitto : python, js 파일들을 제외하고 복사

3. project setting
 . SSL/TLS 지원을 위해 preprocessor, include path 설정
  : Project properties > C/C++ Build > Settings > C++ Compiler/C Compiler > Preprocessor/Symbols
    >  Paho project : "OPEN_SSL", libmosquitto : "WITH_TLS" 설정
  : Project properties > C/C++ Build > Settings > C++ Compiler/C Compiler > Includes 에 OpenSSL source의 include path 설정 (아래)



[OpenSSL library compile]

Paho, libmosquitto에서 SSL/TLS 설정을 사용하고자 할 경우
Tizen에서 돌아가야할 OpenSSL의 libssl.so, libcrypto.so 가 필요함.
Tizen platform내의 OpenSSL shared library를 사용할 수 있겠지만
방법을 모르는 관계로 so를 만들어서 app과 함께 deploy해서 사용할 생각임.

일단 OpenSSL 최신버전을 다운 받을 수 있겠지만 Tizen용으로 빌드를 해야 하기에 git repository에 있는 것을 다운받아 컴파일 하자.
참고
 - Tizen GBS : https://source.tizen.org/ko/documentation/reference/git-build-system
 - GBS 빌드 방법 (by 서주영님)
    . source code download : http://seoz.egloos.com/3896390
    . GBS 설정 : http://seoz.egloos.com/3900549
 - cocos2d-x 포팅 후기 (by 이재홍님) : http://pyrasis.com/cocos2d-x/2013/05/19/cocos2d-x-tizen-port-post-mortem/


1. gerrit 등록 및 GBS 설정
 . gbs.conf는 는 tizen 홈피에 있는 것을 받아서 계정 정보(id, password) 추가
 . buildconf 주석'#' 처리
 . 서주영님 게시물 GBS 설정 3번 항목에 따라 URL 수정

2. OpenSSL repository clone
 . 일단 framework/security/openssl 를 다운 받았음... 사실 OpenSSL repository는 framework, platform 두개가 있는데 차이를 모르겠고 platform은 dependency가 있어 그냥 framework을 다운 받음.

3. 빌드 (gbs build -A armv7l)

빌드된 결과물은 rpm으로 나오겠지만 일단 so만 필요하므로
.gbs.conf 의 buildroot 경로에서 빌드 결과물 중 libssl.so, libcrypto.so 를
밑의 폴더에서  tizen app의 lib 폴더로 복사

~/GBS-ROOT-profile.tizen/local/BUILD-ROOTS/scratch.armv7l.0/home/abuild/rpmbuild/BUILD/openssl-1.0.0f

* 빌드 option 참고 (위쪽 서주영님 포스팅 발췌)

만약 빌드가 잘 안 되거나 GBS 설정 파일의 url을 바꾼 경우라면 아래와 같이 --clean 옵션을 이용하여 빌드를 하시기 바랍니다.

gbs build -A i586 --clean

만약 다운로드 받은 타이젠 소스코드를 수정하셨다면 아래와 같이 --include-all 옵션을 주어야 합니다.
GBS는 git에 커밋(commit)이 된 소스코드를 이용하여 빌드를 하기 때문에 소스코드를 수정했다면 git에 커밋을 해야 GBS로 빌드할 수 있습니다.
만약 커밋을 하지 않고 소스코드를 빌드하고 싶다면 --include-all 옵션을 주어야 합니다.

gbs build -A i586 --include-all

빌드 시 아키텍처를 선택하지 않았다면 기본적으로 i586으로 빌드가 되며 arm으로 빌드를 하려면 -A 옵션과 함께 armv7l을 인자로 주어야 합니다. (마지막의 l은 L의 소문자입니다.)

$ gbs build -A armv7l


[MQTT sample client app compile & run]

일단 MQTT client sample application을 만들어야 하므로
간단한 Tizen Form-based Application project를 만들어서
client 소스코드를 복사한다.

Paho의 경우 src/samples 내 pubsync.c, MQTTAsync_publish.c, MQTTAsync_subscribe.c 를 사용하고 mosquitto는 소스코드의 client 폴더 내 pub, sub sample를 사용

. 확장자를 cpp로 바꾸고
. main 함수의 이름을 바꾸고 header를 만들어 expose (단 naming mangling 방지를 위해 extern C 사용)
. sample들이 loop을 사용하므로 Tizen thread를 만들어 별도 thread에서 돌아가게 해야 함.
. application event handler에서 thread를 생성해서 실행하도록 코드 작성


그리고 application에서 위에서 만든 libpaho.so, libmosquitto.so 를 사용해야 하므로
application project에서 library project를 reference 하고 include path, library path & library 설정이 필요함 이 부분은 아래 링크에서 잘 설명 되어 있음.

- 오픈소스를 활용한 Tizen 용 web server 포팅 : http://tizenschools.com/?p=40
 . library들이 함께 사용하는 library들 - libdl, libssl, libcrypto

- 또한 SSL/TLS 를 사용하고자 할 경우 CA의 인증서가 필요하므로 이를 App과 함께 배포하고자 shared/data에 복사하고 mosquitto_tls_set, mosquitto_tls_opts_set 설정 함.
 * app과 자동배포가 안되는지 app에서 shared/data에 인증서가 없다. 그냥 public space에 인증서를 sdb pull로 밀어 넣고 해당 path로 접근하게 함.

2013년 5월 7일 화요일

Mosquitto - An Open Source MQTT v3.1 Broker

이전 블로그에서 이전 함 (원본 글 2013/05/07 작성)

Mosquitto

An Open Source MQTT v3.1 Broker



- Mosquitto is an open source message broker
- implements the MQTT protocol version 3.1

 - Client API programming languages
 : C/C++
 : Python
 : JS with WebSocket

- BSD License

* Facebook using MQTT



[Sample compile & run]

- Server

 cc@cc-System:~$ tar zxvf mosquitto-1.1.3.tar.gz 
cc@cc-System:~$ cd mosquitto-1.1.3/
cc@cc-System:~/mosquitto-1.1.3$ ls
aclfile.example  client          compiling.txt  config.mk  installer  LICENSE-3rd-party.txt  logo      man   mosquitto.conf   pwfile.example  readme-windows.txt  service  test
ChangeLog.txt    CMakeLists.txt  config.h       examples   lib        LICENSE.txt            Makefile  misc  pskfile.example  readme.txt      security            src

cc@cc-System:~/mosquitto-1.1.3$ make

set -e; for d in lib client src; do make -C ${d}; done
make[1]: Entering directory `/home/cc/mosquitto-1.1.3/lib'
cc -Wall -ggdb -O2  -I. -I.. -I../lib -fPIC -DWITH_TLS -DWITH_TLS_PSK -DWITH_THREADING -c mosquitto.c -o mosquitto.o
cc -Wall -ggdb -O2  -I. -I.. -I../lib -fPIC -DWITH_TLS -DWITH_TLS_PSK -DWITH_THREADING -c logging_mosq.c -o logging_mosq.o

cc mosquitto.o bridge.o conf.o context.o database.o logging.o loop.o memory_mosq.o persist.o net.o net_mosq.o read_handle.o read_handle_client.o read_handle_server.o read_handle_shared.o security.o security_default.o send_client_mosq.o send_mosq.o send_server.o service.o subs.o util_mosq.o will_mosq.o -o mosquitto  -ldl -lm -lssl -lcrypto
cc -Wall -ggdb -O2  -c mosquitto_passwd.c -o mosquitto_passwd.o
cc mosquitto_passwd.o -o mosquitto_passwd  -lcrypto
make[1]: Leaving directory `/home/cc/mosquitto-1.1.3/src'
set -e; for d in man; do make -C ${d}; done
make[1]: Entering directory `/home/cc/mosquitto-1.1.3/man'
make[1]: Nothing to be done for `all'.
make[1]: Leaving directory `/home/cc/mosquitto-1.1.3/man'

cc@cc-System:~/mosquitto-1.1.3$ cd src/
cc@cc-System:~/mosquitto-1.1.3/src$ ./mosquitto
1367887027: mosquitto version 1.1.3 (build date 2013-05-07 09:36:34+0900) starting
1367887027: Using default config.
1367887027: Opening ipv4 listen socket on port 1883.
1367887027: Opening ipv6 listen socket on port 1883.
- Client

- client application을 실행하려면 mosquitto library 경로(mosquitto-1.1.3/lib)를 ldconfig에서 인식하도록 /etc/ld.so.conf.d/ 에 configuration을 저장 해줘야 한다.
- client 폴더의 mosquitto_pub, mosquitto_sub 를 실행하면 되고 관련 설명은 아래 참고
mosquitto_pub(1) – command line client for publishing 


- 서버 실행

 cc@cc-System:~/mosquitto-1.1.3/src$ ./mosquitto
1367891704: mosquitto version 1.1.3 (build date 2013-05-07 09:36:34+0900) starting
1367891704: Using default config.
1367891704: Opening ipv4 listen socket on port 1883.
1367891704: Opening ipv6 listen socket on port 1883.
1367893254: New connection from 127.0.0.1.
1367893254: New client connected from 127.0.0.1 as mosqsub/16299-cc-Sys.
1367893308: New connection from 127.0.0.1.
1367893308: New client connected from 127.0.0.1 as mosqpub/16317-cc-Sys.
1367893333: New connection from 127.0.0.1.
1367893333: New client connected from 127.0.0.1 as mosqpub/16391-cc-Sys.
1367893360: New connection from 127.0.0.1.
1367893360: New client connected from 127.0.0.1 as mosqsub/16406-cc-Sys.
1367893367: New connection from 127.0.0.1.
1367893367: New client connected from 127.0.0.1 as mosqpub/16408-cc-Sys.
1367893373: New connection from 127.0.0.1.
1367893373: New client connected from 127.0.0.1 as mosqpub/16409-cc-Sys.


- publish 
 cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_pub -t sensors/temperature -m 32 -q 1
cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_pub -t sensors/temperature -m 34 -q 1
cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_pub -t sensors/temperature -m 35 -q 1
cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_pub -t sensors/temperature -m 38 -q 1
cc@cc-System:~/mosquitto-1.1.3/client$ 


- event receiving by subscribers

 cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_sub -t sensors/temperature -q 1
32
34
35
38


cc@cc-System:~/mosquitto-1.1.3/client$ ./mosquitto_sub -t sensors/temperature -q 1
35
38



역시.. 분석은 나중에..

2013년 5월 8일 수요일

Message pushing on Android without GCM

이전 블로그에서 이전 함 (원본 글 2013/05/08 작성)

[Using MQTT in Android mobile applications]


 - Persistent TCP/IP connection with ping request every 20mins (wake up by AlaramManager)
 - Message lost will be happen during connection closed situation.

 GCM 안 쓰고 하려면 이 방법 밖에 없나.. ?


[How to Implement Push Notifications for Android]

 - Made sample application with same MQTT approach with above

[XMPP messaging pushing related article]


 - 뭐 5분씩 heartbeat을 날려도 배터리 소모에는 별 지장은 없을 거라는 얘기..


 XMPP is a good solution. I have used it for a push enabled, realtime, Android application. XMPP is powerful, highly extensible and easy to integrate and use.
There are loads of free XMPP servers (though out of courtesy you shouldn't abuse them) and there are open source servers you can run on one of your own boxes. OpenFire is an excellent choice.
The library you want isn't Smack as noted above, it's aSmack. But note, this is a build environment - you will have to build the library.
This is a calculation I did on battery life impact of an XMPP solution:
The Android client must maintain a persistent TCP connection by waking up periodically to send a heartbeat to the XMPP server.
This clearly imposes a cost in terms of power usage. An estimate of this cost is provided below:
  • Using a 1400mAh battery (as supplied in the Nexus One and HTC Desire)
  • An idle device, connected to an 3G network, uses approximately 5mA
  • The wake-up, heartbeat, sleep cycle occurs every 5 minutes, takes three seconds to complete and uses 300mA
  • The cost in battery usage per hour is therefore:
    • 36 seconds 300mA = 3mAh sending heartbeat
    • 3600 seconds 5mA = 5mAh at idle
    • 4:95 + 3 = 7:95mAh combined
  • A 1400mAh battery lasts approximately 11.6 days at idle and 7.3 days when  running the application, which represents an approximate 37% reduction in  battery life.
  • However, a reduction in battery life of 37% represents the absolute worst case in practice given that devices are rarely completely idle.
share|improve this answer



 - smack을 사용할 경우 connection을 계속 유지해준다. 내부적으로 heartbeat 관련 사항은 소스를 봐야 할것 같은데.

By default Smack will try to reconnect the connection in case it was abruptly disconnected. Use ConnectionConfiguration#setReconnectionAllowed(boolean) to turn on/off this feature. The reconnection manager will try to immediately reconnect to the server and increase the delay between attempts as successive reconnections keep failing. 
In case you want to force a reconnection while the reconnetion manager is waiting for the next reconnection, you can just use Connection#connect() and a new attempt will be made. If the manual attempt also failed then the reconnection manager will still continue the reconnection job. 


org.jivesoftware.smack
Interface ConnectionListener

All Known Implementing Classes:
AbstractConnectionListenerReconnectionManager

<pre>public interface ConnectionListener</pre>
Interface that allows for implementing classes to listen for connection closing and reconnection events. Listeners are registered with Connection objects.


Author:
Matt Tucker
See Also:
Connection.addConnectionListener(org.jivesoftware.smack.ConnectionListener),Connection.removeConnectionListener(org.jivesoftware.smack.ConnectionListener)

Method Summary
 voidconnectionClosed()
          Notification that the connection was closed normally or that the reconnection process has been aborted.
 voidconnectionClosedOnError(Exception e)
          Notification that the connection was closed due to an exception.
 voidreconnectingIn(int seconds)
          The connection will retry to reconnect in the specified number of seconds.
 voidreconnectionFailed(Exception e)
          An attempt to connect to the server has failed.
 voidreconnectionSuccessful()
          The connection has reconnected successfully to the server.
 


[Android Push Server MQTT]
- 작성자 : 이광운 ultrakain엣gmail.com

scalibility를 고려한 push server 관련 자료.
근데 결론이 뭐지? PT 자료만으로는 모르겠다.
Asynchronous socket I/O를 지원하는 framework에서는 당연히 reactor, proactor를 사용하는 것은 당연할테고..