MySQL 레코드 자동 생성

Database 2017.04.16 19:04 Posted by 파란크리스마스

MySQL 레코드 자동 생성

출처 : MySQL Row Generator - Use The Index, Luke
[MySQL] 무작위 샘플 데이터 만들기

View 생성

CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n UNION ALL SELECT 1  UNION ALL SELECT 2  UNION ALL 
   SELECT 3   UNION ALL SELECT 4  UNION ALL SELECT 5  UNION ALL
   SELECT 6   UNION ALL SELECT 7  UNION ALL SELECT 8  UNION ALL
   SELECT 9   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
     FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_256 hi;

CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
     FROM generator_64k lo, generator_16 hi;

0부터 30까지 레코드 만들기

select *
  from generator_256
 where n < 31;

해당 월의 마지막 날까지 레코드 생성

MySQL의 내장함수 current_date로 오늘날짜를 가져와서 날짜함수 LAST_DAY로 해당 월의 마지막 일을 얻어 오고, DATE_FORMAT 함수의 %d로 일수를 조회 한 후에 generator_256 뷰를 이용해서 일수만큼 레코드를 생성해서 INTERVAL 을 이용해서 마지막 일자에서 n 필드의 값으로 빼면서 해당 월의 일수 만큼 레코드를 생성한다.

SELECT LAST_DAY(current_date) - INTERVAL n DAY dt
  FROM generator_256
 WHERE n < DATE_FORMAT(LAST_DAY(current_date), '%d');

해당 월의 통계 데이터 생성

select a.dt, IFNULL(SUM(b.level_request), 0)
  from (  SELECT LAST_DAY(current_date) - INTERVAL n DAY dt
            FROM generator_256
           WHERE n < DATE_FORMAT(LAST_DAY(current_date), '%d')
       ) a LEFT OUTER JOIN group2 b
       ON a.dt = DATE(b.date_request)
 group by a.dt
 order by a.dt
저작자 표시
신고

JQuery UI - Datepicker

Programming/JavaScript, Sencha 2017.04.09 18:57 Posted by 파란크리스마스

JQuery UI - Datepicker

출처 : Datepicker | jQuery UI
JQuery UI datepicker 한국어 적용 - 제타위키

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui.js"/>"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css"/>">
<title>Insert title here</title>
<script>
// Datepicker 오늘 날짜 설정
function setDatepickerToday(datepicker) {
	var d = new Date();
	datepicker.datepicker("setDate", new Date(d.getFullYear(), d.getMonth(), d.getDate()) );
}

// 한글화 설정
$.datepicker.setDefaults({
	dateFormat: 'yy-mm-dd',
	prevText: '이전 달',
	nextText: '다음 달',
	monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
	dayNames: ['일', '월', '화', '수', '목', '금', '토'],
	dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
	dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
	showMonthAfterYear: true,
	yearSuffix: '년'
});

$( function() {
	// datepicker 생성
	$( "#datepicker" ).datepicker({
		// 날짜를 선택했을 경우 이벤트 발생
		onSelect: function (dateText, inst) {
			alert('날짜선택 = ' + dateText);
		}
	});
	
	// 오늘 날짜 설정
	setDatepickerToday($( "#datepicker" ));
});
</script>
</head>
<body>
 
<p>날짜 : <input type="text" id="datepicker"></p>

</body>
</html>
저작자 표시
신고

MySQL - 일별통계, 주간통계, 월간통계

Database/SQL 2017.04.09 18:11 Posted by 파란크리스마스

MySQL - 일별통계, 주간통계, 월간통계

출처 : Error related to only_full_group_by when executing a query in MySql - Stack Overflow
[Mysql] DB일간 주간 월간 년간 통계 | database

sample 테이블 생성

CREATE TABLE `test_st` (
  `reg_date` date NOT NULL,
  `value` int(11) NOT NULL
);

INSERT INTO `test_st` (`reg_date`, `value`) VALUES
  ('2017-03-01', 4),
  ('2017-03-08', 2),
  ('2017-03-15', 4),
  ('2017-03-22', 4),
  ('2017-04-01', 9),
  ('2017-04-02', 1),
  ('2017-04-04', 2),
  ('2017-04-09', 4),
  ('2017-04-11', 2),
  ('2017-04-16', 4),
  ('2017-04-18', 5),
  ('2017-04-23', 3),
  ('2017-04-25', 4),
  ('2017-04-30', 4),
  ('2017-04-01', 5);

MySQL - 일별통계

SELECT DATE(`reg_date`) AS `date`, 
       sum(`value`)
  FROM test_st
 GROUP BY `date`;

MySQL - 주간통계

SELECT DATE_FORMAT(DATE_SUB(`reg_date`, INTERVAL (DAYOFWEEK(`reg_date`)-1) DAY), '%Y/%m/%d') as start,
       DATE_FORMAT(DATE_SUB(`reg_date`, INTERVAL (DAYOFWEEK(`reg_date`)-7) DAY), '%Y/%m/%d') as end,
       DATE_FORMAT(`reg_date`, '%Y%U') AS `date`, 
       sum(`value`)
  FROM test_st
 GROUP BY date;

MySQL - 월간통계

SELECT MONTH(`reg_date`) AS `date`, 
       sum(`value`)
  FROM test_st
 GROUP BY `date`;

기간별 통계

SELECT DATE(`reg_date`) AS `date`,
       sum(`value`)
  FROM test_st
 WHERE DATE(`reg_date`) >= STR_TO_DATE('2017-04-01', '%Y-%m-%d')
   AND DATE(`reg_date`) <= STR_TO_DATE('2017-04-10', '%Y-%m-%d')
 GROUP BY `date`;
저작자 표시
신고

CKEditor 4.6

Programming/Java 2017.04.09 17:29 Posted by 파란크리스마스

CKEditor 4.6

출처 : CKEditor 4.6
CKEditor not working after opening jQuery UI Dialog - Stack Overflow

CKEditor - JQuery UI Dialog와 같이 사용하기

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-ui.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/ckeditor/ckeditor.js"/>"></script>
<link rel="stylesheet" href="<c:url value="/resources/css/jquery-ui.css"/>">
<title>JQuery Dialog</title>
<script type="text/javascript">
// CKEditor 기본 경로 설정 - config.js의 경로 설정
window.CKEDITOR_BASEPATH = '<c:url value="/resources/ckeditor"/>';
//window.parent.CKEDITOR.tools.callFunction('콜백의 식별 ID 값', '파일의 URL', '전송완료 메시지')

// CKEditor 제거 함수 - CKEditor 생성 되어 있는지 확인 후 제거
function DestryoCKEditorInstances(textarea_name) {
	if (CKEDITOR.instances[textarea_name])	{
		CKEDITOR.instances[textarea_name].destroy();
	}
}

function insertPopUpForSubject(){
	// 팝업 다이얼로그
	$("#tabb_subject_insert").dialog({
		position : {
			my : 'center center',
			at : 'center top'
		},
		width : 800,
		//height : 800,
		modal : true,
		open: function( event, ui ) {
			// 팝업창 열릴때 CKEditor 설정
			CKEDITOR.replace( 'example_subject_insert' , {
				extraPlugins: 'uploadimage,image2',
				uploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor2.do"/>',
				filebrowserImageUploadUrl: '<c:url value="/dragdrop/fileUpload/ckeditor.do"/>'
			});
		},
		close: function () {
			// 반듯이 팝업창 닫힐때 제거 되어함
			DestryoCKEditorInstances('example_subject_insert');
		}
	});
}
</script>
</head>
<body>

<button class="button button2" onclick="javascript:insertPopUpForSubject();">문제 입력1</button>

<div id="tabb_subject_insert"  title="문제 입력!"  style="display:none">
	<table align="center" width="90%" border="0" cellspacing="0" cellpadding="0">
	<tr>
		 <td>seq</td>
		 <td><input type="text" size="20" id="seq_subject_insert" ></td>
	</tr>
	<tr>
		 <td>보기</td>
		 <td>
			<textarea id="example_subject_insert" name="example_subject_insert" form="usrform">Enter text here...</textarea>
		 </td>
	</tr>
	</table>
	<center>
		<button class="button button5" onclick="javascript:insert_subject1_complete(1);">입력 완료(과목1)</button>
		<button class="button button5" onclick="javascript:cancle_insert();">취 소</button>
	</center>
</div>

</body>
</html>


저작자 표시
신고

Spring MVC - 네이버 로그인 처리

Programming/Java 2017.04.03 16:05 Posted by 파란크리스마스

Spring MVC - 네이버 로그인 처리

네이버 로그인 API를 이용해서 네이버 계정으로 로그인 처리를 Spring 프레임웍에서 사용 할 수 있도록 간단하게 NaverLoginController를 작성해보았습니다. 임시로 로그인 결과값을 가지고 와서 tbluser2 테이블의 abcd 계정의 1111 암호를 사용하는 사용자로 로그인 되도록 고정했습니다. (authentication-provider 사용자가 제어 하는 부분은 따로 찾아서 적용필요)

bluexmas-security.xml

alias의 authenticationManager 이름은 NaverLoginController 에서 속성으로 사용

	<security:authentication-manager alias="authenticationManager">
		<security:authentication-provider>

			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select user_id username, pass password, 1 as enabled from tbluser2 where user_id = ?"
				authorities-by-username-query="select user_id username, 'ROLE_USER' authority from tbluser2 where user_id = ?" />

		</security:authentication-provider>
	</security:authentication-manager>

NaverLogInController.java

package com.bluexmas.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.math.BigInteger;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.SecureRandom;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;

@Controller
public class NaverLogInController {
	
	private String naverClientId = "네이버API_Client_ID";
	
	private String naverClientSecret = "네이버API_Client_Secret";
	
	private String state = "";
	
	@Autowired
	@Qualifier("authenticationManager")
	protected AuthenticationManager authenticationManager;
	
	/**
	 * 네이버 로그인 요청
	 * 
	 * @param request
	 * @param uri
	 * @return
	 */
	@RequestMapping(value = "/naverLogin.do")
	public String makeNaverRequestStatement(
			HttpServletRequest request,
			@RequestParam(value = "uri", required = false) String uri) 
	{
		HashMap<String, String> naverUrl = this.makeRequestStatement(request, naverClientId);
		this.state = naverUrl.get("state");
		String returnUrl = request.getHeader("referer");
		
		return "redirect:" + naverUrl.get("url");
	}
	
	/**
	 * 네이버 로그인 요청에 대한 응답 처리
	 * 
	 * @param request
	 * @param response
	 * @param state
	 * @param code
	 * @param error
	 * @param error_description
	 * @return
	 */
	@RequestMapping(value = "/naverRequestKey.do")
	public String getNaverRequestKey(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("state") String state, 
			@RequestParam(value = "code", required = false) String code, 
			@RequestParam(value = "error", required = false) String error, 
			@RequestParam(value = "error_description", required = false) String error_description) 
	{
		HttpSession session = request.getSession();
		
		System.out.print("state = " + this.state + "="+  state + "/code = " + code + "/error = " + error + "/error_description = " + error_description);
		
		if (state.equals(this.state)) {
			session.setAttribute("isLoged", true);
		} else {
			session.setAttribute("isLoged", false);
			//System.out.println("state key값 불일치. 인증에러");
			return "redirect:/index.html";
		}
		
		// 네이버에 token_type, access_token 요청
		HashMap<String, String> result1 = this.getRequestKey(request, state, code, naverClientId, naverClientSecret);
		
		//
		String access_token = result1.get("access_token");
		String refresh_token = result1.get("refresh_token");
		String token_type = result1.get("token_type");
		
		System.out.println("access_token = " + access_token + "," + refresh_token + "," + token_type);

		// 사용자 정보 조회 요청
		HashMap<String, Object> result2 = this.requestUserInfo(token_type, access_token);
		System.out.println("result=" + result2);

		String email = (String)result2.get("email");
		
		if (email==null) {
			System.out.println("email = " + email);
			session.setAttribute("isLoged", false);
			return "redirect:/index.html";
		}
		
		String user_id = (String)result2.get("email");
		
		// 수동 로그인(spring security manual login) 처리
		try {
			// 
			UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken("abcd", "1111");
			
			// Authenticate the user
			Authentication authentication = authenticationManager.authenticate(authRequest);
			SecurityContext securityContext = SecurityContextHolder.getContext();
			securityContext.setAuthentication(authentication);
		} catch (Exception e) {
			e.printStackTrace();
			SecurityContextHolder.getContext().setAuthentication(null);
		}
		
		//return "redirect:" + returnUrl;
		return "redirect:/index.html";
	}
	
	/**
	 * 호스트이름 반환
	 * 
	 * @param request
	 * @return
	 */
	public static String getHostname(HttpServletRequest request) {
		String port_str = (request.getServerPort()==80 ? "" : ":" + request.getServerPort());
		return "http://" + request.getServerName() + port_str + request.getContextPath();
	}
	
	/**
	 * state 값 생성
	 * 
	 * @return
	 */
	public String generateState() {
		SecureRandom random = new SecureRandom();
		return new BigInteger(130, random).toString(32);
	}
	
	/**
	 * 네이버 로그인 요청 (Redirect URL 생성)
	 * 
	 * 1. redirect 생성 - 네이버 로그인 요청 완료 후 응답 받는 url 생성
	 * 2. state 생성 - Ramdom 함수로 생성
	 * 3. 요청 URL 생성 반환
	 * 
	 * @param request
	 * @param clientId
	 * @return
	 */
	private HashMap<String, String> makeRequestStatement(HttpServletRequest request, String clientId) {
		//String redirectUri = "http://127.0.0.1:8080/naverRequestKey.cmx";
		String redirectUri = getHostname(request) + "/naverRequestKey.do";
		String state = generateState();
		String url = "https://nid.naver.com/oauth2.0/authorize?" + "response_type=code&client_id=" + clientId + "&redirect_uri=" + redirectUri + "&state=" + state;
		
		HashMap<String, String> naverUrl = new HashMap<String, String>();
		naverUrl.put("state", state);
		naverUrl.put("url", url);
		return naverUrl;
	}
	
	/**
	 * 네이버에 token_type, access_token 요청(로그인 성공 이후)
	 * 
	 * @param request
	 * @param state
	 * @param code
	 * @param clientId
	 * @param naverClientSecret
	 * @return
	 */
	private HashMap<String, String> getRequestKey(HttpServletRequest request, String state, String code, String clientId, String naverClientSecret) {
		String naverUrl = "https://nid.naver.com/oauth2.0/token?client_id=" + clientId + "&client_secret=" + naverClientSecret + "&grant_type=authorization_code" + "&state=" + state + "&code=" + code;
		String naverJsonKey = "";// null로 하니까 null이 json에 포함이 됨.
		HashMap<String, String> result = new HashMap<String, String>();

		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(naverUrl).openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String input;
			while ((input = reader.readLine()) != null) {
				naverJsonKey += input;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			JSONParser parser = new JSONParser();
			JSONObject jsonObject = (JSONObject) parser.parse(naverJsonKey);
			
			result.put("access_token", (String) jsonObject.get("access_token"));
			result.put("refresh_token", (String) jsonObject.get("refresh_token"));
			result.put("token_type", (String) jsonObject.get("token_type"));
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 네이버에 로그인 사용자의 정보 요청
	 * 
	 * @param token_type
	 * @param access_token
	 * @return
	 */
	public HashMap<String, Object> requestUserInfo(String token_type, String access_token) {
		
		String url = "https://apis.naver.com/nidlogin/nid/getUserProfile.xml";
		String naverResult = "";
		try {
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Authorization", token_type + " " + access_token);
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String input;
			while ((input = reader.readLine()) != null) {
				naverResult += input;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		HashMap<String, Object> result = new HashMap<String, Object>();

		try {
			InputSource is = new InputSource(new StringReader(naverResult));
			Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
			XPath xpath = XPathFactory.newInstance().newXPath();
			Node email = (Node) xpath.evaluate("//data/response/email", xml, XPathConstants.NODE);
			Node nickname = (Node) xpath.evaluate("//data/response/nickname", xml, XPathConstants.NODE);
			Node profile_image = (Node) xpath.evaluate("//data/response/profile_image", xml, XPathConstants.NODE);
			Node age = (Node) xpath.evaluate("//data/response/age", xml, XPathConstants.NODE);
			Node gender = (Node) xpath.evaluate("//data/response/gender", xml, XPathConstants.NODE);
			Node id = (Node) xpath.evaluate("//data/response/id", xml, XPathConstants.NODE);
			Node birthday = (Node) xpath.evaluate("//data/response/birthday", xml, XPathConstants.NODE);
			if (email!=null) result.put("email", email.getTextContent());
			if (nickname!=null) result.put("nickname", nickname.getTextContent());
			if (profile_image!=null) result.put("profile_image", profile_image.getTextContent());
			if (age!=null) result.put("age", age.getTextContent());
			if (gender!=null) result.put("gender", gender.getTextContent());
			if (id!=null) result.put("id", id.getTextContent());
			if (birthday!=null) result.put("birthday", birthday.getTextContent());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}


저작자 표시
신고

NanoPi M1 Plus - DHT11 control with pi4j

OS/NanoPi 2017.04.02 09:57 Posted by 파란크리스마스

NanoPi M1 Plus - DHT11 control with pi4j

출처 : Java Native Interface (JNI) - Java Programming Tutorial
Use arrays (JNI) - Real's Java How-to - Rgagnon
android - How to return an array from JNI to Java? - Stack Overflow

NanoPi M1 Plus에서 pi4j로만으로 DHT11센서의 값을 읽을 수 없어 pi4j의 native 코드를 추가해서 온도 값을 가지고 오도록 수정하였습니다. 첨부한 jar을 적용해서 사용하세요.

pi4j-core.jar

핀배열

 DHT11  BCM  GPIO  Name  Pin
 VCC      3.3v  1
 GND  0v  9
 Sensor  3  22  CTS2  15

dht11.h

int* read_dht11_dat(int pin);

dht11.c

/*
 *  dht11.c:
 *      Simple test program to test the wiringPi functions
 *      DHT11 test
 */
  
#include <wiringPi.h>
  
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <dht11.h>

#define MAXTIMINGS      85
#define DHTPIN    3
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
  
int* read_dht11_dat(int pin) {
    uint8_t laststate       = HIGH;
    uint8_t counter  = 0;
    uint8_t j          = 0, i;
    float   f; /* fahrenheit */
  
    dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
  
    /* pull pin down for 18 milliseconds */
    pinMode( pin, OUTPUT );
    digitalWrite( pin, LOW );
    delay( 18 );
    /* then pull it up for 40 microseconds */
    digitalWrite( pin, HIGH );
    delayMicroseconds( 40 );
    /* prepare to read the pin */
    pinMode( pin, INPUT );
  
    /* detect change and read data */
    for ( i = 0; i < MAXTIMINGS; i++ ) {
        counter = 0;
        while ( digitalRead( pin ) == laststate ) {
            counter++;
            delayMicroseconds( 1 );
            if ( counter == 255 ) {
                break;
            }
        }
        laststate = digitalRead( pin );
  
        if ( counter == 255 )
            break;

// printf("i = %d, j = %d\n", i, j);
  
        /* ignore first 3 transitions */
        if ( (i >= 4) && (i % 2 == 0) ) {
            /* shove each bit into the storage bytes */
            dht11_dat[j / 8] <<= 1;
            if ( counter > 16 )
                dht11_dat[j / 8] |= 1;
            j++;
        }
    }
  
    /*
     * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
     * print it out if data is good
     */
    if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) {
        f = dht11_dat[2] * 9. / 5. + 32;
        //printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
        //    dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
    } else {
        //printf( "Data not good, skip\n" );
    }
    
    return dht11_dat;    
}

com_pi4j_wiringpi_Gpio.h 내용 추가

/*
 * Class:     com_pi4j_wiringpi_Gpio
 * Method:    readDHT11Data
 * Signature: (II)V
 */
JNIEXPORT jintArray JNICALL Java_com_pi4j_wiringpi_Gpio_readDHT11Data
  (JNIEnv *, jclass, jint);

com_pi4j_wiringpi_Gpio.c 내용 추가

#include <dht11.h>

/*
 * Class:     com_pi4j_wiringpi_Gpio
 * Method:    readDHT11Data
 * Signature: (II)V
 */
JNIEXPORT jintArray JNICALL Java_com_pi4j_wiringpi_Gpio_readDHT11Data
  (JNIEnv *env, jclass obj, jint pin)
{
    // return (jintArray) read_dht11_dat(pin);
    int size = 5;
    jintArray result;
    result = (*env)->NewIntArray(env, size);
    if (result == NULL) {
    	return NULL; /* out of memory error thrown */
    }
    
    int *a1 = read_dht11_dat(pin);
    
    int i;
    // fill a temp structure to use to populate the java int array
    jint fill[size];
    for (i = 0; i < size; i++) {
    	 fill[i] = a1[i]; // put whatever logic you want to populate the values here.
    }
    // move from the temp structure to the java structure
    (*env)->SetIntArrayRegion(env, result, 0, size, fill);
    return result;
}

Gpio 클래스 함수 추가

package com.pi4j.wiringpi;

public class Gpio {
    
    public static native int[] readDHT11Data(int pin);
}

DHT11_native.java

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.NanoPiM1PlusGpioProvider;
import com.pi4j.wiringpi.Gpio;
 
public class DHT11_native {
    private static final int MAXTIMINGS = 85;
    private int[] dht11_dat = { 0, 0, 0, 0, 0 };
    
    private final static int DHTPIN = 3; // 3;
 
    public float getTemperature() {
    	float f = 0;
    	dht11_dat = Gpio.readDHT11Data(DHTPIN);
    	
       if ( (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) {
      	 f = (float) (dht11_dat[2] * 9. / 5. + 32);
         System.out.println(String.format( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)" , dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f) );
     } else {
    	 System.out.println( "Data not good, skip" );
     }
       
        return f;
 
    }
 
    private boolean checkParity() {
      return (dht11_dat[4] == ((dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF));
    }
 
    public static void main (String ars[]) throws Exception {
    	
    	GpioFactory.setDefaultProvider(new NanoPiM1PlusGpioProvider());
 
    	DHT11_native dht = new DHT11_native();
 
        for (int i=0; i<10; i++) {
           Thread.sleep(1000);
           dht.getTemperature();
        }
 
        System.out.println("Done!!");
 
    }
}

실행

# java -cp .:pi4j-core.jar DHT11_native
Data not good, skip
Humidity = 31.0 % Temperature = 23.0 *C (73.4 *F)
Humidity = 30.0 % Temperature = 23.0 *C (73.4 *F)
Humidity = 30.0 % Temperature = 23.0 *C (73.4 *F)

실행결과

저작자 표시
신고

Chart.js - Spring 연동

Programming/Java 2017.03.29 20:05 Posted by 파란크리스마스

Chart.js - Spring 연동

출처 : Chart.js - Spring 연동

JSONChartJS 클래스

package com.intel4.json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.intel4.service.QuestionListService;
import com.intel4.util.BeanUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONChartJS extends JSONData {

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {

		String subcmd = request.getParameter("subcmd");
		JSONObject jobj_data = null;
		if (subcmd.equals("line")) {
			jobj_data = getAddData(request, response);
		}
		return jobj_data;
	}

	private JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {
		
		JSONArray datas = new JSONArray();
		
		JSONObject data1 = new JSONObject();
		data1.put("month", "1월");
		data1.put("pc", 100);
		data1.put("monitor", 80);
		datas.add(data1);
		JSONObject data2 = new JSONObject();
		data2.put("month", "2월");
		data2.put("pc", 80);
		data2.put("monitor", 70);
		datas.add(data2);
		JSONObject data3 = new JSONObject();
		data3.put("month", "3월");
		data3.put("pc", 70);
		data3.put("monitor", 60);
		datas.add(data3);
		JSONObject data4 = new JSONObject();
		data4.put("month", "4월");
		data4.put("pc", 90);
		data4.put("monitor", 100);
		datas.add(data4);
		JSONObject data5 = new JSONObject();
		data5.put("month", "5월");
		data5.put("pc", 40);
		data5.put("monitor", 110);
		datas.add(data5);
		
		JSONObject result = new JSONObject();
		result.put("datas", datas);
		
		return result;
	}
}

Line Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
<title>Line Chart</title>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas {
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}
</style>
</head>
<body>

<div style="width: 80%">
	<div>
		<canvas id="canvas" height="350" width="600"></canvas>
	</div>
</div>

<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];

var lineChartData = {
	labels : chartLabels,
	datasets : [ {
		label : "월별 PC 판매량",
		fillColor : "rgba(220,220,220,0.2)",
		strokeColor : "rgba(220,220,220,1)",
		pointColor : "rgba(220,220,220,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(220,220,220,1)",
		data : chartData1
	}, {
		label : "월별 모니터 판매량",
		fillColor : "rgba(151,187,205,0.2)",
		strokeColor : "rgba(151,187,205,1)",
		pointColor : "rgba(151,187,205,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(151,187,205,1)",
		data : chartData2
	} ]

}

function createChart() {
	var ctx = document.getElementById("canvas").getContext("2d");
	LineChartDemo = Chart.Line(ctx, {
		data : lineChartData,
		options : {
			scales : {
				yAxes : [ {
					ticks : {
						beginAtZero : true
					}
				} ]
			}
		}
	});
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {

			$.each(result.datas, function(inx, obj) {
				chartLabels.push(obj.month);
				chartData1.push(obj.pc);
				chartData2.push(obj.monitor);

			});

			createChart();

		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}
</script>
</body>
</html>

실행결과

Bar Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
</style>


<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var lineChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        },
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
    ]
 
}

function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'horizontalBar',
    	data: lineChartData,
    	options: {
            scales: {
            	xAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

Pie Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
    <title>Pie Chart</title>
    <script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
    <script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
    <style>
    canvas{
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var PieChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        
        /*,
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#aff",
            pointHighlightFill : "#aff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        */
    ]
 
}
 
function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'pie',
    	data: PieChartData,
    	
        options: {
            responsive: true
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

저작자 표시
신고

NanoPi M1 Plus - DHT11 온도 습도 측정

OS/NanoPi 2017.03.28 00:20 Posted by 파란크리스마스

NanoPi M1 Plus - DHT11 온도 습도 측정

출처 : DHT11 Humidity & Temperature Sensor Module | UUGear

C 언어

/*
 *  dht11.c:
 *      Simple test program to test the wiringPi functions
 *      DHT11 test
 */
 
#include <wiringPi.h>
 
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXTIMINGS      85
#define DHTPIN	  7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
 
void read_dht11_dat() {
	uint8_t laststate       = HIGH;
	uint8_t counter	 = 0;
	uint8_t j	       = 0, i;
	float   f; /* fahrenheit */
 
	dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
 
	/* pull pin down for 18 milliseconds */
	pinMode( DHTPIN, OUTPUT );
	digitalWrite( DHTPIN, LOW );
	delay( 18 );
	/* then pull it up for 40 microseconds */
	digitalWrite( DHTPIN, HIGH );
	delayMicroseconds( 40 );
	/* prepare to read the pin */
	pinMode( DHTPIN, INPUT );
 
	/* detect change and read data */
	for ( i = 0; i < MAXTIMINGS; i++ ) {
		counter = 0;
		while ( digitalRead( DHTPIN ) == laststate ) {
			counter++;
			delayMicroseconds( 1 );
			if ( counter == 255 ) {
				break;
			}
		}
		laststate = digitalRead( DHTPIN );
 
		if ( counter == 255 )
			break;
 
		/* ignore first 3 transitions */
		if ( (i >= 4) && (i % 2 == 0) ) {
			/* shove each bit into the storage bytes */
			dht11_dat[j / 8] <<= 1;
			if ( counter > 16 )
				dht11_dat[j / 8] |= 1;
			j++;
		}
	}
 
	/*
	 * check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
	 * print it out if data is good
	 */
	if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) {
		f = dht11_dat[2] * 9. / 5. + 32;
		printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
			dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
	} else {
		printf( "Data not good, skip\n" );
	}
}
 
int main( void ) {
	printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );
 
	if ( wiringPiSetup() == -1 )
		exit( 1 );
 
	while ( 1 ) {
		read_dht11_dat();
		delay( 1000 ); /* wait 1sec to refresh */
	}
 
	return(0);
}

컴파일

# gcc -Wall -o dht11 dht11.c -lwiringPi -lpthread

실행

디버깅 모드 설정

# export WIRINGPI_DEBUG=TRUE

디버깅 모드 해지

# unset WIRINGPI_DEBUG

실행

# ./dht11     
Raspberry Pi wiringPi DHT11 Temperature test program
Data not good, skip
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
Data not good, skip
Data not good, skip
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
저작자 표시
신고

Spring MVC - Form 데이터 전달

Programming/Java 2017.03.26 19:51 Posted by 파란크리스마스

기본 Form 데이터 전달

기본 Form 데이터 전달 JSP - /sample/form1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form1.do"/>" method="get">
	<input type="text" name="user_id">
	<input type="password" name="password">
	<input type="submit">
</form>

</body>
</html>

기본 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form1.do", method = RequestMethod.GET)
	public String form1(
			@RequestParam("user_id") String user_id, 
			@RequestParam("password") String password,
			ModelMap modelMap) throws Exception 
	{
		System.out.println("user_id = " + user_id + "/" + password);
		return "redirect:/sample/form1.jsp";
	}

파일 업로드 Form 데이터 전달

파일 업로드 Form 데이터 전달 JSP - /sample/form2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form2.do"/>" method="post" enctype="multipart/form-data">
	<input type="text" name="title"><br/>
	<input type="file" name="file1"><br/>
	<input type="file" name="file2"><br/>
	<input type="submit">
</form>

</body>
</html>

파일 업로드 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form2.do", method = RequestMethod.POST)
	public String form2(
			@RequestParam("title") String title, 
			@RequestParam("file1") MultipartFile file1, 
			@RequestParam("file2") MultipartFile file2, 
			ModelMap modelMap) 
	{
		System.out.println("title = " + title);
		
		String uuid_filename1 = fileWrite(file1);
		String uuid_filename2 = fileWrite(file2);
		
		System.out.println(uuid_filename1 + "/" + uuid_filename2);
		
		return "redirect:/sample/form2.jsp";
	}
	
	// 파일 저장 메소드
	private String fileWrite(MultipartFile uploadfile) {
		OutputStream out = null;
		String targetFilename = null;
		try {
			String filePath = "C:/test"; // 설정파일로 뺀다.
			
			// 파일명 얻기
			String fileName = uploadfile.getOriginalFilename();
			
			// 파일의 바이트 정보 얻기
			byte[] bytes = uploadfile.getBytes();
	
			String originalFilename = uploadfile.getOriginalFilename(); // 파일명
			
			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);
	
			UUID uuid = UUID.randomUUID();
			targetFilename = uuid.toString() + "." + fileExt.toLowerCase();
	
			String fileFullPath = filePath + "/" + targetFilename; // 파일 전체 경로
			
			// 파일 객체 생성
			File file = new File(fileFullPath);
			// 상위 폴더 존재 여부 확인
			if (!file.getParentFile().exists()) {
				// 상위 폴더가 존재 하지 않는 경우 상위 폴더 생성
				file.getParentFile().mkdirs();
			}
			
			// 파일 아웃풋 스트림 생성
			out = new FileOutputStream(file);
			// 파일 아웃풋 스트림에 파일의 바이트 쓰기
			out.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); }
		}
		return targetFilename;
	}
}
저작자 표시
신고

Orange PI Zero - pi4j로 PWM 제어

OS/Orange PI 2017.03.25 12:10 Posted by 파란크리스마스

Orange PI Zero - pi4j로 PWM 제어

Orange PI Zero는 하나의 PWM만 지원

배선

Java 소스

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.OrangePiZeroGpioProvider;
import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.SoftPwm;

public class SG90PWMMain {

	private static int PIN_NUMBER = 7;

	public static void main(String[] args) throws Exception {
		//
		//GpioFactory.setDefaultProvider(new RaspiGpioProvider(RaspiPinNumberingScheme.BROADCOM_PIN_NUMBERING));
		//GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
		//GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());
		GpioFactory.setDefaultProvider(new OrangePiZeroGpioProvider());

		// initialize wiringPi library, this is needed for PWM
		Gpio.wiringPiSetup();

		// softPwmCreate(int pin, int value, int range)
		// the range is set like (min=0 ; max=100)
		SoftPwm.softPwmCreate(PIN_NUMBER, 0, 50);
		int counter = 0;
		while (counter < 3) {
			// fade LED to fully ON
			for (int i = 0; i <= 100; i++) {
				// softPwmWrite(int pin, int value)
				// This updates the PWM value on the given pin. The value is
				// checked to be in-range and pins
				// that haven't previously been initialized via softPwmCreate
				// will be silently ignored.
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			// fade LED to fully OFF
			for (int i = 100; i >= 0; i--) {
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			counter++;
		}
	}

}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar SG90PWMMain

실행 영상

저작자 표시
신고

Orange PI Zero GPIO 설치, pi4j

OS/Orange PI 2017.03.25 03:01 Posted by 파란크리스마스

Orange PI Zero GPIO 설치

출처 : WiringOP for Orange pi zero - Beginners - OrangePi - Powered by

현재 pi4j는 Orange PI PC2 지원하지 않아 수정한 jar를 배포합니다.

pi4j-core.jar

$ sudo apt-get install build-essential
$ git clone https://github.com/zhaolei/WiringOP.git -b h3
$ cd WiringOP
$ chmod +x ./build
$ sudo ./build
$ gpio -v
gpio version: 2.20
Copyright (c) 2012-2014 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty
 
Banana Pro Details:
  Type: Banana Pro, Revision: 1.2, Memory: 1024MB, Maker: LeMaker 
orangepi@OrangePizero:~/WiringOP$ gpio readall
 +-----+-----+----------+------+---+-Orange Pi+---+---+------+---------+-----+--+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 |     |     |     3.3v |      |   |  1 || 2  |   |      | 5v       |     |     |
 |  12 |   8 |    SDA.0 | ALT5 | 0 |  3 || 4  |   |      | 5V       |     |     |
 |  11 |   9 |    SCL.0 | ALT5 | 0 |  5 || 6  |   |      | 0v       |     |     |
 |   6 |   7 |   GPIO.7 | ALT3 | 0 |  7 || 8  | 0 | ALT3 | TxD3     | 15  | 13  |
 |     |     |       0v |      |   |  9 || 10 | 0 | ALT3 | RxD3     | 16  | 14  |
 |   1 |   0 |     RxD2 | ALT5 | 0 | 11 || 12 | 0 | ALT3 | GPIO.1   | 1   | 110 |
 |   0 |   2 |     TxD2 | ALT5 | 0 | 13 || 14 |   |      | 0v       |     |     |
 |   3 |   3 |     CTS2 | ALT3 | 0 | 15 || 16 | 0 | ALT3 | GPIO.4   | 4   | 68  |
 |     |     |     3.3v |      |   | 17 || 18 | 0 | ALT3 | GPIO.5   | 5   | 71  |
 |  64 |  12 |     MOSI | ALT4 | 0 | 19 || 20 |   |      | 0v       |     |     |
 |  65 |  13 |     MISO | ALT4 | 0 | 21 || 22 | 0 | ALT3 | RTS2     | 6   | 2   |
 |  66 |  14 |     SCLK | ALT4 | 0 | 23 || 24 | 0 | ALT4 | CE0      | 10  | 67  |
 |     |     |       0v |      |   | 25 || 26 | 0 | ALT3 | GPIO.11  | 11  | 21  |
 |  19 |  30 |    SDA.1 | ALT4 | 0 | 27 || 28 | 0 | ALT4 | SCL.1    | 31  | 18  |
 |   7 |  21 |  GPIO.21 | ALT3 | 0 | 29 || 30 |   |      | 0v       |     |     |
 |   8 |  22 |  GPIO.22 | ALT3 | 0 | 31 || 32 | 0 | ALT3 | RTS1     | 26  | 200 |
 |   9 |  23 |  GPIO.23 | ALT3 | 0 | 33 || 34 |   |      | 0v       |     |     |
 |  10 |  24 |  GPIO.24 |  OUT | 0 | 35 || 36 | 0 | ALT3 | CTS1     | 27  | 201 |
 |  20 |  25 |  GPIO.25 |  OUT | 1 | 37 || 38 | 0 | ALT5 | TxD1     | 28  | 198 |
 |     |     |       0v |      |   | 39 || 40 | 0 | ALT5 | RxD1     | 29  | 199 |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+-Orange Pi+---+------+----------+-----+-----+

C언어 샘플 소스

#include <wiringPi.h>
  
int main()
{
  wiringPiSetup();
  pinMode(7, OUTPUT);
  while(1) {
    digitalWrite(7,HIGH);
    delay(500);
    digitalWrite(7,LOW);
    delay(500);
  }
  return 0;
}

컴파일

$ gcc -Wall -o blink blink.c -lwiringPi -lpthread

실행

$ sudo ./blink

java 샘플 소스

/*
 * #%L
 * **********************************************************************
 * ORGANIZATION  :  Pi4J
 * PROJECT       :  Pi4J :: Java Examples
 * FILENAME      :  ControlGpioExample.java
 *
 * This file is part of the Pi4J project. More information about
 * this project can be found here:  http://www.pi4j.com/
 * **********************************************************************
 * %%
 * Copyright (C) 2012 - 2016 Pi4J
 * %%
 * This program 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 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 General Lesser Public License for more details.
 *
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * #L%
 */
 
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.OrangePiZeroGpioProvider;
import com.pi4j.io.gpio.OrangePiZeroPin;
import com.pi4j.io.gpio.PinState;
 
/**
 * This example code demonstrates how to perform simple state
 * control of a GPIO pin on the Raspberry Pi.
 *
 * @author Robert Savage
 */
public class ControlGpioExample {
 
    public static void main(String[] args) throws InterruptedException {

        //GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
        //GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());
    	GpioFactory.setDefaultProvider(new OrangePiZeroGpioProvider());

        System.out.println("<--Pi4J--> GPIO Control Example ... started.");
 
        // create gpio controller
        final GpioController gpio = GpioFactory.getInstance();
 
        // provision gpio pin #01 as an output pin and turn on
        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(OrangePiZeroPin.GPIO_07, "MyLED", PinState.HIGH);
 
        // set shutdown state for this pin
        pin.setShutdownOptions(true, PinState.LOW);
 
        System.out.println("--> GPIO state should be: ON");
 
        Thread.sleep(5000);
 
        // turn off gpio pin #01
        pin.low();
        System.out.println("--> GPIO state should be: OFF");
 
        Thread.sleep(5000);
 
        // toggle the current state of gpio pin #01 (should turn on)
        pin.toggle();
        System.out.println("--> GPIO state should be: ON");
 
        Thread.sleep(5000);
 
        // toggle the current state of gpio pin #01  (should turn off)
        pin.toggle();
        System.out.println("--> GPIO state should be: OFF");
 
        Thread.sleep(5000);
 
        // turn on gpio pin #01 for 1 second and then off
        System.out.println("--> GPIO state should be: ON for only 1 second");
        pin.pulse(1000, true); // set second argument to 'true' use a blocking call
 
        // stop all GPIO activity/threads by shutting down the GPIO controller
        // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        gpio.shutdown();
 
        System.out.println("Exiting ControlGpioExample");
    }
}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar ControlGpioExample

실행결과

저작자 표시
신고

Orange PI Zero

OS/Orange PI 2017.03.25 02:01 Posted by 파란크리스마스

Orange PI Zero

출처 : 스터디메이크 :: 오렌지파이 제로 보드 간단 사용기
Xunlong Orange Pi Zero

vi 설치

$ sudo apt-get install vim

vnc 설치

출처 : Armbian: Access the Remote Desktop of Orange Pi with VNC

vnc 설치

$ sudo apt-get update && apt-get upgrade
$ sudo apt-get install tightvncserver

vnc 사용자 추가

$ su - 
# adduser vnc
Adding user `vnc' ...
Adding new group `vnc' (1001) ...
Adding new user `vnc' (1001) with group `vnc' ...
Creating home directory `/home/vnc' ...
Copying files from `/etc/skel' ...
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully
Changing the user information for vnc
Enter the new value, or press ENTER for the default
        Full Name []: VNCuser
        Room Number []: 
        Work Phone []: 
        Home Phone []: 
        Other []: 
Is the information correct? [Y/n] 

vnc 사용자 추가

# gpasswd -a vnc sudo
Adding user vnc to group sudo

vnc 서버 실행

# su - vnc
$ vncserver :1
 
You will require a password to access your desktops.
 
Password: 
Verify:   
Would you like to enter a view-only password (y/n)? 
*** buffer overflow detected ***: vncpasswd terminated
xauth:  file /home/vnc/.Xauthority does not exist
 
New 'X' desktop is OrangePizero:1
 
Creating default startup script /home/vnc/.vnc/xstartup
Starting applications specified in /home/vnc/.vnc/xstartup
Log file is /home/vnc/.vnc/OrangePizero:1.log

Wifi 설정

출처 : 014. Raspberry Pi 라즈베리 파이 - wheezy무선랜 ... - Tsunami - Tistory

$ cd /etc/ifplugd/action.d/
$ sudo mv ifupdown ifupdown.bk
$ sudo cp /etc/wpa_supplicant/ifupdown.sh ./ifupdown

암비안 와이파이 설정

출처 : 오렌지파이 제로 무선인터넷 설정 1.2 암비안 와이파이 설정

$ sudo nmtui

SD 확장

SD 확장전 용량확인

$ sudo fdisk /dev/mmcblk0
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       1.6G  1.2G  349M  78% /
devtmpfs        168M     0  168M   0% /dev
tmpfs           224M     0  224M   0% /dev/shm
tmpfs           224M  8.5M  216M   4% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           224M     0  224M   0% /sys/fs/cgroup
tmpfs           224M  4.0K  224M   1% /tmp
/dev/mmcblk0p1   63M  4.6M   59M   8% /media/boot
tmpfs            45M     0   45M   0% /run/user/107
tmpfs            45M     0   45M   0% /run/user/1000

SD FDisk

orangepi@OrangePizero:~$ sudo fdisk /dev/mmcblk0

Welcome to fdisk (util-linux 2.25.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/mmcblk0: 7.4 GiB, 7948206080 bytes, 15523840 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x000b04ea

Device         Boot  Start     End Sectors  Size Id Type
/dev/mmcblk0p1       40960  172031  131072   64M  b W95 FAT32
/dev/mmcblk0p2      172032 3514367 3342336  1.6G 83 Linux


Command (m for help): d
Partition number (1,2, default 2): 2

Partition 2 has been deleted.

Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (2-4, default 2): 2
First sector (2048-15523839, default 2048): 172032
Last sector, +sectors or +size{K,M,G,T,P} (172032-15523839, default 15523839): 

Created a new partition 2 of type 'Linux' and of size 7.3 GiB.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Re-reading the partition table failed.: Device or resource busy

The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8).

orangepi@OrangePizero:~$ sudo shutdown -r now

SD 확장

$ sudo resize2fs /dev/mmcblk0p2
resize2fs 1.42.12 (29-Aug-2014)
Filesystem at /dev/mmcblk0p2 is mounted on /; on-line resizing required
old_desc_blocks = 1, new_desc_blocks = 1
The filesystem on /dev/mmcblk0p2 is now 1918976 (4k) blocks long.

SD 확장 확인

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       7.3G  1.2G  5.8G  17% /
devtmpfs        168M     0  168M   0% /dev
tmpfs           224M     0  224M   0% /dev/shm
tmpfs           224M  8.5M  216M   4% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           224M     0  224M   0% /sys/fs/cgroup
tmpfs           224M  4.0K  224M   1% /tmp
/dev/mmcblk0p1   63M  4.6M   59M   8% /media/boot
tmpfs            45M     0   45M   0% /run/user/107
tmpfs            45M     0   45M   0% /run/user/1000

JDK 설치

$ sudo apt install -t jessie-backports openjdk-8-jre openjdk-8-jre-headless openjdk-8-jdk openjdk-8-jdk-headless ca-certificates-java

JAVA_HOME 환경변수 추가

$ sudo vi /etc/profile

내용 추가 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf
저작자 표시
신고


 

티스토리 툴바