englishtokorea/main_backup.py
2025-05-28 14:26:49 +09:00

203 lines
7.0 KiB
Python

import pymysql
import pygame
import time
import RPi.GPIO as GPIO
import requests
import json
import psutil
from datetime import datetime
from gtts import gTTS
from mutagen.mp3 import MP3
from luma.core.interface.serial import spi, noop
from luma.core.render import canvas
from luma.core.legacy import text, show_message
from luma.core.virtual import viewport
from luma.led_matrix.device import max7219
from PIL import ImageFont
from luma.core.legacy.font import proportional, CP437_FONT, TINY_FONT
timedisplay = False
# 밝기센서 핀 설정
light_sensor_pin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(light_sensor_pin, GPIO.IN)
#밝기체크 gpio
def brightness():
return GPIO.input(light_sensor_pin)
# 폰트설정
font = ImageFont.truetype("/home/pi/python_project/NeoDunggeunmoPro-Regular.ttf", size=16)
font2 = ImageFont.truetype("/home/pi/python_project/pixelmix.ttf", size=6)
font3 = ImageFont.truetype("/home/pi/python_project/DungGeunMo.ttf", size=8)
#max7219 클래스 초기화
serial = spi(port=0, device=0, gpio=noop())
device = max7219(serial,width=32, height=16,block_orientation=-90, blocks_arranged_in_reverse_order=False)
#데이터베이스 세팅
class db_con:
host="syye.net"
user="pythonUser"
password="Tjekdfl1324%^"
database="pythonDB"
char='utf8'
# MySQL 서버 연결 설정
conn = pymysql.connect(
host="syye.net",
user="pythonUser",
password="Tjekdfl1324%^",
db="pythonDB",
charset='utf8',
autocommit=True)
# mysql 커서 생성
curs = conn.cursor(pymysql.cursors.DictCursor)
def byte_transform(bytes, to, bsize=1024):
a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 }
r = float(bytes)
for i in range(a[to]):
r = r / bsize
return round(r,2)
#현제시간 / 날씨d
def animation(device):
#openweathermap api 데이터 호출
api = "https://api.openweathermap.org/data/2.5/weather?lat=35.8242238&lon=127.1479532&appid=00eb2155e51742aa2856a69da0f6dc61&lang=kr&units=metric"
result = requests.get(api)
result = json.loads(result.text)
weather = result['weather'][0]['description'] #날씨
temperature = result['main']['temp'] # 현제온도
feels_like = result['main']['feels_like'] # 체감온도
humidity = result['main']['humidity'] # 습도
toggle = False # Toggle the second indicator every second
while True:
memory = psutil.virtual_memory()
total_memory = byte_transform(memory.total,'m')
used_memory = byte_transform(memory.used,'m')
free_memory = byte_transform(memory.available,'m')
print(f"Total Memory: {total_memory} M")
print(f"Used Memory: {used_memory} M")
print(f"Free Memory: {free_memory} M")
toggle = not toggle
hours = datetime.now().strftime('%H')
minutes = datetime.now().strftime('%M')
month = datetime.now().strftime('%m')
day = datetime.now().strftime('%d')
sec = datetime.now().second
print(sec)
if sec == 1:
# 조회
sql = "SELECT * FROM chet where stat='0' order by id asc limit 1"
curs.execute(sql)
rows = curs.fetchall()
cnt = curs.rowcount
print(cnt)
if cnt > 0:
dataload(device,rows)
break
elif sec == 20:
weathertext = "전주 오늘날씨 : " + weather + ", 온도:" + str(temperature) + "도, 체감온도:" + str(
feels_like) + "도, 습도:" + str(humidity) + "%"
virtual = viewport(device, height=device.width, width=len(weathertext) * 14)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), weathertext, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
elif sec == 40:
api = "https://quotation-api-cdn.dunamu.com/v1/forex/recent?codes=FRX.KRWUSD"
result = requests.get(api)
result = json.loads(result.text)
name = result[0]['name']
times = result[0]['time']
basePrice = result[0]['basePrice']
provider = result[0]['provider']
pricetext = name+" 환율 : 1$ / " + str(basePrice) + " 시간:" + str(times) + " 자료:" + str(provider)
virtual = viewport(device, height=device.width, width=len(pricetext) * 13)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), pricetext, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
else:
with canvas(device) as draw:
text(draw, (1, 8), hours, fill="white", font=proportional(CP437_FONT))
text(draw, (16, 8), ":" if toggle else " ", fill="white", font=proportional(TINY_FONT))
text(draw, (18, 8), minutes, fill="white", font=proportional(CP437_FONT))
draw.text((2, 1),month+". "+day, fill="white", font=font2)
if sec%3 == 0:
device.contrast(255) if brightness() == 0 else device.contrast(10)
time.sleep(0.5)
def dataload(device,rows):
# 가져온 데이터를 처리하거나 출력할 수 있습니다.
for data in rows:
title = data['mess']
author = data['name']
idx = data['id']
# 출력한 데이터 업데이트
update_query = "UPDATE chet set stat=%s where id=%s"
data = ("1", idx)
curs.execute(update_query, data)
# 음성으로 작성할 문구
script = author + "가 보낸메세지 "
script += title
# mp3파일 생성
tts_ko = gTTS(text=script, lang='ko')
tts_ko.save('./temp.mp3')
# mp3파일 재생
audio = MP3("./temp.mp3")
times = audio.info.length
pygame.mixer.init()
pygame.mixer.music.load("./temp.mp3")
pygame.mixer.music.play()
time.sleep(1)
virtual = viewport(device, height=device.width, width=len(title) * 16)
with canvas(virtual) as draw:
draw.rectangle(device.bounding_box)
draw.text((32, 1), "mess : " + title, fill="white", font=font)
for offset in range(virtual.width - device.width):
# Led밝기
device.contrast(255) if brightness() == 0 else device.contrast(10)
virtual.set_position((offset, 0))
time.sleep(0.03)
time.sleep(times) # wait and let the sound play for 1 second
pygame.mixer.music.stop()
print('end')
animation(device)
animation(device)