본문 바로가기
공부기록

6월 26일 라즈베리파이 - 네트워크

by project100 2023. 6. 26.

+ : GPIO 21 

-  : GND

 

라즈베리파이 네크워트 활용

requests 모듈

 설치) sudo pip3 install requests

 Get 방식의 데이터 전송

 requests.get(url, params)

 url : 서버의 주소와 해당 매핑 url

 params : 딕셔너리 형태로 데이터를 작성

 

예)  url : 'http://ip주소/mapurl'

       params = {'data1': 'value1', 'data2':'value2', ....}

       response = requests.get(url, params=param)

 

json 모듈을 사용한 post 전송

다양한 데이터를 전송할 때 json 형태로 변환하여 서버에 전송할 수 있음.

이 때 headers 매개변수를 사용

딕셔너리로 데이터를 작성

-> json.dumps() : json 객체로 변환(json 모듈이 제공)

 

requests.post(url, data=json.dumps(d), headers=hd)

hd = {'Content-Type':'application/json; charset=utf-8'}

requests.post(url, data=json.dumps(d), headers=hd)

 

 

인텔리제이

package com.raspberry.raspiserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HomeController {
    @GetMapping("getreq")
    @ResponseBody
    public String getResquest(){
        log.info("getResquest()");
        return "ok";
    }
}

vs code

서버랑 연결 잘 된 경우 :  200

reture 값 : ok

import requests

response = requests.get('http://192.168.0.xxx:8080/getreq')
print(response.status_code)
print(response.text)

 

 

 

 

 

데이터 전송

 

get 방식

인텔리제이

package com.raspberry.raspiserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HomeController {
    @GetMapping("getreq")
    @ResponseBody
    public String getResquest(String data1, String data2){
        log.info("getResquest()");
        log.info("전송받은 데이터 : " + data1);
        log.info("전송받은 데이터 : " + data2);
        return "ok";
    }
}

vs code

import requests

server_url = 'http://192.168.0.sss:8080/'
dest_url = server_url + 'getreq'
param = {'data1':'AA', 'data2':'BB'}

response = requests.get(dest_url, params=param)
print(response.status_code)
print(response.text)

 

post 방식

인텔리제이

package com.raspberry.raspiserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HomeController {
    @PostMapping("postreq")
    @ResponseBody
    public String postResquest(String p1, String p2){
        log.info("postResquest()");
        log.info("전송받은 데이터 : " + p1);
        log.info("전송받은 데이터 : " + p2);
        return "OK";
    }
}

vs code

import requests

server_url = 'http://192.168.0.zzz:8080/'
dest_url = server_url + 'getreq'
param = {'data1':'AA', 'data2':'BB'}

# post 방식으로 전송
dest_url = server_url + 'postreq'
d = {'p1':'123', 'p2':'456'}
resp = requests.post(dest_url, data=d)
print(resp.status_code)
print(resp.text)

 

json 방식

인텔리제이

// dto
package com.raspberry.raspiserver.dto;

import lombok.Data;

@Data
public class DataDto {
    private String name;
    private int age;
    private String addr;
}

// controller
package com.raspberry.raspiserver.controller;

import com.raspberry.raspiserver.dto.DataDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HomeController {
    @PostMapping("jsonreq")
    @ResponseBody
    public String jsonRequest(@RequestBody DataDto data){
        log.info("jsonRequest()");
        log.info("name : " + data.getName());
         log.info("age : " + data.getAge());
        log.info("addr : " + data.getAddr());
        return "확인";
    }
}

 

vs code

import requests
import json

server_url = 'http://192.168.0.ddd:8080/'
dest_url = server_url + 'getreq'
param = {'data1':'AA', 'data2':'BB'}

# json 형태로 전송(post)
dest_url = server_url + 'jsonreq'
d2 = {'name':'전우치', 'age':23, 'addr':'인천시 부평구' }
hds = {'Content-Type':'application/json; charset=utf-8'}
resp2 = requests.post(dest_url, data=json.dumps(d2), headers=hds)
print(resp2.status_code)
print(resp2.text)

 

Map 형식

   @PostMapping("jsonreq")
    @ResponseBody
    public Map<String, String> jsonRequest(@RequestBody DataDto data){
        log.info("jsonRequest()");
        log.info("name : " + data.getName());
        log.info("age : " + data.getAge());
        log.info("addr : " + data.getAddr());
        Map<String, String> rmap = new HashMap<>();
        rmap.put("result", "ok");
        return rmap;
    }

 

온습도계 연결

 

+ : 5.5v

out  : GPIO

- : GRD

 

인텔리제이

// dto
package com.raspberry.raspiserver.dto;

import lombok.Data;

@Data
public class SensingDto {
    private float temp;
    private float hum;
    private String time;
}


// controller
package com.raspberry.raspiserver.controller;

import com.raspberry.raspiserver.dto.DataDto;
import com.raspberry.raspiserver.dto.SensingDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class HomeController {
    @PostMapping("dht11")
    @ResponseBody
    public String sensingDht11(@RequestBody SensingDto sens){
        log.info("sensingDth11()");
        log.info("온도 : " + sens.getTime());
        log.info("습도 : " + sens.getHum());
        log.info("시간 : " + sens.getTime());
        return "ok";
    }
}

vs code

from datetime import datetime
import Adafruit_DHT as D
import requests
import json
import time

try:
    while True:
        h, t = D.read_retry(D.DHT11, 14)
        print(F'온도 : {t:0.1f}도, 습도 : {h:0.1f}%')
        timeObj = datetime.now()
        times = timeObj.strftime('%d-%b-%Y %H:%M:%S')
        data={"temp":t, "hum":h, "time":times}
        sendurl='http://192.168.0.ccc:8080/dht11'
        hds = {'Content-Type':'application/json; charset=utf-8'}
        resp = requests.post(sendurl, data=json.dumps(data), headers=hds)
        print(resp)
        time.sleep(2)
except KeyboardInterrupt:
    print('전송중단')
finally:
    print('프로그램 종료')