import machine, time, onewire, ds18x20
#from machine import Pin
import badge, ugfx, wifi
import urequests as requests

looptime=1 #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 get_temp():
  global roms
  global ds
  ds.convert_temp()
  print("%.2f"%ds.read_temp(roms[0]))
  time.sleep(100)
  ds.convert_temp()
  print("%.2f"%ds.read_temp(roms[0]))
  ugfx.area(49,30,200,100,ugfx.WHITE)
  ugfx.string(50, 30, "Temp is %.2f" % (ds.read_temp(roms[0])) , "Roboto_BlackItalic24", 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])
  #tell the webserver
  thermoUrl="http://192.168.3.24:8080/json.htm?type=command&param=udevice&idx=79&nvalue=0&svalue=%.2f" % (temptemp)
  print(thermoUrl)
  #tell the thermostat
  try: 
    thermo = requests.get(thermoUrl)
    ugfx.area(50,30,200,100,ugfx.WHITE)
    ugfx.string(50, 30, "Temp is %.2f" % (temptemp) , "Roboto_BlackItalic24", 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)

def loop_store():
  store_reading()
  #time.sleep(looptime*60)  #wait 1 mins


system_init()
print("All systems go!")
sleeptime = 60000

count = 0
while True:
  get_temp()
  time.sleep_ms(sleeptime)  
  loop_store()
  #get_temp()
  
  #show_temp()
  #handle_web()


"""except Exception as e: 
  #probably a bug:
  ugfx.string(50, 50,str(e), "Roboto_BlackItalic12", ugfx.BLACK)
  ugfx.flush()"""