SlideShare a Scribd company logo
1 of 13
제9회 공개SW 개발자 대회
< API >
S 코치
<목차 Context>
1. 프로젝트 표준화
2. 프로젝트 설명 : 프로젝트 폴더구조/역할
3. Server Side API
4. Client Side API
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////// [프로젝트 표준화]
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
❍ 본 프로젝트의 모든 소스코드는 다음과 같은 rule에 따라 설계 되었습니다.
1. 변수(필드) 및 함수(메소드)의 identifier는 java진영의 Camel-Case의 원칙으로 작성하였습니다,
다만 Python진영의 identifier 명명 규칙이 따로 존재 하므로 Phthon관련 file(*.py)은 파이썬 명명 규칙을 원칙으
로 하였습니다.
[Java, javascript, android 영역 예시]
[Python 영역 예시]
2. 모든 identifier는 그 기능을 대표 할 수 있는 identifier로 명명 하였습니다. 따라서 identifier만을 봤을 때 무슨
역할을 하는지 기대 할수 있습니다. 다만 분기문을 위한 단순 증감치는 한글자의 알파벳으로 명명 하여 사용됩니다.
아래 예시와 같습니다,
[예시]
3. 모든 identifier를 명명 할 때는 아래 예시와 같이 길더라도 Full-Context로써 명명하였습니다.
[예시]
4. 모든 코드의 line처리는 Scope( {...} )가 병렬적으로 대칭성을 이루게 표현 하여 가독성을 높혔습니다.
아래 [예시]와 같습니다.
[예시]
5. import된 lib는 종류별로 분류 하여 import하였습니다.
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////// [프로젝트 설명] : 프로젝트 폴더구조/ 역할
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
[프로젝트 1] ==> 서비스 프로그램
02.service project
|_001.client-side
| |_Gear : 기어 단말기
| |_ index.html : Gear 페이지
| |_ Gear.wgt : 빌드 패키징 된 위젯
| |_ lib : 라이브러리 폴더
|_ main.js : S코치 BusinessLogic
|_ smoothie.js : 3rd-party-lib for real time plotting
| |
| |
| |_Provider : 안드로이드 Provider
| |_appsrcmainjavacomsamsungandroidsdkaccessoryexamplehelloaccessoryprovider
| |_ClientSideActivity.java : Service에 바인딩 되는 Activity
| |_HelloAccessoryProviderService.java : Service로 백그라운드에서 BusinessLogic 처리
|
|
|
|_002.server-side
| |_test
| | |_test.py : Machine Learning 분류기 학습
| | |_user.py : ORM bining domain-object
| | |_test.pyc : test.py 백업파일
| | |_user.pyc : user.py 백업파일
| |_android: 서버의 classifier를 학습(Machine-Leraning)시키기위한 CSV files
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
[프로젝트 2] ==> 운영시 필요한 프로그램
01.operation project ==> 는 데이터 모으는 용도로 사용.
==> 스마트워치 + JAVA기반의 소켓서버프로그램 , 머신러닝을 위한 Feature 생성 프로그램.
==> 필요시 본인에 맞는 환경에 맞게 참고하여 개발하면 됨.
/////////////////////////////////////////////////////////////////////////////////////////////////
return value function name / Class name
filename[randomIndex]
best_music(file_dir)
사용자의 운동시간에따른 적합한 bpm을 갖는 노래
- file_dir : read 할 BPM정보 directory
tempwhat
supervised_classifier(directory, new_data)
Classifier를 학습시키는 함수.
- directory, new_data
라벨링이 되어있는 training/testing data-set관련 경로와 학
습 데이터 셋을 매개변수로 받는다.
lda, lda_array
run_LDA(X, y, num_components)
- X : 피쳐들
- y : 클래스 (라벨)
- num_components : 축소될 차원의 수
svc_rbf
run_rbf_SVM(X, y, C, gamma=0.7)
rbf커널과 SVM을 데이터를 이용하여 분류기를 학습
- X : 피쳐들
- y : 클래스 (라벨)
- C : 차원축소 상수
svc_linear
run_linear_SVM(X, y, C)
linear커널과 SVM을 데이터를 이용하여 분류기를 학습시킨
다.
- X : 피쳐들
- y : 클래스 (라벨)
- C : 차원축소 상수
pca, pca_array
run_PCA(dataframe, num_components)
축소할 차원 set을 이용하여 DF-data를 fitting 시킨다.
PCA라는 알고리즘으로 Dimension Reduction 한 결과를
return한다.
feature_df, class_df
load_data(directory)
ubuntu directory에 있는 classifier supervised learning 을 위
한 dataset load. Pthon-Numpy-Array형태로 return한다.
- CSV파일 : Dataset(Summation of Feature) =
training-data + testing-data
response
predict()
/predict/ URL이 POST방식으로 request됬을 때 실행하는 함
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////// [Server Side API]
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
[개발환경]
- ubuntu ver.12
- python 2.7 (3.4에서도 호완 됨을 확인.)
- flask: framework
- SQL-alchemy : ORM framework
- maria-DB
/////////////////////////////////////////////////////////////////////////////////////////////////
test.py 는 ubuntu OS 기반에서 작동하는 python2.7(zero-conficuration) + flask 기반의 웹 서버 프로젝트입니다.
Function, Class Summary
수. 분류기를 3개로 분할 하여, 분류기를 학습시킨다.
response
predictoneclassifier()
/predictoneclassifier/ URL이 POST방식으로 request됬을 때
실행하는 함수. 분류기 1개로 다양한 운동에 대해서 학습된
분류기가 있다. json객체가 setting된 request를 retrun 한다.
UPLOAD_FOLDER 서버 persistence layer 접근 가능 Directory
app.config['UPLOAD_FOLDER'] 서버 persistence layer 접근 가능 Directory 등록
class User(Base)
User Domain Object(Value Object) def __repr__(self)
Constructor and Description
HelloAccessoryProviderService() HelloAccessortProviderServce instance 초기화 작업
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////// [Client Side API]
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
[개발환경]
- window
- jdk1.7
- android , java
/////////////////////////////////////////////////////////////////////////////////////////////////
com.samsung.android.sdk.accessory.example.helloaccessoryprovider
Class HelloAccessoryProviderService
com.samsung.android.sdk.SAAgent
com.samsung.android.sdk.accessory.example.helloaccessoryprovider.HelloAccessoryProviderService
public class HelloAccessoryProvideService
extends SAAgent
HelloAccessoryProvideService 클래스는 타이젠 OS 기반의 갤럭시 Gear 단말기 시리즈 Web-App 과 Bluetooth 로
연결되는 Provider 역할 어플리케이션입니다. 따라서 이 앱은 안드로이드 OS 기반 앱이며, Gear 단말기와
Webserver 를 중계하는 peer-app 입니다.
한편, Backgoround(Service)에서 Gear 단말기에서 실시간으로 획득한 3 축-자이로스코프센서, 3 축-가속도센서,
운동시간 등 Raw-Data 가 실시간으로 PrioirtyQueue 자료구조에 모아집니다. Raw-Data 는 여러 가지 모듈화된
method 를 통하여 계산되며 결과적으로 추가적인 Pre-Processing(전처리)을 통한 42-Demension(차원) Feature 로
가공 되어집니다.
요컨데, 42-Demension(차원) Feature 들의 Data-Set 은 Webserver 로 전송되어 SVM(Support Vector
Machine)알고리즘 Supervised-Learning(Machine Learning 의 한 종류)으로 Training 된 Classifier(분류기)를 위한
Unseen-data 입니다.계산된 Feature, 운동시간, 축적 운동시간, 운동날짜(년/월/일) Data 는 json format 형식의 객체에
K, V 형식으로 setting 되며 HttpPost 방식으로 Webserver 로 전송 되어지며(request), Serverside 의 BusinessLogic 및
적절한 Work-Flow 를 통한 response 를 받아서 다시 Gear 단말기로 전달 합니다.
Since:
Android1.2.2
Constructor Summary
Modifier and Type Field and Description
static Comparator<String>
CASE_INSENSITIVE_ORDER
A Comparator that orders String objects as by
compareToIgnoreCase
private Socket
socket
기계학습을 위한 DATA 모을 시 자바프로그램과 연동 하기 위한
소켓
Public Boolean isAuthentication
기어 제품과 연결된 상태 저장
private String ip
유동적 ==> 데이터 모을 때 *.java 프로그램(ServerSide.java)과 통신.
private int port
PORT 번호
public static final String TAG
앱 이름
public Context mContext 컨텍스트(Context) 객체 할당
private final IBinder m_binder
Ibinder 객체. 인턴트로 액티비티티와 서비스 연결 및 자원 공유
HashMap<Integer, HelloAccessoryProviderConnection> mConnectionsMap
mConnectionsMap 객체
HashMap<Integer, HelloAccessoryProviderConnection> mConnectionsMapCopy
mConnectionsMap 객체 재 할당
PriorityQueue<String>
priorityQueue
SAP 통신으로 기어 2 로부터 0.2 초마다 넘어오는
7 개-unseen-data(String 형식)
int
noAccessCsvFile
종료버튼 눌렀을 때, priorityQueue 의 모든 Data-point 를 CSV 파일에
모두 Write 하고, 파일에 접근(Access) 안하는 상태.
int endButtonStatus
기어 2 의 종료버튼 클릭 여부. 0 클릭 안됨 / 1 클릭 됨
BufferedReader in
웹서버로 데이터 보내기전 완성된 CSV 파일 읽을 때 사용
BufferedWriter bw
CSV 파일로 출력
Public HelloAccessoryProviderConnection mMyConnection
HelloAccessoryProviderConnection 객체. 기어와 연결 할 때
String
columnName
Featrue CSV 파일 Column 명 ==> CSV 파일에 write 할것.
42-Demension
double summationExerciseDuringTime
운동시간 모으는 필드
Public
HelloAccessoryProviderConnection
mMyConnection
HelloAccessoryProviderConnection 객체. 기어와 연결 할 때 필요
String ip 자바프로그램의 IP주소
List<Double> exerciseDuringTimeA
운동 지속 시간
double duringExerciseSummation
exerciseDuringTime 필드를 summation(축적)
String musicFromServer
서버에서 추천 받은 노래 이름
MediaPlayer mMediaPlayer
MediaPlayer 객체 할당
String mMp3Path
musicFromServer 를 재 할당
String DEST_DIRECTORY
내부 저장소에 File Read/Wirte 하는 directory 할당.
String
DEST_MP3_DIRECTORY
노래 파일 있는 Directory.
/storage/emulated/legacy/Music/
String result
Intent 로 Activity 에서 보낸 값 get 할 필드 . onBind()에서 받는다.
private String exerciseName
운동 종류
private String exerciseCount
운동 횟수
private String exerciseKcal
소모 칼로리
Runnable mRun
사용자 심박수와 연관된 BPM 을 가진 노래(MP3) 재생 쓰레드
Field Summary
Method and Type Method and Description
void onCreate()
각종 초기화 작업. strict mode 추가
void setSocket(String ip, int port)
PC 소켓서버(.java 프로그램)와 연결하는 소켓 생성 메소드
IBinder onBind(Intent arg0)i
액티비티와 Binding
void onServiceConnectionRequested
서비스(Service)와 액티비티(Activity) 바인딩
byte[] getApplicationCertificate(Context context)
void
onEndButtonClicked()
기어2의 '종료 버튼' 눌렀을 때, '실행' 되는 method 모아 뒀던
unseen-data(priorityQueue)를 단말기 경로에 CSV(Comma
Serperated Values)형식으로 Write. 웹서버와 HttpPost통신. request /
response 처리. 42차원의 Feature값 생성
void onReceive(int channelId, byte[] data)
기어 단말기로부터 총 7가지 unseen-data를 받아서 가공
void
onSend2 (String a_message)
종료버튼 클릭하면 서버로직에서 판단된 데이터를 받아서 "기어2, 기
어S, 기어S2"로 전송
void onServiceConnectionLost(int errorCode)
Connection객체 destory됬을 때 호출 되는 call back method
static double calDuringExercise(Double[] array)
획득한 raw-data(센서값)을 Column별로 나눈 값의 운동 시간 계산
List<String[]> ColumnListForJson()
json의 K값으로 이용될 문자열 값 setting 하는 method
List<Double[]> columnArray(PriorityQueue<String> tempPriorityQueue)
Collection객체들을 Column별로 쪼개어, javaSE의 array로 변형
static double mean(Double[] array)
raw-data(센서값)을 Column별로 나눈 값의 산술 평균 계산 method
static double standardDeviation(Double[] array, int option)
획득한 raw-data(센서값)을 Column별로 나눈 값의 표준-편차 계산
static double variance(Double[] array)
raw-data(센서값)을 Column별로 나눈 값의 분산 계산
static double
valueMinMaxAmp(Double[] array, int option)
raw-data(센서값)을 Column별로 나눈 값의 최대값, 최소값 , 진폭 계
산
option: 0 – 최소값 , 1 – 최대값 , 2 – 진폭
static double
valueRMS(Double[] array)
raw-data(센서값)을 Column별로 나눈 값의 RMS(Root Mean Square)
계산
void
onServiceConnectionResponse
(SAPeerAgent peerAgent, SASocket thisConnection, int
result)
기어와 연결 성공시 callback method
Method Summary
Modifier and Type Field and Description
var
SAAgent
SAAgent 객체 할당 변수. 안드로이드 단말기 찾는 객체
var
SASocket
안드로이드 단말기와 연결하는 소켓
var
CHANNELID
소켓연결 채널 ID
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////// [Client Side API]
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
[개발환경]
- window
- jdk1.7
- tizen-sdk-2.3.1
/////////////////////////////////////////////////////////////////////////////////////////////////
classpath:Gear/js
main.js
main.js 는 기어용 앱의 BusinessLogic 이 들어있는 file 로써 삼성 갤럭시 Gear(Gear2, Gear S, Gear S2)단말기의
디바이스 센서를 이용하여 정보를 사용자로부터의 움직임값을 1 차적으로 생산해냅니다. 크게 2 가지의 센서로부터
가속도센서와 자이로스코프센서의 3-Axis 값을 0.2 초마다 획득하도록 설계되어있습니다. 시간주기는 refresh 변수의
값을 setting 하는 것으로 변화 줄 수 있지만 현재 기기의 하드웨어적인 성능을 고려하여 가장 정확하면서
Perfomance 를 고려한 수치가 0.2 초입니다. 이러한 방식으로 획득된 센서값과 센서값에 맞는 시간 데이터는
SAP(Samsung Accossory Protocol)통신을 통하여 접속된 안드로이드 OS 기반 Device 로 보냅니다. 이때 보내는
데이터를 본 프로젝트에서는 편의상 Raw-Data 라고 부릅니다.
main.js 는 크게 3 가지 부분으로 기능상 나눌수 있습니다. 첫째로 Peer 단말기를 찾아서 접속하여 SAP 통신을 위한
소켓 연결 부분, 둘째로 Raw-Data 를 획득하여 안드로이드단말기로 전달하기전 알맞게 변형시키는 부분, 마지막으로
안드로이드로부터 데이터를 받아서 classpath:index.html 파일의 해당되는 id 를 가진 Element 에 HTML 코드를
생산하는 부분으로 모듈화하여 설계하였습니다.
또한 본 프로젝트는 모든 삼성 갤럭시 기어에서 작동합니다. 2015 년 - 10 - 02 에 출시한 기어 S2 의 추가된 UI 및
기능도 추가 및 최적화 하였습니다. 따라서 한 가지 소스코드를 가지고 배포할 기기에 빌드 및 배포 하게 되면
배포기기에 맞게 알아서 UI 및 레이아웃이 변형이 되며 백그라운드에서 작동하는 BusinessLogic 은 변경 할 필요가
없습니다. 하위 tizen-sdk 버전과 호환 가능합니다.
Since:
tizen-sdk-2.3.1
tizen-sdk-2.3
Variable Summary
var
ProviderAppName
앱이름
var
endButtonStatus
정지버튼 클릭 상태
var
finalValueFromAndroid
단말기에서 기어로 서버로부터의 결과 값 보낸 상태. 동
시에 SAP통신 소켓 상태. peerAgentFindCallback변수
가 dependency
var
agentCallback
agentCallback 콜백 객체
var
peerAgentFindCallback
onsuccess()함수에서peerAgentFindCallback변수
dependency. 등록된 리스너가 피어단말기와 연결 요청
성공시 실행할 작업 단위
var
refresh
0.2초 쓰레드 발생 작업 시간
var
timer
디바이스 센서(가속도,자이로) 쓰레드 객체 저장
var
realTimer
운동시간 측정 쓰레드 객체 저장
var
currentTime
운동시간
var
ax
가속도센서 X축
var
ay
가속도센서 Y축
var
az
가속도센서 Z축
var
rotx
자이로센서 X축
var
roty
자이로센서 Y축
var
rotz
자이로센서 Z축
var
smoothie
리얼타임플로팅(RTP 파형) 객체
var
tempAx
RTP 가속도 X
var
tempRotx
RTP 자이로 Y
var
threadRTP
RTP 쓰레드 객체 할당 할 곳. 쓰레드 제어하기위해서
비고 Function and Description
addEventListener
window.onload = function ()
앱을 처음 키면 LOAD
ax = e.accelerationIncludingGravity.x;
ay = -e.accelerationIncludingGravity.y;
window.addEventListener('devicemotion',function(e)
이벤트리스너로 등록. tizen sdk 2.3.1
Function Summary
az = -e.accelerationIncludingGravity.z;
rotx = e.rotationRate.alpha;
roty = e.rotationRate.beta;
rotz = e.rotationRate.gamma;
devicemotionAPI에서 자이로스코프센서과 가속도
센서를 획득.
주의: classpath:config.xml파일에<tizen:privilege
name="http://tizen.org/feature/sensor.acceleromet
er"/>과<tizen:privilegename="http://tizen.org/featur
e/sensor.gyroscope"/> 추가.
currentTime
setTimerTest()
운동시간 측정 함수
N
fetch()
안드로이드 단말기와 SAP통신을 위한 소켓(SASocket)
열고, 데이터 주고 받는다.
N
onreceive(channelId, data)
- channelId : 기어입장에서 접속할 단말기 채널 ID
- data : 접속한 단말기로 보낼 데이터
N
disconnect()
classpath:index.html의 'END'버튼 클릭시 실행.
onsuccess()함수를 dependency한다.
N
connect()
classpath:index.html의 'START'버튼 클릭시 실행되는
Callback-function.onsuccess()함수를 dependency한
다.
N
onsuccess(agents)
connect() function이 Dependecy한다.
N
onerror(err)
gear단말기에서 안드로이드 단말기로 SAP 소켓 연결요
청 할때 Error 발생시 Callback function.
N
createHTML(log_string)
classpath:index.html 의 resultBoard라는 id에
Element생성

More Related Content

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

[공개SW개발자대회][최종발표][S코치][API ver.01]

  • 1. 제9회 공개SW 개발자 대회 < API > S 코치
  • 2. <목차 Context> 1. 프로젝트 표준화 2. 프로젝트 설명 : 프로젝트 폴더구조/역할 3. Server Side API 4. Client Side API
  • 3. ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// [프로젝트 표준화] ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ❍ 본 프로젝트의 모든 소스코드는 다음과 같은 rule에 따라 설계 되었습니다. 1. 변수(필드) 및 함수(메소드)의 identifier는 java진영의 Camel-Case의 원칙으로 작성하였습니다, 다만 Python진영의 identifier 명명 규칙이 따로 존재 하므로 Phthon관련 file(*.py)은 파이썬 명명 규칙을 원칙으 로 하였습니다. [Java, javascript, android 영역 예시] [Python 영역 예시]
  • 4. 2. 모든 identifier는 그 기능을 대표 할 수 있는 identifier로 명명 하였습니다. 따라서 identifier만을 봤을 때 무슨 역할을 하는지 기대 할수 있습니다. 다만 분기문을 위한 단순 증감치는 한글자의 알파벳으로 명명 하여 사용됩니다. 아래 예시와 같습니다, [예시] 3. 모든 identifier를 명명 할 때는 아래 예시와 같이 길더라도 Full-Context로써 명명하였습니다. [예시] 4. 모든 코드의 line처리는 Scope( {...} )가 병렬적으로 대칭성을 이루게 표현 하여 가독성을 높혔습니다. 아래 [예시]와 같습니다. [예시]
  • 5. 5. import된 lib는 종류별로 분류 하여 import하였습니다.
  • 6. ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// [프로젝트 설명] : 프로젝트 폴더구조/ 역할 ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// [프로젝트 1] ==> 서비스 프로그램 02.service project |_001.client-side | |_Gear : 기어 단말기 | |_ index.html : Gear 페이지 | |_ Gear.wgt : 빌드 패키징 된 위젯 | |_ lib : 라이브러리 폴더 |_ main.js : S코치 BusinessLogic |_ smoothie.js : 3rd-party-lib for real time plotting | | | | | |_Provider : 안드로이드 Provider | |_appsrcmainjavacomsamsungandroidsdkaccessoryexamplehelloaccessoryprovider | |_ClientSideActivity.java : Service에 바인딩 되는 Activity | |_HelloAccessoryProviderService.java : Service로 백그라운드에서 BusinessLogic 처리 | | | |_002.server-side | |_test | | |_test.py : Machine Learning 분류기 학습 | | |_user.py : ORM bining domain-object | | |_test.pyc : test.py 백업파일 | | |_user.pyc : user.py 백업파일 | |_android: 서버의 classifier를 학습(Machine-Leraning)시키기위한 CSV files ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// [프로젝트 2] ==> 운영시 필요한 프로그램 01.operation project ==> 는 데이터 모으는 용도로 사용. ==> 스마트워치 + JAVA기반의 소켓서버프로그램 , 머신러닝을 위한 Feature 생성 프로그램. ==> 필요시 본인에 맞는 환경에 맞게 참고하여 개발하면 됨. /////////////////////////////////////////////////////////////////////////////////////////////////
  • 7. return value function name / Class name filename[randomIndex] best_music(file_dir) 사용자의 운동시간에따른 적합한 bpm을 갖는 노래 - file_dir : read 할 BPM정보 directory tempwhat supervised_classifier(directory, new_data) Classifier를 학습시키는 함수. - directory, new_data 라벨링이 되어있는 training/testing data-set관련 경로와 학 습 데이터 셋을 매개변수로 받는다. lda, lda_array run_LDA(X, y, num_components) - X : 피쳐들 - y : 클래스 (라벨) - num_components : 축소될 차원의 수 svc_rbf run_rbf_SVM(X, y, C, gamma=0.7) rbf커널과 SVM을 데이터를 이용하여 분류기를 학습 - X : 피쳐들 - y : 클래스 (라벨) - C : 차원축소 상수 svc_linear run_linear_SVM(X, y, C) linear커널과 SVM을 데이터를 이용하여 분류기를 학습시킨 다. - X : 피쳐들 - y : 클래스 (라벨) - C : 차원축소 상수 pca, pca_array run_PCA(dataframe, num_components) 축소할 차원 set을 이용하여 DF-data를 fitting 시킨다. PCA라는 알고리즘으로 Dimension Reduction 한 결과를 return한다. feature_df, class_df load_data(directory) ubuntu directory에 있는 classifier supervised learning 을 위 한 dataset load. Pthon-Numpy-Array형태로 return한다. - CSV파일 : Dataset(Summation of Feature) = training-data + testing-data response predict() /predict/ URL이 POST방식으로 request됬을 때 실행하는 함 ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// [Server Side API] ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// [개발환경] - ubuntu ver.12 - python 2.7 (3.4에서도 호완 됨을 확인.) - flask: framework - SQL-alchemy : ORM framework - maria-DB ///////////////////////////////////////////////////////////////////////////////////////////////// test.py 는 ubuntu OS 기반에서 작동하는 python2.7(zero-conficuration) + flask 기반의 웹 서버 프로젝트입니다. Function, Class Summary
  • 8. 수. 분류기를 3개로 분할 하여, 분류기를 학습시킨다. response predictoneclassifier() /predictoneclassifier/ URL이 POST방식으로 request됬을 때 실행하는 함수. 분류기 1개로 다양한 운동에 대해서 학습된 분류기가 있다. json객체가 setting된 request를 retrun 한다. UPLOAD_FOLDER 서버 persistence layer 접근 가능 Directory app.config['UPLOAD_FOLDER'] 서버 persistence layer 접근 가능 Directory 등록 class User(Base) User Domain Object(Value Object) def __repr__(self) Constructor and Description HelloAccessoryProviderService() HelloAccessortProviderServce instance 초기화 작업 ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// [Client Side API] ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// [개발환경] - window - jdk1.7 - android , java ///////////////////////////////////////////////////////////////////////////////////////////////// com.samsung.android.sdk.accessory.example.helloaccessoryprovider Class HelloAccessoryProviderService com.samsung.android.sdk.SAAgent com.samsung.android.sdk.accessory.example.helloaccessoryprovider.HelloAccessoryProviderService public class HelloAccessoryProvideService extends SAAgent HelloAccessoryProvideService 클래스는 타이젠 OS 기반의 갤럭시 Gear 단말기 시리즈 Web-App 과 Bluetooth 로 연결되는 Provider 역할 어플리케이션입니다. 따라서 이 앱은 안드로이드 OS 기반 앱이며, Gear 단말기와 Webserver 를 중계하는 peer-app 입니다. 한편, Backgoround(Service)에서 Gear 단말기에서 실시간으로 획득한 3 축-자이로스코프센서, 3 축-가속도센서, 운동시간 등 Raw-Data 가 실시간으로 PrioirtyQueue 자료구조에 모아집니다. Raw-Data 는 여러 가지 모듈화된 method 를 통하여 계산되며 결과적으로 추가적인 Pre-Processing(전처리)을 통한 42-Demension(차원) Feature 로 가공 되어집니다. 요컨데, 42-Demension(차원) Feature 들의 Data-Set 은 Webserver 로 전송되어 SVM(Support Vector Machine)알고리즘 Supervised-Learning(Machine Learning 의 한 종류)으로 Training 된 Classifier(분류기)를 위한 Unseen-data 입니다.계산된 Feature, 운동시간, 축적 운동시간, 운동날짜(년/월/일) Data 는 json format 형식의 객체에 K, V 형식으로 setting 되며 HttpPost 방식으로 Webserver 로 전송 되어지며(request), Serverside 의 BusinessLogic 및 적절한 Work-Flow 를 통한 response 를 받아서 다시 Gear 단말기로 전달 합니다. Since: Android1.2.2 Constructor Summary
  • 9. Modifier and Type Field and Description static Comparator<String> CASE_INSENSITIVE_ORDER A Comparator that orders String objects as by compareToIgnoreCase private Socket socket 기계학습을 위한 DATA 모을 시 자바프로그램과 연동 하기 위한 소켓 Public Boolean isAuthentication 기어 제품과 연결된 상태 저장 private String ip 유동적 ==> 데이터 모을 때 *.java 프로그램(ServerSide.java)과 통신. private int port PORT 번호 public static final String TAG 앱 이름 public Context mContext 컨텍스트(Context) 객체 할당 private final IBinder m_binder Ibinder 객체. 인턴트로 액티비티티와 서비스 연결 및 자원 공유 HashMap<Integer, HelloAccessoryProviderConnection> mConnectionsMap mConnectionsMap 객체 HashMap<Integer, HelloAccessoryProviderConnection> mConnectionsMapCopy mConnectionsMap 객체 재 할당 PriorityQueue<String> priorityQueue SAP 통신으로 기어 2 로부터 0.2 초마다 넘어오는 7 개-unseen-data(String 형식) int noAccessCsvFile 종료버튼 눌렀을 때, priorityQueue 의 모든 Data-point 를 CSV 파일에 모두 Write 하고, 파일에 접근(Access) 안하는 상태. int endButtonStatus 기어 2 의 종료버튼 클릭 여부. 0 클릭 안됨 / 1 클릭 됨 BufferedReader in 웹서버로 데이터 보내기전 완성된 CSV 파일 읽을 때 사용 BufferedWriter bw CSV 파일로 출력 Public HelloAccessoryProviderConnection mMyConnection HelloAccessoryProviderConnection 객체. 기어와 연결 할 때 String columnName Featrue CSV 파일 Column 명 ==> CSV 파일에 write 할것. 42-Demension double summationExerciseDuringTime 운동시간 모으는 필드 Public HelloAccessoryProviderConnection mMyConnection HelloAccessoryProviderConnection 객체. 기어와 연결 할 때 필요 String ip 자바프로그램의 IP주소 List<Double> exerciseDuringTimeA 운동 지속 시간 double duringExerciseSummation exerciseDuringTime 필드를 summation(축적) String musicFromServer 서버에서 추천 받은 노래 이름 MediaPlayer mMediaPlayer MediaPlayer 객체 할당 String mMp3Path musicFromServer 를 재 할당 String DEST_DIRECTORY 내부 저장소에 File Read/Wirte 하는 directory 할당. String DEST_MP3_DIRECTORY 노래 파일 있는 Directory. /storage/emulated/legacy/Music/ String result Intent 로 Activity 에서 보낸 값 get 할 필드 . onBind()에서 받는다. private String exerciseName 운동 종류 private String exerciseCount 운동 횟수 private String exerciseKcal 소모 칼로리 Runnable mRun 사용자 심박수와 연관된 BPM 을 가진 노래(MP3) 재생 쓰레드 Field Summary
  • 10. Method and Type Method and Description void onCreate() 각종 초기화 작업. strict mode 추가 void setSocket(String ip, int port) PC 소켓서버(.java 프로그램)와 연결하는 소켓 생성 메소드 IBinder onBind(Intent arg0)i 액티비티와 Binding void onServiceConnectionRequested 서비스(Service)와 액티비티(Activity) 바인딩 byte[] getApplicationCertificate(Context context) void onEndButtonClicked() 기어2의 '종료 버튼' 눌렀을 때, '실행' 되는 method 모아 뒀던 unseen-data(priorityQueue)를 단말기 경로에 CSV(Comma Serperated Values)형식으로 Write. 웹서버와 HttpPost통신. request / response 처리. 42차원의 Feature값 생성 void onReceive(int channelId, byte[] data) 기어 단말기로부터 총 7가지 unseen-data를 받아서 가공 void onSend2 (String a_message) 종료버튼 클릭하면 서버로직에서 판단된 데이터를 받아서 "기어2, 기 어S, 기어S2"로 전송 void onServiceConnectionLost(int errorCode) Connection객체 destory됬을 때 호출 되는 call back method static double calDuringExercise(Double[] array) 획득한 raw-data(센서값)을 Column별로 나눈 값의 운동 시간 계산 List<String[]> ColumnListForJson() json의 K값으로 이용될 문자열 값 setting 하는 method List<Double[]> columnArray(PriorityQueue<String> tempPriorityQueue) Collection객체들을 Column별로 쪼개어, javaSE의 array로 변형 static double mean(Double[] array) raw-data(센서값)을 Column별로 나눈 값의 산술 평균 계산 method static double standardDeviation(Double[] array, int option) 획득한 raw-data(센서값)을 Column별로 나눈 값의 표준-편차 계산 static double variance(Double[] array) raw-data(센서값)을 Column별로 나눈 값의 분산 계산 static double valueMinMaxAmp(Double[] array, int option) raw-data(센서값)을 Column별로 나눈 값의 최대값, 최소값 , 진폭 계 산 option: 0 – 최소값 , 1 – 최대값 , 2 – 진폭 static double valueRMS(Double[] array) raw-data(센서값)을 Column별로 나눈 값의 RMS(Root Mean Square) 계산 void onServiceConnectionResponse (SAPeerAgent peerAgent, SASocket thisConnection, int result) 기어와 연결 성공시 callback method Method Summary
  • 11. Modifier and Type Field and Description var SAAgent SAAgent 객체 할당 변수. 안드로이드 단말기 찾는 객체 var SASocket 안드로이드 단말기와 연결하는 소켓 var CHANNELID 소켓연결 채널 ID ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////// [Client Side API] ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////// [개발환경] - window - jdk1.7 - tizen-sdk-2.3.1 ///////////////////////////////////////////////////////////////////////////////////////////////// classpath:Gear/js main.js main.js 는 기어용 앱의 BusinessLogic 이 들어있는 file 로써 삼성 갤럭시 Gear(Gear2, Gear S, Gear S2)단말기의 디바이스 센서를 이용하여 정보를 사용자로부터의 움직임값을 1 차적으로 생산해냅니다. 크게 2 가지의 센서로부터 가속도센서와 자이로스코프센서의 3-Axis 값을 0.2 초마다 획득하도록 설계되어있습니다. 시간주기는 refresh 변수의 값을 setting 하는 것으로 변화 줄 수 있지만 현재 기기의 하드웨어적인 성능을 고려하여 가장 정확하면서 Perfomance 를 고려한 수치가 0.2 초입니다. 이러한 방식으로 획득된 센서값과 센서값에 맞는 시간 데이터는 SAP(Samsung Accossory Protocol)통신을 통하여 접속된 안드로이드 OS 기반 Device 로 보냅니다. 이때 보내는 데이터를 본 프로젝트에서는 편의상 Raw-Data 라고 부릅니다. main.js 는 크게 3 가지 부분으로 기능상 나눌수 있습니다. 첫째로 Peer 단말기를 찾아서 접속하여 SAP 통신을 위한 소켓 연결 부분, 둘째로 Raw-Data 를 획득하여 안드로이드단말기로 전달하기전 알맞게 변형시키는 부분, 마지막으로 안드로이드로부터 데이터를 받아서 classpath:index.html 파일의 해당되는 id 를 가진 Element 에 HTML 코드를 생산하는 부분으로 모듈화하여 설계하였습니다. 또한 본 프로젝트는 모든 삼성 갤럭시 기어에서 작동합니다. 2015 년 - 10 - 02 에 출시한 기어 S2 의 추가된 UI 및 기능도 추가 및 최적화 하였습니다. 따라서 한 가지 소스코드를 가지고 배포할 기기에 빌드 및 배포 하게 되면 배포기기에 맞게 알아서 UI 및 레이아웃이 변형이 되며 백그라운드에서 작동하는 BusinessLogic 은 변경 할 필요가 없습니다. 하위 tizen-sdk 버전과 호환 가능합니다. Since: tizen-sdk-2.3.1 tizen-sdk-2.3 Variable Summary
  • 12. var ProviderAppName 앱이름 var endButtonStatus 정지버튼 클릭 상태 var finalValueFromAndroid 단말기에서 기어로 서버로부터의 결과 값 보낸 상태. 동 시에 SAP통신 소켓 상태. peerAgentFindCallback변수 가 dependency var agentCallback agentCallback 콜백 객체 var peerAgentFindCallback onsuccess()함수에서peerAgentFindCallback변수 dependency. 등록된 리스너가 피어단말기와 연결 요청 성공시 실행할 작업 단위 var refresh 0.2초 쓰레드 발생 작업 시간 var timer 디바이스 센서(가속도,자이로) 쓰레드 객체 저장 var realTimer 운동시간 측정 쓰레드 객체 저장 var currentTime 운동시간 var ax 가속도센서 X축 var ay 가속도센서 Y축 var az 가속도센서 Z축 var rotx 자이로센서 X축 var roty 자이로센서 Y축 var rotz 자이로센서 Z축 var smoothie 리얼타임플로팅(RTP 파형) 객체 var tempAx RTP 가속도 X var tempRotx RTP 자이로 Y var threadRTP RTP 쓰레드 객체 할당 할 곳. 쓰레드 제어하기위해서 비고 Function and Description addEventListener window.onload = function () 앱을 처음 키면 LOAD ax = e.accelerationIncludingGravity.x; ay = -e.accelerationIncludingGravity.y; window.addEventListener('devicemotion',function(e) 이벤트리스너로 등록. tizen sdk 2.3.1 Function Summary
  • 13. az = -e.accelerationIncludingGravity.z; rotx = e.rotationRate.alpha; roty = e.rotationRate.beta; rotz = e.rotationRate.gamma; devicemotionAPI에서 자이로스코프센서과 가속도 센서를 획득. 주의: classpath:config.xml파일에<tizen:privilege name="http://tizen.org/feature/sensor.acceleromet er"/>과<tizen:privilegename="http://tizen.org/featur e/sensor.gyroscope"/> 추가. currentTime setTimerTest() 운동시간 측정 함수 N fetch() 안드로이드 단말기와 SAP통신을 위한 소켓(SASocket) 열고, 데이터 주고 받는다. N onreceive(channelId, data) - channelId : 기어입장에서 접속할 단말기 채널 ID - data : 접속한 단말기로 보낼 데이터 N disconnect() classpath:index.html의 'END'버튼 클릭시 실행. onsuccess()함수를 dependency한다. N connect() classpath:index.html의 'START'버튼 클릭시 실행되는 Callback-function.onsuccess()함수를 dependency한 다. N onsuccess(agents) connect() function이 Dependecy한다. N onerror(err) gear단말기에서 안드로이드 단말기로 SAP 소켓 연결요 청 할때 Error 발생시 Callback function. N createHTML(log_string) classpath:index.html 의 resultBoard라는 id에 Element생성