import machine, time, onewire, ds18x20
#from machine import Pin
import badge, ugfx, wifi
import urequests as requests

looptime=3 #minutes between temp update 

def system_init():
  global ds
  global roms
  
  #init badge stuff
  badge.init()
  wifi.init()
  
  #init gfx stuff
  ugfx.init()
  ugfx.input_init()
  
  ugfx.clear(ugfx.BLACK)
  ugfx.flush()
  ugfx.clear(ugfx.WHITE)
  ugfx.flush()

  #setup pins for tempurature senspr

  #provide power to the header expansion
  badge.power_sdcard_enable()
  dat = machine.Pin(33)

  # create the onewire object
  ds = ds18x20.DS18X20(onewire.OneWire(dat))

  # scan for devices on the bus
  roms = ds.scan()

def show_temp():
  ugfx.string(50, 0, "Use A to get temp!" , "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.string(50, 14, "Use B to send temp to server!" , "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.string(50, 42, "My ip is %s" % (wifi_up()) , "Roboto_BlackItalic12", ugfx.BLACK)
  #cur_ip = wifi_up()
  ugfx.input_attach(ugfx.BTN_A, lambda pushed: get_temp() if pushed else False)
  ugfx.input_attach(ugfx.BTN_B, lambda pushed: store_reading() if pushed else False)
  #ugfx.input_attach(ugfx.BTN_START, lambda pushed: loop_store() if pushed else False)
 
  ugfx.flush()

def get_temp():
  global roms
  global ds

  ds.convert_temp()
  print(ds.read_temp(roms[0]))
  ugfx.area(50,30,100,50,ugfx.WHITE)
  ugfx.string(50, 30, "Temp is %f!" % (round(ds.read_temp(roms[0]),1)) , "Roboto_BlackItalic12", ugfx.BLACK) 
  ugfx.flush()
  time.sleep_ms(250)

def wifi_up():
  while not wifi.sta_if.isconnected():
    time.sleep(0.1)
    pass
  print(wifi.sta_if.ifconfig()[0])
  return wifi.sta_if.ifconfig()[0]
    
def store_reading():
  global roms,ds
  now=time.localtime()
  print ("My ip is : %s" % (wifi_up()))
  ds.convert_temp()
  temptemp=ds.read_temp(roms[0])
  print('%d%d%d %d:%d - Store reading :%f' %(now[0],now[1],now[2],now[3],now[4],temptemp))
  #tell the webserver
  webUrl="http://192.168.2.11/tempsense/index.cgi?action=new&reading=%f&type=1" % (round(temptemp,1))
  thermoUrl="http://192.168.2.118/?ctemp=%d" % (int(temptemp*10))
  #tell the thermostat
  try: 
    thermo = requests.get(thermoUrl)
    ugfx.area(50,30,100,50,ugfx.WHITE)
    ugfx.string(50, 30, "Temp is %f!" % (round(temptemp,1)) , "Roboto_BlackItalic12", ugfx.BLACK) 
    ugfx.flush()
    thermo.close()
  except:
    ugfx.string(10, 10, "Could not upload temperature to thermostat", "Roboto_Regular12", 0)
    ugfx.flush()
    print('thermo fail')
    time.sleep(5)
    
  try:
    web = requests.get(webUrl)
    print('web ok')
  except:
    ugfx.string(10, 10, "Could not upload temperature to webserver", "Roboto_Regular12", 0)
    ugfx.flush()
    print('web fail')
    time.sleep(5)
    return

  web.close()
  

def loop_store():
  global looptime
  print("sending temperature every %d mins!" % (looptime))
  while True:
    store_reading()
    print("waiting for %d minute" % (looptime))
    time.sleep(looptime*60)  #wait 1 mins

try:
  system_init()
 
  get_temp()
  time.sleep_ms(500)
  get_temp()
  
  show_temp()
  #handle_web()
  print("All systems go!")
  loop_store()

except Exception as e: 
  #probably a bug:
  ugfx.string(50, 50,str(e), "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.flush()