PDA

View Full Version : Weather retrieval using Luacom and Threads...



Promixis
April 2nd, 2005, 12:25 PM
This is a quick example of a weather object that you can use with threads. Its also shows how you need to use the gir.coinitialize functions to use luacom with threads..




--[[

Weather Object

Object/class for retreiving the weather from weather.com

Also shows how to use luacom from a seperate thread

--]]



WeatherRetrieval = {

Location = 55410,

RefreshInterval = 30, -- minutes refreseh for current conditions,

RefreshTime = 0,

Weather = nil,-- contains current weather

ThreadID = nil, -- contains thread for async retreival

New = function (self,o)
o = o or {}
setmetatable (o,self)
self.__index = self
return o
end,

Update = function (self)
gir.CoInitialize()

if win.GetElapsedSeconds &#40;self.RefreshTime&#41; < self.RefreshInterval then
-- return nil
end

self.RefreshTime = win.GetElapsedSeconds &#40;&#41;

local WeatherHTTPReq = luacom.CreateObject&#40;"WinHttp.WinHttpRequest.5.1"&#41;
if not WeatherHTTPReq then
return
end
WeatherHTTPReq&#58;Open&#40;"GET", "http&#58;//www.msnbc.com/m/chnk/d/weather_d_src.asp?acid=" .. self.Location, 0&#41;
WeatherHTTPReq&#58;Send&#40;&#41;;

if WeatherHTTPReq.Status ~= 200 then
return
end

local s = WeatherHTTPReq.ResponseText

Math = &#123;&#125;
Math.round = function &#40;x&#41;
return math.floor &#40;x&#41;
end

s= string.gsub &#40;s,"&#125;","return this end"&#41;
s =&#40;string.gsub &#40;s,"&#123;","this = &#123;&#125;"&#41;&#41;
s= string.gsub &#40;s,"sw",""&#41;

local sf = loadstring &#40;s&#41;
sf &#40;&#41;

weather = makeWeatherObj &#40;&#41;

Math = nil
WeatherHTTPReq = nil
collectgarbage &#40;&#41;
self.Weather = weather
gir.CoUninitialize&#40;&#41;;
return true -- success
end,

UpdateAsync = function &#40;self&#41;
self.ThreadID = thread.newthread &#40;function &#40;...&#41; return self&#58;Update &#40;unpack &#40;arg&#41;&#41; end,&#123;self&#125;&#41;
end,

Print = function &#40;self&#41;

while self.ThreadID&#58;isthreadrunning &#40;&#41; do -- wait if async retrieval
print &#40;"Waiting"&#41;
win.Sleep &#40;100&#41;
end


for x,y in pairs &#40;self.Weather&#41; do
print &#40;x,"&#58; ",y&#41;
end
end

&#125;

MplsWeather = WeatherRetrieval&#58;New &#40;&#123;Location = 55410&#125;&#41;

MplsWeather&#58;UpdateAsync &#40;&#41;
--MplsWeather&#58;Update &#40;&#41;

MplsWeather&#58;Print &#40;&#41;