#!/usr/bin/env ruby
# coding: utf-8

require 'yaml'
require 'mysql2'
require 'active_support/time'

###
### 変数宣言
###

# ホスト名
hosts = ["sugiyama", "hogehoge", ...]    #自分のラズパイやチームメンバーのラズパイのホスト名を配列として列挙する．

# データベースへの接続情報の置き場. 
# ~/public_html 以下には置かないこと.
conf = "/home/hogehoge/iotex-server/conf/db_info.yml"    # <= 自分の環境に合わせて書き換えること!!

# 設定ファイルの読み込み
mydb = YAML.load_file( conf )

# データベースへの接続
client = Mysql2::Client.new(
  :host     => "#{mydb["SERV"]}",
  :username => "#{mydb["USER"]}",
  :password => "#{mydb["PASS"]}",
  :database => "#{mydb["DBNM"]}"
)


###
### 時刻の設定
###

# 平均を開始する時間 (デフォルト値は 2022/12/21)
time_from = DateTime.new( 2022, 12, 21, 0, 0, 0, "JST")

# テーブル monitoring_10min に値が入っている場合は, 開始時刻 time_from の値を更新する.
sql = "............."      # データベースに入っている最後の時刻を取得. DESC か ASC を使い, "LIMIT 1" で取り出すレコードの数を 1 つに限定すると良い. 
client.query(sql).each do |item|
  if item["time"].present?
    time_from = Time.parse( item["time"].to_s )   # 時刻のフォーマットに変換するために Time.parse を用いる.
  end
end

# 平均操作を終了する時間. 現在時刻にセット.
time_end = DateTime.now

p "+++++ START : #{time_from},  END : #{time_end} +++++"


###
### 前 10 分平均値の計算とテーブルへの代入
###

# 変数の初期化
time0 = time_from                 #平均開始時刻.
time1 = time_from + 10.minutes    #平均終了時刻.

# ループを回しながら 10 分平均をとる.
while ( time1 < time_end ) do
  p "#{time0} ... #{time1}"
  
  # ホスト名のループを回す. 
  hosts.each do |host|
#    p host
    
    # SQL 文作成.
    # SELECT で指定する時刻はシングルクォートで囲むこと. また, strftime でフォーマットを指定すること ('#{time1.strftime('%Y-%m-%d %H:%M:%S')}')
    # temp, humi, lux の値を平均すること (5 点以上のデータが存在する場合に).
    # 前 10 分平均なので, 平均する時間帯に time0 は含めず, time1 は含めること.
    # 欠損値処理のため，SELECT 文中で hostname と time は決め打ちしている．
    sql = "INSERT INTO monitoring_10min (hostname,time,temp,humi,lux) 
          SELECT '#{host}', '#{time1.strftime('%Y-%m-%d %H:%M:%S')}', 
                 .... temp の平均値 ....,
                 .... humi の平均値 ....,
                 .... lux の平均値 ....,
           FROM monitoring 
           WHERE hostname =  '#{host}'
                 AND time >  '#{time0.strftime('%Y-%m-%d %H:%M:%S')}'
                 AND time <= '#{time1.strftime('%Y-%m-%d %H:%M:%S')}' "
#    p sql
        
    # SQL 文実行
    client.query(sql)
  end
  
  # 時刻の更新
  time0 = time1
  time1 = time1 + 10.minutes
end
