# Shoes Thermometer by Jonas Elfström 2008-07-19
# heavily based on Shoes Clock by Thomas Bell
#
# Gets the temperature from my webserver every fifth minute
# and presents it as a classic round thermometer.
#

require 'net/http'

Shoes.app :height => 290, :width => 270 do
  @radius, @centerx, @centery = 90, 136, 155
  @host = 'kafka.mine.nu'
  @path = '/t/ute.txt'
  @unit = 'C'
  @location = ' in Kumla at '

  click do
    draw_thermometer
  end

  every(300) do
      draw_thermometer
  end

  def get_temperature
    # A quite ugly way to get and convert the temperature to 1 decimal place
    return ((Net::HTTP.get(@host, @path).to_f*10).round).to_f/10
  end

  def draw_thermometer
    ftemp=get_temperature
    clear do
      draw_background
      stack do
        background black
        para span(ftemp.to_s + @unit + @location + Time.now.strftime("%Y-%m-%d %H:%M"), :stroke => "#fed"),
          :margin => 4
      end
      thermometer_indicator ftemp,2
    end
  end

  def draw_background
    background rgb(230, 240, 200)

    fill white
    stroke black
    strokewidth 4
    oval @centerx - 102, @centery - 102, 204, 204

    fill black
    nostroke
    oval @centerx - 5, @centery - 5, 10, 10

    stroke black
    strokewidth 1
    line(@centerx, @centery - 102, @centerx, @centery - 95)
    line(@centerx - 102, @centery, @centerx - 95, @centery)
    line(@centerx + 95, @centery, @centerx + 102, @centery)
    line(@centerx, @centery + 95, @centerx, @centery + 102)
    
    # Write the Celsius numbers in the circle/oval
    unit=50
    radius_local = 85
    (-40..40).step(5) do |temperature|
      _x = radius_local * Math.sin( temperature * Math::PI / unit )
      _y = radius_local * Math.cos( temperature * Math::PI / unit )
      if _x<0
          _x=_x-15
      else
        if _x>0
          _x=_x-12
        else
          _x=_x-8
        end
      end
      _x=_x+4 if temperature==5
      para temperature.to_s, :left=>@centerx+_x, :top=>@centery-_y-13
    end

  end

  def thermometer_indicator(temperature, sw, unit=50, color=red)
    radius_local = unit == 50 ? @radius : @radius - 25
    _x = radius_local * Math.sin( temperature * Math::PI / unit )
    _y = radius_local * Math.cos( temperature * Math::PI / unit )
    stroke color
    strokewidth sw
    line(@centerx, @centery, @centerx + _x, @centery - _y)
  end
  
  # Present the thermometer at application start
  draw_thermometer

end