Apress - Smart Home Automation with Linux (2010)- P45 doc

5 125 0
Apress - Smart Home Automation with Linux (2010)- P45 doc

Đang tải... (xem toàn văn)

Thông tin tài liệu

CHAPTER 6 ■ DATA SOURCES 203 if (stristr($rss->items[$i]['title'], "nasa")) system("sendsms myphone "+$rss->items[$i]['description']); This can be particularly useful for receiving up-to-minute sports results, lottery numbers, or voting information from the glut of reality TV shows still doing the rounds on TV stations the world over. Even if it requires a little intelligent pruning to reduce the pertinent information into 140 octets (in the United States) or 160 characters (in Europe, RSA, and Oceania), which is the maximum length of a single unconcatenated text message, it will be generally cheaper than signing up for the paid-for services that provide the same results. Retrieving Data: Pull This encompasses any data that is purposefully requested when it is needed. One typical example is the weather or financial information that you might present at the end of the news bulletin. In these cases, although the information can be kept up-to-date in real time by simulating a push technology, few people need this level of granularity—once a day is enough. For this example, you will use the data retrieved from an online API to produce your own currency reports. This can be later extended to generate currency conversion tables to aid your holiday financing. The data involved in exchange rates is fairly minimal and consists of a list of currencies and the ratio of conversion between each of them. One good API for this is at Xurrency.com. It provides a SOAP-based API that offers up-to-date reports of various currencies. Which specific currencies can vary over time, so Xurrency.com has thoughtfully provided an enumeration function also. If you’re using PHP and PHP- SOAP, then all the packing and unpacking of the XPI data is done automatically for you so that the initialization of the client and the code to query the currency list is simply as follows: $client = new SoapClient("http://xurrency.com/api.wsdl"); $currencies = $client->getCurrencies(); The getCurrencies method is detailed by the Web Services Description Language (WSDL). This is an XML file that describes the abstract properties of the API. The binding from this description to actual data structures takes place at each end of the transfer. Both humans and machines can use the WSDL to determine how to utilize the API, but most providers also include a human-friendly version with documentation and examples, such as the one at http://xurrency.com/api. This getCurrencies method results in an array of currency identifiers (eur for Euro, usd for U.S. dollars, and so on) that can then be used to find the exchange rates. $fromCurrency = "eur"; $toCurrency = "usd"; $toTarget = $client->getValue(1, $fromCurrency, $toCurrency); $fromTarget = $client->getValue(1, $toCurrency, $fromCurrency); Remember that the conversion process, in the real world, is not symmetrical, so two explicit calls have to be made. You can then generate a table with a loop such as the following: $fromName = $client->getName($fromCurrency); $toName = $client->getName($toCurrency); CHAPTER 6 ■ DATA SOURCES 204 for($i=1;$i<=20;++$i) { print "$i $fromName = ".round($i*$toTarget, 2)." $toName\n"; } Or you can store the rates in a file for comparison on successive days. (Note the PHP use of @ in the following example to ignore errors that might be generated by an inaccessible or nonexistent file.) $currencyDir = "/var/log/myhouse/currency"; $yesterdayRate = @file_get_contents("$currencyDir/$toCurrency"); $message = "The $fromName has "; if ($exchangeRate > $yesterdayRate) { $message .= "strengthed against the $toName reaching ".$exchangeRate; } else if ($exchangeRate < $yesterdayRate) { $message .= "lost against the $toName dropping to ".$exchangeRate; } else { $message .= "remained steady at ".$exchangeRate; } @file_put_contents("$currencyDir/$toCurrency", $exchangeRate); In all cases, you write the current data into a regularly updating log file, as you did with the weather status, for the same reasons—that is, to prevent continually requerying it. However, with the financial markets changing more rapidly, you might want to update this file several times a day. Private Data Most of us have personal data on computers that are not owned or controlled by us. Even though the more concerned of us 10 try to minimize this at every turn, it is often not possible or convenient to do so. Furthermore, there are (now) many casual Linux users who are solely desktop-based and aren’t interested in running their own remote servers and will gladly store their contact information, diary, and e-mail on another computer. The convenience is undeniable—having your data available from any machine in the world (with a network connection) provides a truly location-less digital lifestyle. But your home is not, generally, location-less. Therefore, you need to consider what type of useful information about yourself is held on other computers and how to access it. Calendar Groupware applications are one of the areas in which Linux desktop software has been particularly weak. Google has entered this arena with its own solution, Google Calendar, which links into your e- mail, allowing daily reminders to be sent to your inbox as well as to the calendars of other people and groups. 10 “Concerned” is the politically correct way of saying “paranoid.” CHAPTER 6 ■ DATA SOURCES 205 Calendar events that occur within the next 24 hours can also be queried by SMS, and new ones can be added by sending a message to GVENT (48368). Currently, this functionality is available only to U.S. users but is a free HA feature for those it does affect. The information within the calendar is yours and available in several different ways. First, and most simply, it can be embedded into any web page as an iframe: <iframe src="http://www.google.com/calendar/embed? my_email_address  %40gmail.com&ctz=Europe/London" style="border: 0" width="800" height="600"  frameborder="0" scrolling="no"></iframe> This shows the current calendar and allows to you edit existing events. However, you will need to manually refresh the page for edits to become visible, and new events cannot be added without venturing into the Google Calendar page. The apparent security hole that this public URL opens is avoided, since you must already be signed into your Google account for this to work; otherwise, the login page is shown. Alternatively, if you want your calendar to be visible without signing into your Google account, then you can generate a private key that makes your calendar data available to anyone that knows this key. The key is presented as a secret URL. To discover this URL, go the Settings link at the top right of your Google Calendar account, and choose Calendars. This will open a list of calendars that you can edit and those you can’t. Naturally, you can’t choose to expose the details of the read-only variants. So, select your own personal calendar, and scroll down to the section entitled Private Address. The three icons on the right side, labeled XML, ICAL, and HTML, provide a URL to retrieve the data for your calendar in the format specified. A typical HTML link looks like this: http://www.google.com/calendar/embed?src=my_email_address  %40gmail.com&ctz=Europe/London&pvttk=5f93e4d926ce3dd2a91669da470e98c5 The XML version is as follows: http://www.google.com/calendar/feeds/my_email_address  %40gmail.com/private-5f93e4d926ce3dd2a91669da470e98c5/basic The ICAL version uses a slightly different format: http://www.google.com/calendar/ical/my_email_address  %40gmail.com/private-5f93e4d926ce3dd2a91669da470e98c5/basic.ics The latter two are of greater use to us, since they can be viewed (but not edited) in whatever software you choose. If you’re not comfortable with the XML processing language XSLT, then a simple PHP loop can be written to parse the ICAL file, like this: $regex = "/BEGIN:VEVENT.*?DTSTART:[^:]*:([^\s]*).*?SUMMARY:([^\n]*)  .*?END:VEVENT/is"; preg_match_all($regex, $contents, $matches, PREG_SET_ORDER); CHAPTER 6 ■ DATA SOURCES 206 for($i=0;$i<sizeof($matches);++$i) { // $matches[$i][1] holds the entire ICAL event // $matches[$i][1] holds the time // $matches[$i][2] holds the summary } The date format in ICAL can be stored in one of three formats: • Local time • Local time with time zone • UTC time You need not worry about which version is used, since you can use the existing PHP library functions, such as this: $prettyDate = strftime("%A %d %b %Y.", strtotime($matches[$i][1])); ■ Note Be warned that the XML version of your data includes back references to your calendar, which include your private key. Naturally, other online calendar applications exist, offering similar functionality. This version is included as a guide. But having gotten your data onto your own machine, you can trigger your own e- mail notifications, send SMS messages to countries currently unsupported by Google, or automatically load the local florist’s web page when the words grandma and birthday appear. Webmail Most of today’s workforce considers e-mail on the move as a standard feature of office life. But for the home user, e-mail falls into one of two categories: • It is something that is sent to their machine and collected by their local client (often an old version of Outlook Express); consequently, it’s unavailable elsewhere. • It is a web-based facility, provided by Yahoo!, Hotmail, or Google, and can be accessed only through a web browser. Although both statements are (partially) correct, it does hide extra functionality that can be provided very cheaply. In the first case, you can provide your own e-mail server (as I covered in Chapter 5) and add a webmail component using software such as AtMail. This allows your home machine to continue being in charge of all your mail, except that you don’t need to be at home to use it. Alternatively, you can use getmail to receive your webmail messages through an alternate (that is, non-web) protocol. First, you need to ensure that your webmail provider supports POP3 access. This isn’t always easy to find or determine, since the use of POP3 means you will no longer see the ads on CHAPTER 6 ■ DATA SOURCES 207 their web pages. But when it is available, it is usually found in the settings part of the service. All the major companies provide this service, although not all are free. • Hotmail provides POP3 access by default, making it unnecessary to switch on, and after many years of including this only on its subscription service, now Hotmail provides it for free. The server is currently at http://pop3.live.com. • Google Mail was the first to provide free POP3 access to e-mail, from http://pop.gmail.com. Although now most accounts are enabled by default, some older ones aren’t. You therefore need to select Settings and Forwarding and POP/IMAP. From here you can enable it for all mail or any newly received mail. • Yahoo! provides POP3 access and forwarding to their e-mail only through its Yahoo! Plus paid-for service. A cheat is available on some services (although not Yahoo!) where you forward all your mail to another service (such as Hotmail or Gmail) where free POP services are available! Previously, there was a project to process HTML mail directly, eliminating the need to pay for POP3 services. This included the now defunct http://httpmail.sourceforge.net. Such measures are (fortunately) no longer necessary. Once you know the server on which your e-mail lives, you can download it. This can be either for reading locally, for backup purposes, or for processing commands sent in e-mails. Although most e-mail software can process POP3 servers, I use getmail. apt-get install getmail4 I have this configured so that each e-mail account is downloaded to a separate file. I’ll demonstrate with an example, beginning with the directory structure: mkdir ~/.getmail mkdir ~/externalmail touch ~/externalmail/gmail.mbox touch ~/externalmail/hotmail.mbox touch ~/externalmail/yahoo.mbox and then a separate configuration file is created for each server called ~/.getmail/getmail.gmail, which reads as follows: [retriever] type = SimplePOP3SSLRetriever server = pop.gmail.com username = my_email_address@gmail.com password = my_password [destination] type = Mboxrd path = ~/externalmail/gmail.mbox [options] verbose = 2 message_log = ~/.getmail/error.log . available from any machine in the world (with a network connection) provides a truly location-less digital lifestyle. But your home is not, generally, location-less. Therefore, you need to consider. use getmail. apt-get install getmail4 I have this configured so that each e-mail account is downloaded to a separate file. I’ll demonstrate with an example, beginning with the directory. the WSDL to determine how to utilize the API, but most providers also include a human-friendly version with documentation and examples, such as the one at http://xurrency.com/api. This getCurrencies

Ngày đăng: 03/07/2014, 20:20

Mục lục

  • Contents at a Glance

  • About the Technical Reviewers

  • Appliance Control

    • Making Things Do Stuff

    • Using Multiple House Codes

    • Controlling Lights

      • Lamp Module (LM12U)

      • Bayonet Lamp Module (LM15EB)

      • Wall Switch (LW10U)

      • MicroModule with Dimmer (LWM1)

      • DIN Rail Dimmer (LD11)

      • Controlling Appliances

        • Appliance Module (AM12U)

        • Combination Devices

          • Electronic Curtain Rails: Retrofit

          • Electronic Curtain Rails: Prebuilt

          • Tabletop Transmitter Modules

            • Mini Controller (MC460)

            • Sundowner Dusk/Dawn Controller (SD7233/SD533)

            • Mini Timer (MT10U)

            • Handheld Transmitter Modules

              • Handheld RF Remote (HR10U)

              • Keyfob Remote (KR22E)

              • EasyTouch35 Universal Remote Control

              • Gateways and Other Exotic Devices

              • Differences Between X10 and C-Bus

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan