728x90

0. 데이터타입 기초

0-1) 비트 ( bit = binary degit )

- 이진수의 하나의 자릿수를 나타내며 0과 1을 의미

- 컴퓨터에서 0은 전류가 흐르지 않는 상태, 1은 그 반대이다.

  또는 0은 거짓, 1은 참을 의미하기도 한다.

 

0-2) 진법 (Base N)

- 수를 셀 때, 자릿수가 올라가는 단위를 기준으로 하는 셈법의 총칭

- 일상에서 가장 보편적으로 사용하는 것은 10진법으로 (0~9의 범위를 가진다)

- 컴퓨터에서 사용하는 진법은 2진법으로 0과 1

- 8진법은 0~7, 16진법은 0~15까지의 수를 사용하는 진법이다.

단, 16진법은 9이후를 10으로 표기하지 않고 A로 표기한다. (A~F)

 

0-3) 진법 변환

- 10진법 -> 2진법 (소인수분해)

몫과 나머지를 쓰고 나머지를 마지막나머지 + 밑에서부터 차례대로 붙여가면 된다.

바꾼 값의 결과는 아래와 같으며 해당 수의 진법 표기는 괄호안에 적는다. (10)은 10진법 표기

 

13 (10) -> 01101 (2)

 

- 8진법 -> 10진법 (자릿수 변환)

 

0307 (8)

(3 x 82) + (0x81) + (7 x 80) = 199 (10)    // 0승은 항상 1

 

0-4) 리터럴

소스코드에서 프로그래머에 의해 직접 입력된 값, 자바에서 실제 처리하는 데이터

 

 

1. 기본 데이터 타입

- 자바에서의 기본테이터 타입 (반대는 참조데이터 타입) 은 아래 8가지이다.

- 타입이름은 모두 소문자임에 유의

- 1Byte 는 8 bit이다.

   즉 0000 0000(2) ~ 1111 1111(2) 의 값을 표현을 가진다.

 

        1Byte    2Byte    4Byte    8Byte
        (8bit)   (16bit)    (32bit)   (64bit)
-----------------------------------------
정수형   byte     short    int      long
실수형                      float    double
문자형              char  --- 실제로 char(캐릭터) 타입은 정수형에 포함되나 이는 뒤에서 설명
논리형  boolean

 

char는 ushort, int, uint, long, uyong, float, double 또는 10진수로 암시적으로 변환될 수 있다. 그러나 다른 유형에서 char 유형으로의 암묵적 변환은 없다.

 

1) 정수형(Interger Type)

저장되는 값의 허용범위 (char타입은 음수값을 포함하지 않으므로 제외)

n = 메모리bit수 - 1   (ex : 8bit크기는 8 - 1 = 7)
  -2^n ~ (2n-1)

byte : -128 ~ 127    | 0포함,  -2^7 ~ (2^7-1)

short : -32768 ~ 32,767

char : 0 ~ 65536 (유니코드) | 0 ~ (2^16-1)

int : 약 -21억 ~ 21억 | -2^31 ~ (2^31-1)

long : 약 -922경 ~ 922경

 

1-2) 정수 리터럴 표현

- 2진수 : 0b1011  (맨앞은 숫자 0)

- 8진수 : 013       (맨앞은 숫자 0)

- 10진수 : 365     (소수점없는 10진법 숫자)

- 16진수 : 0x3B0F (맨앞은 숫자 0)

- long타입 (기본적으로 자바 컴파일러는 정수 리터럴을 int타입으로 간주한다!)

long l = 12_345_678_999;	// int타입으로 간주해서 타입이 맞지 않다는 에러 출력
long l = 12345678999L;   // int타입 범위를 벗어나면 L을 붙여서 롱타입임을 알려줌, 에러 없음

* 숫자밑에 _은 자릿수 구분을 위한 임의 표기로 에러사항이 아님

 

1-3) char타입

작은 따옴표로 감싼 형식을 쓰며 이것을 문자 리터럴이라고 한다.

문자 리터럴엔 유니코드값인 2byte크기 (0~65535)에 세계각국의 문자코드가 변환되어 저장된다.

 

유니코드 값은 크게 a, A, 0 값만 알고 있어도 유용하다.

char타입엔 아래와 같이 정수값을 저장해 쓸 수 있다.

char ch1 = 'A';	// unicode : 65
char ch2 = 65;	// A와 같음
char ch3 = '0'; // unicode : 48
char ch4 = 48;  // 문자 0과 같음
char ch5 = 'a'; // unicode : 97
char ch6 = '97';// a와 같음

아래와 같이 16진수 표현 또는 유니코드 표현을 쓸 수도 있다.

char c1 = 0x0041;	// 10진수값으로 65이며 unicode문자 A
char c2 = '\u0042'; // 문자 B

또한 int타입 변수에도 저장할 수 있지만 이 때는 콘솔로 출력해보면 유니코드 값이 출력된다.

char ch1 = 'A';		// A출력
int i = 'A';		// 65출력

2) 실수 타입

자바에서는 실수 연산은 기본적으로 double 타입으로 처리한다. (정수는 int)

따라서 float타입의 변수 선언 시 반드시 f를 붙여 float형으로 간주하도록 한다.

float f = 3.14f;  // 대문자 F로도 표기 가능, f생략 시 컴파일 에러

 

실수 타입은 항상 정수보다 표현범위가 크다. 

부동 소수점 방식으로 저장되어 더 큰 범위의 값을 저장할 수 있다. 

float : (+/-) 1.4 x10−45 ~ (+/-) 3.4028235 x 1038

double : (+/-) 4.9 x10−324 ~ (+/-) 1.7976931348623157 x 10308

 

0.1 == 0.1f
실수저장방식인 부동소수점 방식이 0.1을 정확히 표현불가 
0.1f는 0.1의 근사값 (.1.......) 따라서 0.1보다 큰값이 됨

 

2. 참조타입

Date today = new Date();

데이터 클래스 타입의 참조형 변수 today선언

참조타입은 4byte를 가진다.

 

문자열을 저장가능한 String 타입또한 클래스 타입의 참조타입이다.

String str = "이것이 문자열입니다.";

 

'Study > Java' 카테고리의 다른 글

JAVA - getter, setter  (0) 2021.02.09
JAVA - 파일 내 특정 문자열이 포함된 행을 제거  (0) 2021.02.04
자바 - 식별자  (0) 2021.01.06
자바 NIO 셀렉터  (0) 2017.07.05
Java Network 프로그래밍 기초  (0) 2017.06.03
728x90

0. 샘플 소스

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
function fun1() {
	alert("안녕 자바스크립트");
	return;
}
function fun2(money) {
	alert("받은 동전 : " + money)
	return;
}
function fun3(money) {
	alert("무료음료수 전달")	
	return "커피";
}

function fun4(a, b) {
	alert("받은 동전" + a + b);
	alert("음료수 선택");
	return "사이다";
}
	
</script>
<body>
<h1>WebContent/js1/test3.html</h1>
<input type="button" value="출력버튼" onclick="fun1()">
<input type="button" value="값을 받아서 뽑기출력버튼" onclick="fun2(500)">
<input type="button" value="무료음료수받기" onclick="alert('전달받은 음료수: ' + fun3() )">
<input type="button" value="음료수받기" onclick="alert('받은 음료수: ' + fun4(500, 100) )">
</body>
</html>

위의 funtion 인 fun4에서 "받은 동전" + a + b와 같이 쓰면 문자열로 서로 연결된다.

 

이를 피하고 a와 b변수의 값을 더하고자 한다면 아래와 같이 수정한다.

function fun4(a, b) {
	alert("받은 동전" + (a + b) );
	alert("음료수 선택");
	return "사이다";
}​

 

1. 가변인자를 통한 함수 정의

(...)
<script type="text/javascript">
// 입력받은 값 평균 구하기
function fun4(...args) {
    let res = 0;    
    for (let i = 0; i < args.length; i++) {
        res += args[i];
    }    
    avg = res / args.length;
    return avg;
}
</script>
(...)
<input type="button" value="두수합리턴받아서 평균 구하기"
 		onclick="alert('리턴받은값 : ' + fun4(10, 20) )">

 

2. 내장함수

: 자바스크립트에서 기본적으로 제공하는 함수

ex) alert, confirm 등

 

1) alert

- alert는 리턴값이 없고 사용자에게 팝업창으로 알려주는 역할

var a = alert("메시지");
	alert(a);

- 리턴값이 없으므로 undefined 메시지가 뜸

 

2) confirm

- 사용자가 확인 / 취소를 선택할 수 있는 팝업을 제공

 

var r = confirm('확인/취소 선택하세요');
alert(r);

- 확인 시 true, 취소 시 false를 리턴

 

3) prompt

- 사용자에게서 입력받은 값을 반환, 입력값은 문자로 인식

var v = prompt("입력하세요", "입력란");
	alert(v);
alert(v + 100);	// 문자열로 더해져서 출력됨
alert(v * 100); // 곱하기는 숫자로 인식

 

4) parseInt

- 숫자 정수로 변환하는 함수

alert(parseInt(v) + 100);	

5) isNaN

- 숫자 / 문자열인지 판별하는 함수로 문자이면 true, 숫자면 false반환

(문자열과 숫자가 함께 포함되면 문자로 인식)

var isString = isNaN(v);
if (isString) {
	alert ('문자를 입력하셨습니다');
}
else {
	alert ('숫자를 입력하셨습니다');
}	

 

'Study > JavaScript' 카테고리의 다른 글

[JavaScript] Proxy  (0) 2024.04.03
[JavaScript] 기본  (0) 2021.10.18
자바스크립트 - 의사 결정  (0) 2017.03.28
자바 스크립트 기초 - 함수, 메서드, 객체  (0) 2017.03.27
728x90

식별자 (Identifiers)

- 자바에서 각 대상을 구분하는 이름

- 변수, 상수, 클래스, 인터페이스, 패키지 등과 같은 개체(entity)의 이름

 

식별자 작성 규칙
[ 필수 사항 ]
1. 첫글자에 숫자 사용 불가(ex. 7eleven 사용 불가)
2. 특수문자 $ 또는 _ 만 사용 가능(ex. channel#5 사용 불가)
3. 대소문자 구별(ex. name 과 Name 은 다름)
4. 예약어(키워드) 사용 불가
5. 공백 사용 불가

6. 한글 사용도 가능 (권장사항 아니며 실제 사용하지 않음)
--------------------------------------------
[ 권장 사항 ]
6. 길이 제한 없음
7. 의미가 있는 단어 사용
8. 한글 사용 가능(하지만 실제 사용하지 않음 => 문제 발생 가능성 있음)
9. 두 개 이상의 단어를 조합할 경우 두번째 단어부터 첫글자를 대문자 사용
   ex) myfirstname => myFirstName(Camel-case 표기법)

'Study > Java' 카테고리의 다른 글

JAVA - 파일 내 특정 문자열이 포함된 행을 제거  (0) 2021.02.04
JAVA에서의 데이터 타입  (0) 2021.01.11
자바 NIO 셀렉터  (0) 2017.07.05
Java Network 프로그래밍 기초  (0) 2017.06.03
NIO 기반 네트워킹  (0) 2017.05.30
728x90

Visual Studio 패키지 관리자 콘솔

Install-Package Spire.Doc -Version 8.10.4

 

using추가

using Spire.Doc;

메소드 정의

 public static string[] GetDocxPlainText(string _filePath)
        {
            //Create word document
            Document document = new Document();

            //load a document
            document.LoadFromFile(_filePath);

            string plainText = document.GetText();
            string[] splitLine = plainText.Split(new[] { "\r\n" }, StringSplitOptions.None);

            return splitLine;
        }

 

'Study > C#' 카테고리의 다른 글

c#트랙바를 통한 볼륨 조절  (0) 2017.05.18
IP 주소 정수로 변환  (0) 2017.05.16
C# Thread  (0) 2017.04.24
C# MS-SQL 연동  (0) 2017.04.14
C# 네트워크 기본  (1) 2017.04.12
728x90

라즈비안 업데이트 및 업그레이드

1
sudo apt-get update & upgrade
cs

nginx 설치

1
sudo apt-get install nginx
cs

서비스 시작
1
sudo /etc/init.d/nginx start 
cs


php5 설치

1
sudo apt-get install php5-fpm
cs

인증을 위한 php5-mcrypt 설치
 
1
sudo apt-get install php5-mcrypt
cs


nginx에서 php 활성화

1
2
cd /etc/nginx
sudo nano sites-enabled/default
cs



찾기(ctrl+w)로 index index.html index.htm; 행을 찾아 다음과 같이 수정


1
index index.php index.html index.htm;
cs


location ~ \.php$ { 가 있는 행을 찾아 다음과 같이 수정


1
2
3
4
location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}
cs


서비스 재시작

1
sudo /etc/init.d/nginx reload
cs


php 테스트

1
sudo nano index.php
cs


php파일 내용

1
<?php echo phpinfo(); ?>
cs

이후 웹에서 확인하면 php버전과 설정을 확인하는 웹페이지가 열린다.




sqlite3와 php모듈 설치 


1
sudo apt-get install sqlite3 php5-sqlite
cs



sqlite php API는 아래 사이트에서 확인

http://www.tutorialspoint.com/sqlite/sqlite_php.htm




[ 라즈베리 파이 -삼바 설정 ]


삼바 설정

 sudo nano /etc/samba/smb.conf



맨 아래에 다음과 같은 설정 추가


[Web Server]

comment = Server HTML root

path = /var/www/html

browsable = yes

public = no

security = user

guest ok = no

read only = no

writeable = yes

create mask = 0755

directory mask = 0755



삼바 재시작

sudo service smbd restart



권한 조정


sudo adduser $USER root



그 다음 chmod와 chown으로 폴더 접근 및 읽기/쓰기를 가능하게 한다.


'Study > Embedded' 카테고리의 다른 글

wizfi 250, mqtt-sqlite 센서값 전송  (0) 2017.08.03
라즈베리파이3, mosquitto  (0) 2017.07.31
라즈베리 HTTP 서버 구축  (0) 2017.06.27
GCM  (0) 2017.06.27
라즈베리파이, Pi4J를 통한 GPIO 제어  (0) 2017.06.20
728x90

아두이노 스케치 (wizfi250 기준)



PubSubClient 라이브러리 설치 후 아래의 소스코드 업로드



#include <SPI.h>

#include <WizFi250.h>

#include <PubSubClient.h>


// Update these with values suitable for your network.


const char* ssid = "SK_WiFiGIGAF5E0";

const char* password = "----"; 

const char* mqtt_server = "192.168.---";


WiFiClient WizFi250Client;

PubSubClient client(WizFi250Client);

long lastMsg = 0;

char msg[50];

int value = 0;


void setup_wifi();

void callback(char* topic, byte* payload, unsigned int length);

void reconnect();


void setup() {

  pinMode(7, OUTPUT);     

  Serial.begin(115200);

  setup_wifi();

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);

}


void setup_wifi() {


  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();

  Serial.print("Connecting to ");

  Serial.println(ssid);


  WiFi.init();

  WiFi.begin((char*)ssid, password);


  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }


  Serial.println("");

  Serial.println("WiFi connected");

  Serial.println("IP address: ");

  Serial.println(WiFi.localIP());

}


void callback(char* topic, byte* payload, unsigned int length) {

  int i = 0;


  Serial.println("Message arrived: topic: " + String(topic));

  Serial.println("Length: "+ String(length,DEC));


  //create character buffer with ending null terminator (string)

  for(i=0; i<length; i++){

    msg[i] = payload[i];

  }

  msg[i]= '\0';


  String msgString = String(msg);

  Serial.println("Payload: "+ msgString);

  int state = digitalRead(7);

  //전송된 메시가 "led"이면 LED를 받을 때마다 켜고 끈다.(토글)

  if (msgString == "led_on"){

    digitalWrite(7, HIGH);

    Serial.println("LED ON...");

  }

  else if (msgString == "led_off"){

    digitalWrite(7, LOW);

    Serial.println("LED OFF...");

  }

}


void reconnect() {

  // Loop until we're reconnected

  while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

    // Attempt to connect

    if (client.connect("WizFi250Client")) {    // 클라이언트가 2대 이상일 경우 이름을 다르게 적어준다.

      Serial.println("connected");

      // Once connected, publish an announcement...

      client.publish("iot", "WizFi250 hello world");    // iot/room1 ... iot/room2 등으로 구분 가능

      // ... and resubscribe

      client.subscribe("iot");

    } else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}

void loop() {


  if (!client.connected()) {

    reconnect();

  }

  client.loop();


  long now = millis();  

}



// DHT11 센서값 json, db저장


#include <SPI.h>

#include <WizFi250.h>

#include <PubSubClient.h>

#include <DHT11.h>

#include <SimpleTimer.h>


#define DHTPIN 8  


SimpleTimer timer;

  

DHT11 dht11(DHTPIN); 

float temperature, humidity;

int err;

int setTemp;

char ch[60] = {0};

char ch2[60] = {0};


const char* ssid = "SK_WiFiGIGAF5E0";

const char* password = "1611010239";  

const char* mqtt_server = "192.168.35.163";


WiFiClient WizFi250Client;

WiFiClient client;


PubSubClient client2(WizFi250Client);

long lastMsg = 0;

char msg[50];

int value = 0;


void setup_wifi();

void callback(char* topic, byte* payload, unsigned int length);

void reconnect();


void setup() {

  pinMode(7, OUTPUT);     

  Serial.begin(115200);

  setup_wifi();

  client2.setServer(mqtt_server, 1883);

  client2.setCallback(callback);

  

  timer.setInterval(15000, notify);

}


void setup_wifi() {


  delay(10);

  // We start by connecting to a WiFi network

  Serial.println();

  Serial.print("Connecting to ");

  Serial.println(ssid);


  WiFi.init();

  WiFi.begin((char*)ssid, password);


  while (WiFi.status() != WL_CONNECTED) {

    delay(500);

    Serial.print(".");

  }


  Serial.println("");

  Serial.println("WiFi connected");

  Serial.println("IP address: ");

  Serial.println(WiFi.localIP());

}


void callback(char* topic, byte* payload, unsigned int length) {

  int i = 0;


  Serial.println("Message arrived: topic: " + String(topic));

  Serial.println("Length: "+ String(length,DEC));


  //create character buffer with ending null terminator (string)

  for(i=0; i<length; i++){

    msg[i] = payload[i];

  }

  msg[i]= '\0';


  String msgString = String(msg);

  Serial.println("Payload: "+ msgString);

  int state = digitalRead(7);

  //전송된 메시가 "led"이면 LED를 받을 때마다 켜고 끈다.(토글)

  if (msgString == "led1_on"){

    digitalWrite(7, HIGH);

    Serial.println("LED ON...");

  }

  else if (msgString == "led1_off"){

    digitalWrite(7, LOW);

    Serial.println("LED OFF...");

  }


  if ( msgString == "temp_humidity#stat") {

     if ( (err=dht11.read(humidity, temperature) ) == 0 ) {      

      String str_temp(temperature);

      String str_hum(humidity);

      

      //str = "ROOM1#TEMP#" + str;

      //str.toCharArray(ch, str.length());

      

      String sensor_id = "\"Dummy-1\"";


      // Make JSON data      

      String msg = "{\"Sensor_ID\": ";

      msg += sensor_id;

      msg += ", \"Humidity\": ";

      msg += str_hum;

      msg += "}";

      msg.toCharArray(ch, msg.length() + 1);


      client2.publish("Home/BedRoom/DHT11/Humidity", ch);   


      // Make JSON data      

      String msg2 = "{\"Sensor_ID\": ";

      msg2 += sensor_id;

      msg2 += ", \"Temperature\": ";

      msg2 += str_temp;

      msg2 += "}";

      msg2.toCharArray(ch2, msg2.length() + 1);

      

      client2.publish("Home/BedRoom/DHT11/Temperature", ch2);   

    }

  }

}



void reconnect() {

  // Loop until we're reconnected

  while (!client2.connected()) {

    Serial.print("Attempting MQTT connection...");

    // Attempt to connect

    if (client2.connect("WizFi250Client0")) {

      Serial.println("connected");

      // Once connected, publish an announcement...

      // ... and resubscribe

      client2.subscribe("iot/room1");

      client2.subscribe("iot/temp");

      client2.subscribe("Home/BedRoom/DHT11/Humidity");

      client2.subscribe("Home/BedRoom/DHT11/Temperature");

      

    } else {

      Serial.print("failed, rc=");

      Serial.print(client2.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}


void loop() {


  if (!client2.connected()) {

    reconnect();

  }

  client2.loop();

  timer.run();


  long now = millis();  

}


void notify() {

  // 일정 주기마다 실행

  if ( client2.state() == 0 ) {

     if ( (err=dht11.read(humidity, temperature) ) == 0 ) {      

      String str_temp(temperature);

      String str_hum(humidity);

      

      //str = "ROOM1#TEMP#" + str;

      //str.toCharArray(ch, str.length());

      

      String sensor_id = "\"Dummy-1\"";


      // Make JSON data      

      String msg = "{\"Sensor_ID\": ";

      msg += sensor_id;

      msg += ", \"Humidity\": ";

      msg += str_hum;

      msg += "}";

      msg.toCharArray(ch, msg.length() + 1);


      client2.publish("Home/BedRoom/DHT11/Humidity", ch);   


      // Make JSON data      

      String msg2 = "{\"Sensor_ID\": ";

      msg2 += sensor_id;

      msg2 += ", \"Temperature\": ";

      msg2 += str_temp;

      msg2 += "}";

      msg2.toCharArray(ch2, msg2.length() + 1);

      

      client2.publish("Home/BedRoom/DHT11/Temperature", ch2);   

    }

  }

}




'Study > Embedded' 카테고리의 다른 글

라즈베리파이에서 nginx, php, php-sqlite 설치  (0) 2017.08.10
라즈베리파이3, mosquitto  (0) 2017.07.31
라즈베리 HTTP 서버 구축  (0) 2017.06.27
GCM  (0) 2017.06.27
라즈베리파이, Pi4J를 통한 GPIO 제어  (0) 2017.06.20
728x90

Install Mosquitto:

CODE: SELECT ALL

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key
rm mosquitto-repo.gpg.key
cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-repo.list
sudo apt-get update
sudo apt-get install mosquitto mosquitto-clients



Test Mosquitto:

(broker) Terminal window 1:

mosquitto -v


...port 1833 


(sub) Terminal window 2:

mosquitto_sub -t test




(pub) Terminal window 3:

mosquitto_pub -t test -m "Good morning"




허용된 유저만 접속하도록 설정



사용자 유저/패스워드를 담는 파일

sudo nano mosquitto_auth.txt   



mosquitto 설정 파일 수정

sudo nano /etc/mosquitto/mosquitto.conf



다음과 같이 수정한다.
allow_anonymous false

password_file /etc/mosquitto/mosquitto_auth.txt


사용자 추가

 sudo mosquitto_passwd /etc/mosquitto/mosquitto_auth.txt <사용자_이름>


비밀번호 입력 및 재 입력을 통해 추가한다.



이후 MQTT Dashboard에서 사용자 이름과 패스워드를 넣고 접속을 해야만 pub 이 가능한 걸 볼 수 있다.




mosquitto start / stop / restart

sudo /etc/init.d/mosquitto start



mosquitto 인증 플러그인


기존의 설치된 mosquitto를 제거, 아래 사이트에서 wget으로 최신 버전을 받아 압축해제한다.

https://mosquitto.org/download/



config.mk 파일 수정

WITH_SRV:=yes를 no로 수정



make 하고 make install 한다.



mosquitto-auth-plug 다운

https://github.com/jpmens/mosquitto-auth-plug


압축 해제 후 config.mk 파일을 적절하게 수정 (config.mk.in을 mk로 바꿔서 수정한다. 사전에 openssl 설치 및 컴파일도 필요)


# Select your backends from this list

BACKEND_CDB ?= no

BACKEND_MYSQL ?= yes

BACKEND_SQLITE ?= no

BACKEND_REDIS ?= no

BACKEND_POSTGRES ?= no

BACKEND_LDAP ?= no

BACKEND_HTTP ?= no

BACKEND_JWT ?= no

BACKEND_MONGO ?= no

BACKEND_FILES ?= no


# Specify the path to the Mosquitto sources here

# MOSQUITTO_SRC = /usr/local/Cellar/mosquitto/1.4.12


MOSQUITTO_SRC = /usr/local/mosquitto


# Specify the path the OpenSSL here


#OPENSSLDIR = /usr/bin

OPENSSLDIR = /usr/local/openssl


# Specify optional/additional linker/compiler flags here

# On macOS, add

#       CFG_LDFLAGS = -undefined dynamic_lookup

# as described in https://github.com/eclipse/mosquitto/issues/244


# CFG_LDFLAGS = -undefined dynamic_lookup  -L/usr/local/Cellar/openssl/1.0.2l/lib

# CFG_CFLAGS = -I/usr/local/Cellar/openssl/1.0.2l/include -I/usr/local/Cellar/mosquitto/1.4.12/include


#CFG_LDFLAGS = -undefined dynamic_lookup  -L/usr/local/openssl/

#CFG_CFLAGS = -I/usr/local/openssl/include -I/usr/local/mosquitto-1.4.14/include

#CFG_CFLAGS = -DRAW_SALT


make하여 생긴  auth-plug.so 파일을 mosquitto 경로(/usr/local/mosquitto) 로 옮겨준다.

mosquitto.conf 에서 # security 항목을 찾아 적절히 수정한다. 


#auth_plugin

auth_plugin /usr/local/mosquitto/auth-plug.so

auth_opt_backends mysql

auth_opt_host localhost

auth_opt_port 3306

auth_opt_dbname 


auth_opt_user root

auth_opt_pass 


auth_opt_userquery SELECT pw FROM users WHERE username = '%s'

#auth_opt_superquery SELECT IFNULL(COUNT(*), 0) FROM users WHERE username = '%s' AND super = 1

auth_opt_aclquery SELECT topic FROM acls WHERE username = '%s'


port 1883

protocol mqtt



mosquitto 브로커 시작

mosquitto -c /usr/local/mosquitto/mosquitto.conf




라즈베리파이 wlan 절전 해제


 sudo nano /etc/network/interfaces



wlan 항목 찾아서 wireless-power off 추가

auto wlan0

allow-hotplug wlan0

iface wlan0 inet dhcp

wireless-power off

    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf





'Study > Embedded' 카테고리의 다른 글

라즈베리파이에서 nginx, php, php-sqlite 설치  (0) 2017.08.10
wizfi 250, mqtt-sqlite 센서값 전송  (0) 2017.08.03
라즈베리 HTTP 서버 구축  (0) 2017.06.27
GCM  (0) 2017.06.27
라즈베리파이, Pi4J를 통한 GPIO 제어  (0) 2017.06.20
728x90

Server.java




import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.util.Iterator;

import java.util.List;

import java.util.Set;

import java.util.Vector;


public class IotServer {

Selector selector;

ServerSocketChannel serverSocketChannel;

List<Client> connections = new Vector<Client>();


void startServer() {

try {

selector = Selector.open();

serverSocketChannel = ServerSocketChannel.open();

serverSocketChannel.configureBlocking(false);

serverSocketChannel.bind(new InetSocketAddress(5001));

serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

} catch (Exception e) {

if(serverSocketChannel.isOpen()) { stopServer(); }

return;

}


Thread thread = new Thread() {

@Override

public void run() {

while(true) {

try {

int keyCount = selector.select();

if(keyCount == 0) { continue; }

Set<SelectionKey> selectedKeys = selector.selectedKeys();

Iterator<SelectionKey> iterator = selectedKeys.iterator();

while (iterator.hasNext()) {

SelectionKey selectionKey = iterator.next();

if (selectionKey.isAcceptable()) {

accept(selectionKey);

} else if (selectionKey.isReadable()) {

Client client = (Client)selectionKey.attachment();

client.receive(selectionKey);

} else if (selectionKey.isWritable()) {

Client client = (Client)selectionKey.attachment();

client.send(selectionKey);

}

iterator.remove();

}

} catch (Exception e) {

if(serverSocketChannel.isOpen()) { stopServer(); }

break;

}

}

}

};

thread.start();


System.out.println("서버 멈춤");

}


void stopServer() {

try {

Iterator<Client> iterator = connections.iterator();

while(iterator.hasNext()) {

Client client = iterator.next();

client.socketChannel.close();

iterator.remove();

}

if(serverSocketChannel!=null && serverSocketChannel.isOpen()) { 

serverSocketChannel.close(); 

}

if(selector!=null && selector.isOpen()) {

selector.close();

}

System.out.println("서버 멈춤");

} catch (Exception e) {}

}


void accept(SelectionKey selectionKey) {

try {

ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();

SocketChannel socketChannel = serverSocketChannel.accept();


String message = "[연결 수락: " + socketChannel.getRemoteAddress()  + ": " + Thread.currentThread().getName() + "]";

System.out.println(message);


Client client = new Client(socketChannel);

connections.add(client);


System.out.println("[연결 개수: " + connections.size() + "]");

} catch(Exception e) {

if(serverSocketChannel.isOpen()) { stopServer(); }

}

}



class Client {

SocketChannel socketChannel;

String sendData;


Client(SocketChannel socketChannel) throws IOException {

this.socketChannel = socketChannel;

socketChannel.configureBlocking(false);

SelectionKey selectionKey = socketChannel.register(selector, SelectionKey.OP_READ);

selectionKey.attach(this);

}


void receive(SelectionKey selectionKey) {

try {

ByteBuffer byteBuffer = ByteBuffer.allocate(100);


//상대방이 비정상 종료를 했을 경우 자동 IOException 발생

int byteCount = socketChannel.read(byteBuffer); 


//상대방이 SocketChannel의 close() 메소드를 호출할 경우

if(byteCount == -1) { 

throw new IOException();

}


String message = "[요청 처리: " + socketChannel.getRemoteAddress() + ": " + Thread.currentThread().getName() + "]";

System.out.println(message);


byteBuffer.flip();

Charset charset = Charset.forName("UTF-8");

String data = charset.decode(byteBuffer).toString();

System.out.println(data);

for(Client client : connections) {

client.sendData = data;

SelectionKey key = client.socketChannel.keyFor(selector);

key.interestOps(SelectionKey.OP_WRITE);

}

selector.wakeup();

String[] receivedMessage = null;

receivedMessage = data.split("#");   

System.out.println(receivedMessage[0]+"\n"+receivedMessage[1]);

if(receivedMessage[0].equals("hello")){

if(receivedMessage[1].equals("server")) {

System.out.println("split");

}

}

} catch(Exception e) {

try {

connections.remove(this);

String message = "[클라이언트 통신 안됨: " + socketChannel.getRemoteAddress() + ": " + Thread.currentThread().getName() + "]";

System.out.println(message);

socketChannel.close();

} catch (IOException e2) {}

}

}


void send(SelectionKey selectionKey) {

try {

Charset charset = Charset.forName("UTF-8");

ByteBuffer byteBuffer = charset.encode(sendData);

socketChannel.write(byteBuffer);



selectionKey.interestOps(SelectionKey.OP_READ);

selector.wakeup();

} catch(Exception e) {

try {

String message = "[클라이언트 통신 안됨: " + socketChannel.getRemoteAddress() + ": " + Thread.currentThread().getName() + "]";

System.out.println(message);

connections.remove(this);

socketChannel.close();

} catch (IOException e2) {}

}

}

}


public static void main(String[] args) {

IotServer server = new IotServer();

server.startServer();

}

}



'Study > Java' 카테고리의 다른 글

JAVA에서의 데이터 타입  (0) 2021.01.11
자바 - 식별자  (0) 2021.01.06
Java Network 프로그래밍 기초  (0) 2017.06.03
NIO 기반 네트워킹  (0) 2017.05.30
JAVA - NIO  (0) 2017.05.29
728x90


sudo python -m SimpleHTTPServer 80


 pip install flask

sudo python app.py host='0.0.0.0'


가상환경 구축


pip install virtualenv

virtualenv "프로젝트폴더명" 

cd 프로젝트폴더명

source bin\activate


pip install 시 에러가 난다면 시간 동기화 문제 때문일 수 있다. 그럴땐 아래와 같이 해결한다.


rdate 설치

sudo apt-get install rdate


시간 얻어오기

rdate -p time.bora.net


시간 설정

rdate -s time.bora.net



혹은 수동으로 시간 설정하려면


sudo date -s "2017-06-27 18:25:45"



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from firebase import firebase
from flask import Flask, render_template, request
import threading
from subprocess import Popen, PIPE
from time import sleep
 
app = Flask(__name__)
 
thread = None
 
firebase = firebase.FirebaseApplication('https://androidpushservice-17$
#raspberry cpu temperature
def get_cpu_temperature():
        process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
        output, _error = process.communicate()
        return float(output[output.index('=') + 1:output.rindex("'")])
def background_thread():
        count = 0
        while True:
                cpu_temp = get_cpu_temperature()
                #database update
                firebase.patch('/raspberrypi3', {'temperature': cpu_te$
                sleep(30)
@app.route("/")
@app.route("/index")
def main():
        global thread
        if thread is None:
                thread = threading.Thread(target=background_thread)
                thread.start()
        return render_template('main.html')
if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True)
cs



온습도 (DHT-11)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Adafruit_DHT
import time
 
sensor = Adafruit_DHT.DHT11
pin = 4
 
while True:
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
 
    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C humidity={1:0.1f}%'.format(temperature, humidity))
        time.sleep(2)
    else:
        print('Failed to get reading. Try again!')
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from firebase import firebase
from flask import Flask, render_template, request
import threading
from subprocess import Popen, PIPE
from time import sleep
import Adafruit_DHT
import time
 
app = Flask(__name__)
 
thread = None
 
sensor = Adafruit_DHT.DHT11
pin = 23
 
firebase = firebase.FirebaseApplication('https://androidpushservice-172000.firebaseio.com/', None)
 
#raspberry cpu temperature
def get_cpu_temperature():
        process = Popen(['vcgencmd''measure_temp'], stdout=PIPE)
        output, _error = process.communicate()
        return float(output[output.index('='+ 1:output.rindex("'")])
 
def background_thread():
        count = 0
        while True:
                cpu_temp = get_cpu_temperature()
                humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
 
                if humidity is not None and temperature is not None:
                        print('Temp={0:0.1f}*C humidity={1:0.1f}%'.format(temperature, humidity))
                        print('Rpi 3 Cpu_Temp={0:0.1f}*C'.format(cpu_temp))
                else:
                        print('Failed to get reading. Try again!')
 
                #database update
                firebase.patch('/raspberrypi3', {'temperature': cpu_temp})
                firebase.patch('/raspberrypi3', {'room_temp' : temperature})
                firebase.patch('/raspberrypi3', {'room_humidity' : humidity})
                sleep(30)
 
@app.route("/")
@app.route("/index")
def main():
        global thread
        if thread is None:
                thread = threading.Thread(target=background_thread)
                thread.start()
        return render_template('main.html')
 
if __name__ == '__main__':
        app.run(host='0.0.0.0', debug=True, port=80)
cs



라이브러리 예제를 통한 실행


pi@raspberrypi78:~/Documents/app/Adafruit_Python_DHT/examples $ sudo ./AdafruitDHT.py 11 23

Temp=28.0*  Humidity=35.0%



LED 제어
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 # -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
 
from flask import Flask, render_template, request
import RPi.GPIO as GPIO
 
app = Flask(__name__)
 
GPIO.setmode(GPIO.BCM)
 
leds = {
        21 : {'name' : 'Red LED''state' : GPIO.LOW},
        20 : {'name' : 'Green LED''state' : GPIO.LOW},
        16 : {'name' : 'Blue LED''state' : GPIO.LOW}
        }
 
for led in leds :
        GPIO.setup(led, GPIO.OUT)
        GPIO.output(led, GPIO.LOW)
 
def getGpioState():
        for led in leds:
                leds[led]['state'= GPIO.input(led)
 
        return leds
 
@app.route("/")
def main():
#for port in ports:
#ports[port]['state'] = GPIO.input(port)
        ledState = getGpioState()
 
        gpioState = {
                'leds' : ledState
        }
 
        return render_template('main.html'**gpioState)
 
@app.route("/<led>/<act>")
def action(led, act):
        led = int(led)
        leds = getGpioState()
        dev = leds[led]['name']
 
        if act == "on":
                GPIO.output(led, GPIO.HIGH)
                msg = dev + "를 켭니다."
        elif act == "off":
                GPIO.output(led, GPIO.LOW)
                msg = dev + "를 끕니다."
        elif act == "toggle":
                GPIO.output(led, not GPIO.input(led))
                msg = "토글 " + dev + "."
        else:
                msg = "예기치 않은 동작입니다!"
 
#for port in ports:
#ports[port]['state'] = GPIO.input(port)
 
        leds = getGpioState()
 
        gpioState = {
                'msg' : msg,
                'leds' : leds
        }
 
        return render_template('main.html'**gpioState)
 
if __name__ == "__main__":
        app.run(host='0.0.0.0', port=80, debug=True)
cs


'Study > Embedded' 카테고리의 다른 글

wizfi 250, mqtt-sqlite 센서값 전송  (0) 2017.08.03
라즈베리파이3, mosquitto  (0) 2017.07.31
GCM  (0) 2017.06.27
라즈베리파이, Pi4J를 통한 GPIO 제어  (0) 2017.06.20
라즈베리 파이3, 기본 설정  (0) 2017.06.10
728x90



https://firebase.google.com/docs/




https://git-scm.com/downloads

Git Bash를 이용한 GCM 예제 다운로드


경로 지정 (D:\adt-bundle\sdk, 디렉토리가 없으면 미리 만든다)

1
 cd /d/adt-bundle/sdk
cs

GCM 예제 다운로드


1
 git clone https://github.com/google/gcm
cs


'Study > Embedded' 카테고리의 다른 글

라즈베리파이3, mosquitto  (0) 2017.07.31
라즈베리 HTTP 서버 구축  (0) 2017.06.27
라즈베리파이, Pi4J를 통한 GPIO 제어  (0) 2017.06.20
라즈베리 파이3, 기본 설정  (0) 2017.06.10
아두이노 LCD  (0) 2017.06.01

+ Recent posts