#define uS_TO_S_FACTOR 1000000
#define mS_TO_S_FACTOR 1000
#define TIME_TO_SLEEP 10
#define TIME_TO_WAKEUP 3300
#define TIME_TO_DELAY 30
RTC_DATA_ATTR int bootCount = 0;
int LED = 27;
const int rpistate = 17;
const int pin_relay = 32;
int counter = 0;
unsigned long sleep_time = 0;
void setup(){
Serial.begin(115200);
delay(1000);
counter=0;
pinMode(pin_relay, OUTPUT);
digitalWrite(pin_relay, LOW);
delay(500);
digitalWrite(pin_relay, HIGH);
pinMode(rpistate, INPUT);
Serial.print("Initial RPi state= ");
Serial.print(digitalRead(rpistate));
Serial.print('\n');
++bootCount;
Serial.println("Boot number: " + String(bootCount));
}
void loop(){
Serial.print("RPi state= ");
Serial.print(digitalRead(rpistate));
Serial.print(",Counter= ");
Serial.print(counter);
Serial.print('\n');
delay(1000);
counter += 1;
if(digitalRead(rpistate)==1){
Serial.print("RPi state= ");
Serial.print(digitalRead(rpistate));
Serial.print('\n');
delay(TIME_TO_DELAY * mS_TO_S_FACTOR);
digitalWrite(pin_relay, LOW);
Serial.print("Sleep start");
sleep_time = TIME_TO_WAKEUP * uS_TO_S_FACTOR;
Serial.print(sleep_time);
esp_sleep_enable_timer_wakeup(sleep_time);
esp_deep_sleep_start();
}
}
import requests
import time
import picamera
import datetime
import os
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import ntp_get
from w1thermsensor import W1ThermSensor
from ina219 import INA219
from ina219 import DeviceRangeError
SHUNT_OHMS = 0.1
temperature = 0.0
voltage = 0.0
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
Sw_pin = 18
finish_pin = 17
Interval_pin = 24
def take_photo(temperature, voltage):
with picamera.PiCamera() as camera:
camera.resolution = (640, 480)
camera.start_preview()
time.sleep(2)
camera.capture('/home/pi/Documents/rice/my_picture.jpg')
fname='/home/pi/Documents/rice/my_picture.jpg'
url = "https://notify-api.line.me/api/notify"
token = "それぞれのトークン"
headers = {"Authorization" : "Bearer "+ token}
dt_current = datetime.datetime.now()
message_date = dt_current.strftime('\n%Y年%m月%d日 %H:%M:%S')
add = (" の様子。\n温度は %.2f ℃\nバッテリー電圧は %.3f V" % (temperature, voltage))
message = message_date + add
payload = {"message" : message}
files = {"imageFile": open(fname, "rb")}
r = requests.post(url, headers = headers, params=payload, files=files)
def send_data():
fname = '/home/pi/Documents/rice/data.png'
url = "https://notify-api.line.me/api/notify"
token = "それぞれのトークン"
headers = {"Authorization" : "Bearer "+ token}
dt_current = datetime.datetime.now()
message_date = dt_current.strftime('%Y年%m月%d日')
add = ("のデータ")
message = message_date + add
payload = {"message" : message}
files = {"imageFile": open(fname, "rb")}
r = requests.post(url, headers = headers, params=payload, files=files)
def measurement():
sensor = W1ThermSensor()
celsius = sensor.get_temperature()
ina = INA219(SHUNT_OHMS)
ina.configure()
ina_voltage = ina.voltage()
return celsius, ina_voltage
def data_saving(temperature, voltage):
df = pd.read_csv('/home/pi/Documents/rice/measurement_data.csv')
x = df['date']
y1 = df['temperature']
y2 = df['voltage']
temp = df['temperature']
temp[1:721] = temp.iloc[0:720]
volt = df['voltage']
volt[1:721] = volt.iloc[0:720]
temp[0] = temperature
volt[0] = voltage
df['temperature'] = temp
df['voltage'] = volt
fig = plt.figure(figsize=(6, 4))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2,sharex=ax1)
ax1.set_xlim(-30, 0)
ax1.plot(x, y1, color='black')
ax1.set_ylabel('Temp [C]')
ax1.grid(linestyle='--', linewidth=0.7)
ax2.set_xlim(-30, 0)
ax2.set_xlabel('Day')
ax2.plot(x, y2, color='red')
ax2.set_ylabel('Battery [V]', color='red')
ax2.grid(linestyle='--', linewidth=0.7)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.subplots_adjust(hspace=0.001)
plt.savefig("/home/pi/Documents/rice/data.png", bbox_inches='tight')
df.to_csv('/home/pi/Documents/rice/measurement_data.csv', index=False)
def post_line(message):
fname = '/home/pi/Documents/rice/data.png'
url = "https://notify-api.line.me/api/notify"
token = "それぞれのトークン"
headers = {"Authorization" : "Bearer "+ token}
payload = {"message" : message}
files = {"imageFile": open(fname, "rb")}
r = requests.post(url, headers = headers, params=payload)
def run_shell_command(command_str):
proc = subprocess.run(command_str, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
result = proc.stdout.split("=")
return result[1].replace('\n', '')
def rpi_state():
temp = run_shell_command("vcgencmd measure_temp")
memory_cpu = run_shell_command("vcgencmd get_mem arm")
memory_gpu = run_shell_command("vcgencmd get_mem gpu")
return temp, memory_cpu, memory_gpu
def post_line_state(temperature, voltage):
state = rpi_state()
fname = '/home/pi/Documents/rice/data.png'
url = "https://notify-api.line.me/api/notify"
token = "それぞれのトークン"
headers = {"Authorization" : "Bearer "+ token}
dt_current = datetime.datetime.now()
message_date = dt_current.strftime('\n%Y年%m月%d日')
print(state[0], state[1], state[2])
add = (" の様子。\n装置内温度は {:.2f}℃ \nバッテリー電圧は {:.3f}V \nCPU温度は {} \nCPUメモリは {} \nGPUメモリは {}" .format(temperature, voltage, state[0], state[1], state[2]))
message = message_date + add
payload = {"message" : message}
files = {"imageFile": open(fname, "rb")}
r = requests.post(url, headers = headers, params=payload)
if __name__ == "__main__":
time.sleep(40)
ntp_get.time_setting()
message_0 = ("Good morning RPi!")
post_line(message_0)
temperature, voltage = measurement()
post_line_state(temperature, voltage)
dt_now_round = datetime.datetime.now()
round_min = int(dt_now_round.minute)
if(round_min<4):
time.sleep(1)
else:
wait_time = (62 - round_min) * 60
message_1 = ("wait nice round time for %d sec" % wait_time)
post_line(message_1)
time.sleep(wait_time)
dt_now = datetime.datetime.now()
GPIO.setup(Sw_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(Interval_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(finish_pin, GPIO.OUT)
state_pin = GPIO.input(Sw_pin)
interval = GPIO.input(Interval_pin)
message_2 = ("Blue line was shorted")
data_saving(temperature, voltage)
if (6 <= dt_now.hour <= 18):
take_photo(temperature, voltage)
print("finished post")
if (dt_now.hour == 19):
send_data()
if(state_pin==0):
print("No18 does not connect to GND, shut down process will not start")
message_3 = ("Orange line was shorted")
post_line(message_3)
else:
count_down_min = 0
minute = int(dt_now.minute)
count_down_min = minute
count_down_sec = count_down_min * 60 + int(dt_now.second)
esp32_sleep_time = 3300
esp32_shutdown_wait_time = 30
count_down = 3600 - (esp32_sleep_time + esp32_shutdown_wait_time + count_down_sec)
print("wait sleep time")
print(count_down)
if(count_down<0):
count_down = 0
else:
message_4 = ("Shutdown will start within %d sec" %count_down)
post_line(message_4)
time.sleep(count_down)
GPIO.output(finish_pin, 1)
message_5 = ("Shutdown signal was sent")
post_line(message_5)
time.sleep(5.0)
GPIO.output(finish_pin, 0)
print("shut down process will start in 5 seconds")
os.system("sudo shutdown -h now")