chatGPT는 먼가 성능이 좋지도 신뢰도 할 수 없는 적토마 라는 느낌인데
claude는 제법 똑똑하고 미음이 가는 경주마 라는 느낌?
4~5번의 대화 끝에 아래의 소스를 생성해준다. 이정도면 chatGPT보다 빠르고 나름 믿고 쓸만한 듯?
| 네, 요청하신 대로 DHT22에서 습도를, BMP280에서 온도와 기압을 측정하고, 이를 원격 라즈베리 파이 데이터베이스 서버로 전송하는 전체 시스템에 대한 개별 소스코드를 작성해 드리겠습니다. 1. 센서 데이터 수집 (클라이언트 라즈베리 파이): ```python # sensor_client.py import Adafruit_DHT import Adafruit_BMP.BMP280 as BMP280 import time import requests import uuid # 센서 설정 DHT_SENSOR = Adafruit_DHT.DHT22 DHT_PIN = 4 # GPIO 핀 번호 bmp = BMP280.BMP280() # 클라이언트 ID 설정 CLIENT_ID = str(uuid.uuid4()) # 서버 설정 SERVER_URL = "http://your_server_ip:5000/api/weather" def get_sensor_data(): humidity, _ = Adafruit_DHT.read_retry(DHT_SENSOR, DHT_PIN) temperature = bmp.read_temperature() pressure = bmp.read_pressure() / 100 # hPa로 변환 return { "client_id": CLIENT_ID, "temperature": round(temperature, 2), "humidity": round(humidity, 2) if humidity is not None else None, "pressure": round(pressure, 2) } def send_data(data): try: response = requests.post(SERVER_URL, json=data) print(f"Data sent. Status code: {response.status_code}") except requests.RequestException as e: print(f"Error sending data: {e}") if __name__ == "__main__": while True: data = get_sensor_data() send_data(data) time.sleep(300) # 5분마다 데이터 전송 ``` 2. 서버 API (서버 라즈베리 파이): ```python # server_api.py from flask import Flask, request, jsonify import psycopg2 from psycopg2.extras import RealDictCursor app = Flask(__name__) # 데이터베이스 연결 설정 DB_PARAMS = { "host": "localhost", "database": "weather_db", "user": "your_username", "password": "your_password" } def get_db_connection(): return psycopg2.connect(**DB_PARAMS) @app.route('/api/weather', methods=['POST']) def add_weather_data(): data = request.json conn = get_db_connection() cur = conn.cursor() try: cur.execute( "INSERT INTO weather_data (client_id, temperature, humidity, pressure) VALUES (%s, %s, %s, %s)", (data['client_id'], data['temperature'], data['humidity'], data['pressure']) ) conn.commit() return jsonify({"message": "Data added successfully"}), 201 except Exception as e: conn.rollback() return jsonify({"error": str(e)}), 400 finally: cur.close() conn.close() @app.route('/api/weather', methods=['GET']) def get_weather_data(): conn = get_db_connection() cur = conn.cursor(cursor_factory=RealDictCursor) try: cur.execute("SELECT * FROM weather_data ORDER BY timestamp DESC LIMIT 100") data = cur.fetchall() return jsonify(data) finally: cur.close() conn.close() if __name__ == '__main__': app.run(host='0.0.0.0', port=5000) ``` 3. 데이터베이스 설정 (서버 라즈베리 파이): PostgreSQL을 사용한다고 가정하고, 다음과 같이 데이터베이스와 테이블을 설정합니다: ```sql CREATE DATABASE weather_db; \c weather_db CREATE TABLE weather_data ( id SERIAL PRIMARY KEY, client_id VARCHAR(50), temperature FLOAT, humidity FLOAT, pressure FLOAT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); ``` 4. 필요한 라이브러리 설치: 클라이언트 라즈베리 파이: ``` pip install Adafruit_DHT Adafruit_BMP280 requests ``` 서버 라즈베리 파이: ``` pip install flask psycopg2-binary ``` 5. 시스템 실행: 클라이언트 라즈베리 파이: ``` python sensor_client.py ``` 서버 라즈베리 파이: ``` python server_api.py ``` 이 시스템에서: - 클라이언트 라즈베리 파이는 센서에서 데이터를 수집하고 5분마다 서버로 전송합니다. - 서버 라즈베리 파이는 API를 통해 데이터를 받아 데이터베이스에 저장합니다. - GET 요청을 통해 최근 100개의 데이터를 조회할 수 있습니다. 실제 구현 시 고려할 점: 1. 오류 처리와 로깅을 더 강화하세요. 2. HTTPS를 사용하여 데이터 전송을 암호화하세요. 3. 클라이언트 인증을 추가하여 보안을 강화하세요. 4. 데이터베이스 연결 풀링을 사용하여 성능을 개선하세요. 5. 환경 변수를 사용하여 설정을 관리하세요. 이 코드는 기본적인 구조를 제공합니다. 실제 환경에 맞게 수정하여 사용하시기 바랍니다. |
'개소리 왈왈 > 인공지능' 카테고리의 다른 글
| 클로드를 이용해 코드는 손도 안대고 웹페이지 만들기 (1) | 2024.09.13 |
|---|---|
| 클로드로 날로먹기 모드 (0) | 2024.09.12 |
| GPT-4o? (0) | 2024.05.27 |
| GPT 4. 미국 변호사 시험 상위 10% (0) | 2023.03.16 |
| 대 AI시대, 프로그래머란...? (2) | 2023.02.08 |