mobile Switch to our mobile/Android/iPhone site    Why Why DWC is your best local weather source    Holiday 11 days until Memorial Day (5/28), 31 days until Fathers Day (6/17), 48 days until Independence Day (7/4).    HolidayComplete holiday listHoliday

Code Used at DWC - Temp 82.1° F
The code provided on this page is used here at DeltaWeatherCam.com. It may be freely copied and used for your website. You use this code at your own risk. No warranty is expressed or implied and I accept no liability for any damages that may result from its use.

If you run into problems using any of this code or have questions, please use the contact form and I'll be happy to help as best I can.


Code 1 - Detecting Mobile Browsers

A while back I spent a few days setting up a special page for mobile devices, and creating an auto-detection feature to send mobile visitors there automatically, with an option to return and use the full desktop site. 

I borrowed a lot of ideas from the web and other weather web sites and I'll try and give credit where I can.

The basis of the mobile page was taken from a template mentioned in a topic in the Weather Display forum. Although it calls it an iPhone template, it works great on most smartphones and I renamed it to mobile.php.  It gives credit to Anchorage, KY Weather Center for the original concept and modifications by Snoqualmie, WA Weather.  There are versions that work with WVS and WD outut.  Creating the mobile.php page will require you to edit the code to add references to your specific tags (vws or wd) and to link to your cam and radar, etc.  This is probably the hardest part, locating the proper links to your specific point forecast, etc.  Immediately below this section I include a full copy of the mobile.php file I use with highlights showing the items that I changed.

The code to perform the checking is done in php and was found on the net at http://detectmobilebrowsers.mobi/  This site offers code at no cost for non-commercial use.

Additional code to create and test for cookies was then added to check to see if the mobile visitor had already been to the site and requested to use the desktop version rather than the mobile version. 

So, how do you do it?

1.  First, create your mobile.php file using the template from the WD forum links, or use any mobile page you want!  For now, you can just create a mobile page placeholder with very little data on it as a test. Once you have the mobile page working you can move on to the next step.

2.  Next, add the code from detectmobilebrowsers.mobi (shown below) to your main entry web page, or better yet, to the top of every page, a very easy task if you have a template that every page uses.  Here is how every page on my site begins:

<?php
require_once('mobile_device_detect.php');
if (isset(
$_COOKIE["DWCmobile"]))
echo 
"";
else
mobile_device_detect(true,false,true,true,true,true,true,'http://deltaweathercam.com/mobile.php',false);
?>

Note that the code for which devices are selected as mobile can be changed by altering the 'true' values.  See the .mobi site for details, its easy.  Mine is set to route all mobiles except the iPad to the mobile page. Remember to download the file mobile_device_detect.php and place it in your web root.

Also note that I have added a few lines of code to the mobile detection so that it only gets invoked in the absence of a cookie which is set when a visitor hits the mobile page.  You can rename the cookie to anything you like, usually with some reference to your site name. This results in all mobile visitors going to the mobile page first, but then allows them to ask for the desktop version from there if desired.  The cookie allows them to bypass the mobile check and use the full site, but it expires in an hour which means the next visit they start again at the mobile page.  For the purists, the echo "" is a leftover from some testing, and is there in the event you want to send a blurb to mobile users as you send them to the mobile page.

3.  The mobile page also needs some code to create the cookie.  This is at the top of my mobile.php page in the head section:


<?php
setcookie
("DWCmobile""Been There"time()+3600);
?>

The cookie name DWCmobile should be changed to something relevant to your site, but also remember to change the cookie reference in the code at the top of each page in previous code callout!  The text Been There is not significant, it is just what the cookie contains.  You can also change the expiration time which is currently set to the current time plus 3600 seconds (1 hour). The expiration controls how long the visitor's selection of mobile vs. fulll site remains active, and reinitiates the default on his next connection (an hour after the current visit).

4.  Finally, I added a small link at the very top left corner of my desktop page that links to the mobile page, and a link on the mobile page that goes to the desktop.  You can see these links at http://deltaweathercam.com/index.php and http://deltaweathercam.com/mobile.php.  Don't be fooled by the width of the mobile page, it is elastic and will shrink in width as needed.

The most common problem encountered after implementing this type of check for the user agent is a message similar to:

Warning: Cannot modify header information - headers already sent by (output started at /path/to/yourfilename.php:#) in /path/to/mobile_device_detect.php on line x

This is because your page is sending 'something' before calling the file.  There are several solutions but one of the easiest is to configure your php to enable output buffering.  Normally, session, cookie or HTTP header data in a PHP script must be sent before any output is generated by the script. If this is not possible in your application, you can enable what PHP calls output buffering, with the output_buffering variable.  With output buffering turned on, PHP stores the output of your script in a special memory buffer and sends it only when explicitly told to do so. This allows you to send special HTTP headers and cookie data even in the middle or at the end of your script.  Use of output buffering can slightly degrade performance but only on a very busy site.  The setting in php.ini is:  output_buffering = On


Code 2 - Creating Time-Lapse Video

In case someone might find it useful, here is how I create a video of my camera output.  This example is for my Toshiba cam and creates a video of the previous three hours. 

I have ImageSalsa do a sequential save of my cam image every 15 seconds which creates a series of date/time stamped images, 240 per hour.  I run MovieSalsa every hour using a scheduler (I use VisualCron but the internal Windows scheduler would work fine).  MovieSalsa is set to half of the images (120) for the last 3 hours and create a movie (.avi).  I only use 120 images per hour to reduce the file size created. It also purges all images older than 72 hours. I saved this MovieSalsa configuration file as tlast3hours.tls so I can call it from a batch file, you can use any name desired.



I then convert the .avi file to a mp4 video to reduce the size and make it easy to include in my video player on my site. To do the conversion I use the free utility ffmpeg v0.5.  Unfortunately it is only available as a tar.gz file and requires a unzipper such as 7-Zip to extract the files. The last step I perform is to use the program mp4box to relocate the meta data in the .mp4 file so that it will stream to a visitor rather than waiting for the entire file to be sent before playing.

Here is my batch file:

REM the batch file is located and starts in moviesalsa dir, loads the tls file and runs without display
moviesalsa.exe /F="tlast3hours.tls" /A /I 
REM changes to the ffmpeg dir located below my web root
cd \xampp\htdocs\deltaweathercam\ffmpeg-0.5
REM runs ffmpeg with parameters to load .avi from parent dir and create .mp4 file in parent web root
ffmpeg.exe -i ..\tlast3hours.avi -b 400kb -vcodec libx264 -coder 0 -bf 0 -flags2 -wpred-dct8x8 -crf 22 -y ..\tlast3hours.mp4
REM changes back to my web root
cd ..
REM from the root it runs mp4box.exe located in the mp4box dir which alters the tlast3hours.mp4 so that it properly streams rather than waiting to send the entire file
to the visitor
.\mp4box\MP4Box.exe -inter 2000 tlast3hours.mp4

The code above uses codecs and setting presets to create .mp4 videos that are compatible with desktops and most smartphones, including iPhones. The file will begin playing almost immediately after the visitor clicks play and will stream the video as it is downloaded.

Once I have my .mp4 file I use the JWPlayer from Longtail Video to embed it in my web pages.  There are many options for embedding it but I use their code that is W3C HTML 4.01 Transitional certified. Download the files from LongTail and place them in your web root.

In your document body section include the following:

<script type="text/javascript" src="jwplayer.js"></script>
<!--the DIV below will display the movie, and must have a matching ID to the var velow-->
<div id="last3hours">Loading the player ...</div>
<script type="text/javascript">
var flashvars = { file:'tlast3hours.mp4',autostart:'false' };
var params = { allowfullscreen:'true', allowscriptaccess:'always' };
var attributes = { id:'last3hours', name:'last3hours' };
swfobject.embedSWF('player.swf','last3hours','640','480','9.0.115','false',
flashvars, params, attributes);
</script>

I find the above a much easier method of creating and embedding video than my previous use of the Windows Media Encoder.  It is cross-browser compatible and streams well, avoiding the delay of sending the entire vid to the visitor before display.

I also create the all-day time-lapse in a similar manner, I just use a different .tls file in MovieSalsa and create a different video file with different time parameters.


Code 3 - Creating Audio Forecasts and Conditions

Creating the audio forecast and conditions is a tricky process. It makes use of several programs:

HAMweather - I use the free (for non-commercial use) php version. It creates my forecasts on my main page as well as the text output used for audio files. It is beyond the scope of this discussion to explain how to use HAMweather except to reference the code I use to generate the text files.

2nd Speech Center - This powerful text to speech program isn't free ($39.95) but is one of the easiest tools I have found to create audio from text or screen files. It has both a GUI and command line interface, and I only use the command line.

Simple Search and Replace - This command line utility is used to prep the text files for conversion by 2nd Speech Center by removing and changing abbreviations and other text.

Virtual Weather Station - I use VWS to create the text files that are converted to audio for the current conditions.

Let's first discuss how to create the current conditions audio file.

1. Use VWS to create a text file of the current conditions by using the Internet HTML settings menu choice and create a template file named conditions.htx to create the current conditions:

At ^vst143^ it's ^vst137^. ...^mtr014KEEO^...
The temperature is ^vxv007^ Degrees...
The Wind is out of the ^vst148^ at ^vva002^ mph...
The pressure is ^vxv023^ Inches and ^vst139^...
The Humidity is ^vxv005^ Percent...
Visability is ^mtr011KEEO^ Miles...
Today's HIGH Wind Gust was ^vhi003^ Miles Per Hour At ^vht003^ ...
This Broadcast is Generated Locally by Delta Weather Cam Dot Com, and is updated every 60 seconds.

Put the above filename in the VWS Internet HTML settings template file and have it create an HTML file in your web root named conditions.txt. I have my files created every 1 minute to keep them up to date.

2. Next create a batch file in your web root named conditions.bat:

"C:\Program Files (x86)\2nd Speech Center\ttscmd.exe" /ttm conditions.txt -v 12

I run the above batch file every minute using a scheduler (I use VisualCron but the internal Windows scheduler would work fine). It starts the command line version of 2nd Speech Center called ttscmd.exe and tells it to perform a text to mp3 conversion (/ttm) on the file conditions.txt, and to use the voice number 12. You will need to change the voice number to match your installation since #12 is not one of the default voices that comes with 2nd Speech. To determine the right number, open a command prompt window in your 2nd Speech directory and type ttscmd /v which will return a listing of installed voices and their numbers.

Now let's discuss how to create the forecast audio file.

1. Although Forecast audio only requires a single batch file, you do need to create a template file within HAMweather. In the template folder create a template called voicecast.html Mine looks like this:

Forecast issued %%forecastdate%%
%%zone_warnings%% . . .
%%fc_forecast_text%% . . .
This forecast from N O A A was synthesized to voice by Delta Weather Cam dot com.

The template first posts a line about the creation date of the forecast. It then adds and zone warnings followed by the actual forecast. The last line is just to make it personalized and should be changed to reflect your site. It is formatted to to produce the best speech which is why there are spaces between NOAA and the .com is spelled out.

The main batch file uses the template above to create the text forecast and then converts the text to audio mp3:

cd hw3
c:\xampp\php\php.exe hw3.php forecast=zandh alt=voicecast om=2 of=voice nocache=1
cd ..
ssr.exe 0 "s. ." "s. .... " voicecast.txt
ssr.exe 0 " AM M" " ay em M" voicecast.txt
ssr.exe 0 "mph " "" voicecast.txt
"C:\Program Files (x86)\2nd Speech Center\ttscmd.exe" /ttm voicecast.txt -v 13 -s -1

I run the above batch file every fifteen minutes so it always catches the new forecasts that are issued every 4 hours or so, using a scheduler (I use VisualCron but the internal Windows scheduler would work fine).

It first changes to the HAMweather directory and runs the command line version of php to have HAMweather generate the text forecast of your local area. Note that the path to your version of php will be different. The alt-voicecast refers to the HAMweather template created earlier.

It then changes to the location of the ssr.exe utility, your location may vary. SSR searches for all occurances (0) of the text 's. .' and replaces it with 's. ....' and saves the changes back to the same file voicecast.txt. This change searches for text like 'highs in the 30s. .' and adds extra dots to cause a pause when it is converted to voice.

The next SSR command looks for 'AM M' which is only contained in the time element such as 4:30 AM MST', and it changes it to a phonetic 'ay em M' to force it to say AM rather than am (like I am going to the store).

Finally, it starts the command line version of 2nd Speech Center called ttscmd.exe and tells it to perform a text to mp3 conversion (/ttm) on the file voicecast.txt, and to use the voice number 13 and standard speed -1. You will need to change the voice number to match your installation since #13 is not one of the default voices that comes with 2nd Speech. To determine the right number, open a command prompt window in your 2nd Speech directory and type ttscmd /v which will return a listing of installed voices and their numbers.


Code 4 - Creating Semi-Transparent Pop-Up Overlay Windows

What are they? Click here for a demonstration. These pop-up windows aren't really pop-ups at all, they are a <div> page element that is hidden by default and displayed with a click link. Here is how they are created.

1. Add reference to two new script files in the <head> section of your page

<script src='/jquery-1.5.min.js'></script>
<script src='/jquery.koverlay.1.3.js.txt'></script>

You also need to download these two files, they can be obtained at http://jquery.com and http://plugins.jquery.com/project/kOverlay. If the version number changes on your download, reference the update filenames.

2. At the location in the body of your page where you want the link to launch the popup to appear, place the following anchor reference:

<a href='javascript: void(0);' onClick=" $('#MyPopupDivName').koverlay({title: 'My Popup Div Title Text'}); $('.css_koverlay').css({'background-color':'#006699'});">Text to click to open popup link</a>

<div id="MyPopupDivName" style="display: none;">
Contents to display in popup window, this can be html code, or an iframe reference or even a php include reference. It won't show up until the anchor link is clicked</div> 

The anchor <a... above needs to contain a unique name reference which in this case is MyPopupDivName, which must match the div that appears later in your file. It also contains the Title which you should change to reflect the text you want at the top of the popup window. Finally, change the text for the link to be clicked to launch the popup.

The div <div... above can be placed anywhere in your document after the anchor code. It won't appear until a visitor clicks on the link, and will appear centered over the background page.

The examples below show how to reference iframes and php include files in the anchor.

<a href='javascript: void(0);' onClick=" $('#DWCisLocal').koverlay({title: 'DWC Is Local'}); $('.css_koverlay').css({'background-color':'#006699'});">
Why DWC is your best <span style="font-weight:bold; font-style:italic; color:#F00;">local</span> weather source</a>

<div id="DWCisLocal" style="display: none;">
<?php include ("dwcislocal1.php"); ?>
</div>

<!-- Second example with iframe using an image instead of text to click-->

<a href='javascript: void(0);' onClick=" $('#WDL').koverlay({title: 'Live Instrument Display'}); $('.css_koverlay').css({'background-color':'#006699'});">
<img src="../dwc.jpg" alt="DWC" width="426" height="89" border="0" ></a>

<div id="WDL" style="display: none;">
<iframe src="/live/index.html" width="650" height="545" frameborder="0" id="iframewdl">Your browser does not support inline frames or is currently configured not to display inline frames.</iframe>
</div>