-- Fetch the lamp control times from a file
-- You can use a service like
-- http://aa.usno.navy.mil/data/docs/RS_OneYear.php
-- to build a file for your location
-- The file is assumed to be in the following format
--    01 Jan 1627 0848
--    02 Jan 1628 0848
--    03 Jan 1630 0847                                                                   
--    etc

lamp_pin = 3         -- GPIO-0

REFRESH_TIMER = 0    -- Refresh the lamp_off-lamp_on data
API_TIMER     = 1    -- Timeout to expect results from API

time_now = 0         -- Ensure current time is not nil if unknown
lamp_on_time = 0      -- Ensure lamp_on time is not nil if unknown
lamp_off_time = 0     -- Ensure lamp_off time is not nil if unknown
date = ""

function find_lamp_times()
  lamp_times_fetched = false
  if not file.open("lamptimes.txt", "r") then
    print('Cannot open file lamptimes.txt')
    return
  end
  
  t = file.readline()
  while t do
    if string.find(t,date) then
      lamp_on_hour = string.sub(t,8,9)
      lamp_on_mins = string.sub(t,10,11)
      lamp_off_hour = string.sub(t,13,14)
      lamp_off_mins = string.sub(t,15,16)
      lamp_times_fetched = true
      break
    end
    t = file.readline()
  end
  file.close()
end

function analyze_times()
  conn:close()
  conn = nil
  if (timenow_fetched) then
    time_now = (time_now_hour*60)+time_now_mins
    find_lamp_times()
  else
    print('Unable to fetch current time')
    time_now = time_now + 1                            -- Use internal clock as estimate
    if time_now>1440 then time_now = time_now-1440 end -- Wrap around at 24 hours
  end
  
  if (lamp_times_fetched) then
    lamp_on_time = (lamp_on_hour*60)+lamp_on_mins
    lamp_off_time = (lamp_off_hour*60)+lamp_off_mins
  end
  
  if time_now>lamp_on_time then
    time_to_lamp_on = (24*60) + lamp_on_time - time_now
  else
    time_to_lamp_on = lamp_on_time - time_now
  end
  mins = time_to_lamp_on%60
  hours = (time_to_lamp_on-mins)/60
  print(hours..' hours, '..mins..' minutes until next lamp_on')

  if time_now>lamp_off_time then
    time_to_lamp_off = (24*60) + lamp_off_time - time_now
  else
    time_to_lamp_off = lamp_off_time - time_now
  end
  mins = time_to_lamp_off%60
  hours = (time_to_lamp_off-mins)/60
  print(hours..' hours, '..mins..' minutes until next lamp_off')

  -- In case of invalid data (all values are equal) lamp defaults to on
  if time_to_lamp_on < time_to_lamp_off then
    print('Lamp off')
    gpio.write(lamp_pin, gpio.LOW)   -- Turn off lamp
  else
    print('Lamp on')
    gpio.write(lamp_pin, gpio.HIGH)  -- Turn on lamp
  end
end

function connect(conn, payload)
  conn:send("HEAD / HTTP/1.1\r\n".. 
                      "Host: google.com\r\n"..
                      "Accept: */*\r\n"..
                      "User-Agent: Mozilla/4.0 (compatible; esp8266 Lua;)"..
                      "\r\n\r\n") 
end

function receive(conn, payload)
  -- Try to find the text "Date: " in the header payload
  date_pos = string.find(payload,"Date: ")
  if (date_pos) then
    date = string.sub(payload,date_pos+11,date_pos+16)
    time_now_hour = string.sub(payload,date_pos+23,date_pos+24)
    time_now_mins = string.sub(payload,date_pos+26,date_pos+27)
    print('Date: '..date..' Time: '..time_now_hour..':'..time_now_mins)
    timenow_fetched = true
  end
end

function refresh()
  if not wifi.sta.getip() then wifi.sta.connect() end
  timenow_fetched = false
  lamp_times_fetched = false

  conn=net.createConnection(net.TCP, 0) 
  conn:on("connection",connect)
  conn:on("receive", receive) 
  conn:connect(80,'google.com') 
  -- Allow 5 seconds to fetch the answer before calculating
  tmr.alarm(API_TIMER,5000,tmr.ALARM_SINGLE,analyze_times)

end

gpio.mode(lamp_pin, gpio.OUTPUT)
gpio.write(lamp_pin, gpio.HIGH)   -- Lamp defaults to on

-- Refresh data on startup
refresh()
-- Refresh every minute
tmr.alarm(REFRESH_TIMER, 60000, tmr.ALARM_AUTO, refresh)



