home *** CD-ROM | disk | FTP | other *** search
/ io Programmo 11 / IOPROG_11.ISO / docs / ups-ho~1 < prev    next >
Encoding:
Text File  |  1997-03-30  |  127.8 KB  |  3,425 lines

  1.   The UPS Howto
  2.   Harvey J. Stein, abel@netvision.net.il, Berger Financial Research,
  3.   Ltd.
  4.   v2.02, 31 March 1997
  5.  
  6.   This document will help you connect an uninterruptable power supply to
  7.   a Linux box... if you're lucky...  Copyright (c) 1994, 1995, 1996,
  8.   1997 by Harvey J. Stein.  You may use this document as you see fit, as
  9.   long as it remains intact.  In particular, this notice (along with the
  10.   contributions below) must remain untouched.
  11.  
  12.   1.  Introduction
  13.  
  14.   This HOWTO covers connecting a UPS to a computer running Linux.  The
  15.   idea is to connect the two in such a way that Linux can shutdown
  16.   cleanly when the power goes out, and before the UPS's battery gives
  17.   out.
  18.  
  19.   This includes pointing out the existence of software packages which
  20.   aid in establishing such communications, and detailing exactly how
  21.   such communications are carried out.  The latter often is unnecessary
  22.   if you can find a software package that's already been configured for
  23.   your UPS.  Otherwise, you'll have to read on.
  24.  
  25.   To a large extent this document is even more redundant than when I
  26.   originally wrote it three years ago.  All the basic information has
  27.   always been contained in the powerd man page that comes with the
  28.   SysVinit package.  Whereas three years ago one could commonly find
  29.   Linux distributions which didn't even include this man page, I don't
  30.   believe this is the case any longer.
  31.  
  32.   Furthermore, when I first wrote this Howto, there was no software
  33.   other than powerd.c for Linux/UPS communications and control.  Today
  34.   there are quite afew UPS control packages available in Sunsite's UPS
  35.   directory <http://sunsite.unc.edu:/pub/Linux/system/ups>.
  36.  
  37.   None the less, spurred on by RedHat's imminent reprinting of Dr.
  38.   Linux, I'm updating the UPS Howto.  Why bother?  Well,
  39.  
  40.   ╖  An additional general overview might help to understand how to
  41.      connect a Linux system to a UPS, even if it's just the same
  42.      information written differently.
  43.  
  44.   ╖  The HOWTO is serving as a repository for UPS specific data - there
  45.      are many UPSs that haven't yet been incorporated into the general
  46.      packages.
  47.  
  48.   ╖  The HOWTO contains additional details that aren't available in
  49.      other documents.
  50.  
  51.   ╖  Some of the UPS software packages available in Sunsite's UPS
  52.      directory <http://sunsite.unc.edu:/pub/Linux/system/ups> seem to be
  53.      quite sparsely documented.  You might need to read this before you
  54.      can understand how to use them.
  55.  
  56.   ╖  This thing seems to have a life of it's own now.  It's clear when a
  57.      Howto should be born.  It's less clear when it should be put to
  58.      sleep.
  59.  
  60.   1.1.  Contributors
  61.  
  62.   I am forever indebted to those from whom I've received help,
  63.   suggestions, and UPS specific data.  The list includes:
  64.  
  65.   ╖  Hennus Bergman (hennus@sky.owl.nl)
  66.  
  67.   ╖  Charli (mefistos@impsat1.com.ar)
  68.  
  69.   ╖  Ciro Cattuto (Ciro Cattuto)
  70.  
  71.   ╖  Nick Christenson (npc@minotaur.jpl.nasa.gov)
  72.  
  73.   ╖  Lam Dang (angit@netcom.com)
  74.  
  75.   ╖  Markus Eiden (Markus@eiden.de)
  76.  
  77.   ╖  Dan Fandrich (dan@fch.wimsey.bc.ca)
  78.  
  79.   ╖  Ben Galliart (bgallia@orion.it.luc.edu)
  80.  
  81.   ╖  Danny ter Haar (dth@cistron.nl)
  82.  
  83.   ╖  Christian G. Holtje (docwhat@uiuc.edu)
  84.  
  85.   ╖  Raymond A. Ingles (inglesra@frc.com)
  86.  
  87.   ╖  Peter Kammer (pkammer@ics.uci.edu)
  88.  
  89.   ╖  Marek Michalkiewicz (ind43@sun1000.ci.pwr.wroc.pl)
  90.  
  91.   ╖  Jim Ockers (ockers@umr.edu)
  92.  
  93.   ╖  Evgeny Stambulchik (fnevgeny@plasma-gate.weizmann.ac.il)
  94.  
  95.   ╖  Clive A. Stubbings (cas@vjet.demon.co.uk)
  96.  
  97.   ╖  Miquel van Smoorenburg (miquels@cistron.nl)
  98.  
  99.   ╖  Slavik Terletsky (ts@polynet.lviv.ua)
  100.  
  101.   ╖  Tom Webster (webster@kaiwan.com)
  102.  
  103.   Note that email addresses appearing below as excerpts from email
  104.   messages can be out of date.  The above is probably out of date too,
  105.   but some of it's more recent than what's below.
  106.  
  107.   Also, many apologies to anyone whom I've failed to note in this list.
  108.   Please email me and I'll add you.
  109.  
  110.   1.2.  Important disclaimer
  111.  
  112.   I really can't guarantee that any of this will work for you.
  113.   Connecting a UPS to a computer can be a tricky business.  One or the
  114.   other or both might burn out, blow up, catch fire, or start World War
  115.   Three.  Furthermore, I only have direct experience with the Advice
  116.   1200 A UPS, and a 5kva Best Ferrups, and I didn't have to make a
  117.   cable.  So, BE CAREFUL. GATHER ALL INFORMATION YOU CAN ON YOUR UPS.
  118.   THINK FIRST.  DON'T IMPLICITLY TRUST ANYTHING YOU READ HERE OR
  119.   ANYWHERE ELSE.
  120.  
  121.   On the other hand, I managed to get everything working with my UPSs,
  122.   without much information from the manufacturer, and without blowing
  123.   anything up, so it is possible.
  124.  
  125.   1.3.  Other documents
  126.  
  127.   This document does not cover the general features and capabilities of
  128.   UPSs.  For that type of information, you might turn to The UPS FAQ
  129.   <ftp://navigator.jpl.nasa.gov/pub/doc/faq/UPS.faq>.  It can also be
  130.   found at ftp://rtfm.mit.edu/pub/usenet-by-hierarchy/comp/answers/UPS-
  131.   faq.  It is maintained by Nick Christenson
  132.   (npc@minotaur.jpl.nasa.gov), but seems to have last been updated in
  133.   1995.  In email to him, he'd like that you put UPS or UPS FAQ or
  134.   something along these lines in the Subject line of the message.
  135.  
  136.   There're also more and more UPS manufactures sprouting up on the net.
  137.   Some of them actually supply useful information on their web sites.  A
  138.   convenient list of UPS manufacturers' web sites is available at The
  139.   UPS Directory <http://www.upssystems.uk.com/upsdir.html>.  Said site
  140.   also has a UPS FAQ <http://www.upssystems.uk.com/upsfaqs.html>.
  141.  
  142.   2.  Important note on obsolete information
  143.  
  144.   I've just discovered that some of the documentation below is obsolete.
  145.   In particular, the init daemon that comes with the latest sysvinit
  146.   package
  147.   <http://sunsite.unc.edu/pub/Linux/system/daemons/init/sysvinit-2.64.tar.gz>
  148.   is more sophisticated than I've portrayed it to be.  Although it seems
  149.   that the current version is backward compatible with what's written
  150.   here, it looks like it has some undocumented features which are very
  151.   important for UPS support.
  152.  
  153.   The control mechanism outlined below only allows powerd to give init
  154.   one of two messages, namely powerfail or powerok.  init runs one
  155.   command when it receives powerfail, and another when it receives
  156.   powerok.  This leads to complicated powerd logic for dealing with low
  157.   battery signals and other sorts of special situations.
  158.  
  159.   Newer versions of init (as of version 2.58, it seems) are more
  160.   sophisticated.  These versions can be signaled to run one of three
  161.   scripts.  Thus, init can have a powerfail script for announcing a
  162.   power outage, a powerfailnow script for doing an immediate shutdown,
  163.   and a powerok script for halting any pending shutdowns.  This is much
  164.   cleaner than the gyrations one would have to go through with the
  165.   mechanisms detailed below.
  166.  
  167.   Although most of the discussion here assumes the old init
  168.   communication method, I just added two new sections where the authors
  169.   uses the new communcation method.  These are sections ``Trust Energy
  170.   Protector 400/650'' and ``APC Smart-UPS 700''.  The former is
  171.   especially detailed.  Both include a powerd.c which signals init to do
  172.   an immediate shutdown when a low battery signal is received, as well
  173.   as the relevant /etc/inittab lines to make this work.  Other than
  174.   this, all I can tell you is to look at the source code for init.
  175.  
  176.   Also, for all I know, many of the software packages listed below also
  177.   use this newer communication method.
  178.  
  179.   3.  Smart and dumb UPSs.
  180.  
  181.   UPSs fall into two categories, which I'll call ``smart'' and ``dumb''.
  182.   The difference between the two is the amount of information one can
  183.   get from the UPS and the amount of control one can exert over the UPS.
  184.  
  185.      Dumb UPS
  186.  
  187.      ╖  Connects to the computer via serial port.
  188.  
  189.      ╖  Uses modem control lines to communicate with the computer.
  190.  
  191.      ╖  Can signal whether or not the power is out.
  192.  
  193.      ╖  Typically can signal whether or not the battery is low.
  194.  
  195.      ╖  The computer can usually signal the UPS to turn itself off.
  196.  
  197.      Smart UPS
  198.  
  199.      ╖  Connects to the computer via serial port.
  200.  
  201.      ╖  Communicates with the computer via normal data transfer through
  202.         the serial port.
  203.  
  204.      ╖  Typically has some sort of command language that the computer
  205.         can use to get various pieces of information from the UPS, to
  206.         set various operating parameters for the UPS, and to control the
  207.         UPS (such as turning it off).
  208.  
  209.   Usually smart UPSs can be operated in dumb mode.  This is useful
  210.   because as far as I know, the company which manufactures the most
  211.   popular smart UPS (namely APC) will only disclose the communication
  212.   protocol for their UPSs to people who sign a non-disclosure agreement.
  213.  
  214.   As far as I know, the only smart UPS available which is easy to
  215.   communicate with under Linux are those made by Best.  Furthermore,
  216.   BEST fully documents the smart mode (and the dumb mode) of their UPSs.
  217.   BEST also supplies source code for programs which can communicate with
  218.   their UPSs.
  219.  
  220.   All the packages listed in section ``Software'' will communicate with
  221.   a UPS in dumb mode.  This is all you really need.  The ones
  222.   specifically for the APC UPSs make various claims as to being usable
  223.   in smart mode, but I don't know exactly what they permit.  A full
  224.   implementation would give you a pop-up window with all sorts of fun
  225.   gauges displaying various statistics for the UPS, such as load,
  226.   internal temperature, fault history, input voltage, output voltage,
  227.   etc.  It seems like the smupsd-0.7-1.i386.rpm package (section
  228.   ``Software'') approaches this.  I'm not sure about the others.
  229.  
  230.   The rest of this document is pretty much confined to configuring your
  231.   system to work with a dumb UPS.  The general idea is about the same
  232.   with a smart UPS, but the details of how powerd would need to work and
  233.   what kind of cable you need are different for a smart UPS.
  234.  
  235.   4.  Software
  236.  
  237.   Basically, all you need is a working powerd binary, usually found in
  238.   /sbin/powerd.  This is usually part of the SysVinit package.  As far
  239.   as I know, all current Linux distributions include a recent version of
  240.   SysVinit.  Very old versions didn't include powerd.
  241.  
  242.   The only problem you might have is that your cable might not match how
  243.   powerd is set up, in which case you'll have to either rewire your
  244.   cable, or pick up a copy of powerd.c and modify it to work with your
  245.   cable.  Or, for that matter, you can always pick up one of the
  246.   following packages, most of which allow you to configure them to match
  247.   your cable.
  248.   As mentioned, an alternative to using the powerd that comes with the
  249.   SysVinit package would be to use one of the UPS packages now
  250.   available.  There are many packages currently available to aid in
  251.   setting up computer/ups communications.  None of this was available
  252.   when I first wrote this Howto, which is why I had to write it.  In
  253.   fact, there's a good chance that you might be able to use one of these
  254.   software packages, and avoid this Howto entirely!
  255.  
  256.   As of 15 March 1997 or so, Sunsite's UPS directory
  257.   <http://sunsite.unc.edu:/pub/Linux/system/ups> had quite a few
  258.   packages available.  Other sites seem to have UPS control packages
  259.   available too.  Here's what I've found to date (all but two from
  260.   sunsite):
  261.  
  262.      Enhanced_APC_BackUPS.tar.gz
  263.         <http://sunsite.unc.edu:/pub/Linux/system/ups/Enhanced_APC_BackUPS.tar.gz>
  264.         A package for controlling APC Smart UPSs.  Seems to basically
  265.         follow the BUPS Howto (included here), but also seems to have
  266.         some low battery warning support.
  267.  
  268.      Enhanced_APC_UPSD-v1.4.tar.gz
  269.         <http://sunsite.unc.edu:/pub/Linux/system/ups/Enhanced_APC_UPSD-
  270.         v1.4.tar.gz>
  271.         The .lsm file says that it's formerly the above package, but it
  272.         actually includes the above package as a .tar.gz file inside of
  273.         this tar.gz file!  The documentation is spotty.  It seems to
  274.         support APC UPSs in both smart mode and dumb mode, but I can't
  275.         be sure.
  276.  
  277.      apcd-0.5.tar.gz
  278.         <http://sunsite.unc.edu:/pub/Linux/system/ups/apcd-0.5.tar.gz>
  279.         Another package for controlling APC Smart UPSs.  Seems to
  280.         include some sort of master/slave support (i.e. - one machine
  281.         signals others to shut down when the power goes out).  Seems to
  282.         use the UPS in smart mode, as opposed to via modem signal line
  283.         toggling.
  284.  
  285.      smupsd directory <ftp://cms180.cmsnet.com/pub/smupsd/>
  286.         Yet another package for APC UPSs.  Seems to operate APC UPSs in
  287.         Very Smart(tm) mode.  For example, it includes a Java based GUI
  288.         UPS monitoring tool!  The above directory includes the software
  289.         package precompiled in RPM package format
  290.         (ftp://cms180.cmsnet.com/pub/smupsd/smupsd-0.7-1.i386.rpm), as
  291.         well as a source RPM for the package
  292.         (ftp://cms180.cmsnet.com/pub/smupsd/smupsd-0.7-1.src.rpm), and a
  293.         readme for the package
  294.         (ftp://cms180.cmsnet.com/pub/smupsd/smupsd-0.7-1.README).
  295.  
  296.      genpower-1.0.1.tgz
  297.         <http://sunsite.unc.edu:/pub/Linux/system/ups/genpower-1.0.1.tgz>
  298.         A general UPS handling package.  Includes configurations for
  299.         many UPSs - two TrippLite configurations, and three APC
  300.         configurations.  Includes good documentation.  A best buy.
  301.  
  302.      powerd-2.0.tar.gz
  303.         <http://sunsite.unc.edu:/pub/Linux/system/ups/powerd-2.0.tar.gz>
  304.         A replacement for the powerd that comes with the SysVinit
  305.         package.  As opposed to comments included in the documentation
  306.         it doesn't seem to have been merged into the SysVinit package as
  307.         of version 2.62.  Its advantages are that it can act as a server
  308.         for other powerds running on other machines (for when you have a
  309.         network of machines hanging off a single UPS), and it can be
  310.         configured by config file - the source code doesn't have to be
  311.         edited and recompiled.
  312.  
  313.      upsd-1.0.tgz
  314.         <http://sunsite.unc.edu:/pub/Linux/system/ups/upsd-1.0.tgz>
  315.         Another replacement for powerd.  Seems to be quite comparable in
  316.         features to powerd-2.0.tar.gz.
  317.  
  318.      checkups.tar
  319.         <http://www.bestpower.com/section/software/checkups.tar>
  320.         This package is for controlling Best UPSs.  It's direct from
  321.         Best's web site.  Includes binaries for lots of unix flavors,
  322.         but more importantly, it includes source code, so you can try it
  323.         out under Linux, and if it doesn't work, you can try to fix it.
  324.         The source code includes both ``basic checkups'' which controls
  325.         the UPS in dumb mode, and ``advanced checkups'' which is a
  326.         little more sophisticated - it will signal a shutdown when the
  327.         UPS says it has X minutes of power remaining instead of just
  328.         shutting down X minutes after the power goes out.  The advanced
  329.         checkups program also will shut down when the UPS registers
  330.         various alarms such as High Ambient Temperature, Near Low
  331.         Battery, Low AC Out, or User Test Alarm.
  332.  
  333.      bestups-0.9.tar.gz
  334.         <http://sunsite.unc.edu:/pub/Linux/system/ups/bestups-0.9.tar.gz>
  335.         A package that might very well be on sunsite by the time you
  336.         read this.  It's a pair of communications module which works
  337.         with Best Ferrups UPSs.  It operates the UPS in smart mode.  It
  338.         inter-operates well with powerd-2.0 - useful if you have a big
  339.         Best Ferrups UPS keeping up all the machines on a network.
  340.  
  341.   Note that I've only glanced at these packages.  I haven't used them,
  342.   except that we've just started using bestups-0.9.tar.gz
  343.   <http://sunsite.unc.edu:/pub/Linux/system/ups/bestups-0.9.tar.gz> in
  344.   conjunction with powerd-2.0.tar.gz
  345.   <http://sunsite.unc.edu:/pub/Linux/system/ups/powerd-2.0.tar.gz>,
  346.   where ``just started'' means we began testing last Thursday.
  347.  
  348.   5.  Do it yourself guide
  349.  
  350.   This discussion is specifically tailored for dumb UPS control.
  351.   However, most of the process is about the same for dumb UPSs and smart
  352.   UPSs.  The biggest difference is in the details of how the UPS
  353.   monitoring daemon (typically powerd) communicates with the UPS.
  354.  
  355.   Before doing anything, I suggest the following algorithm:
  356.  
  357.   ╖  Skim this document.
  358.  
  359.   ╖  Download and investigate all packages which seem specifically
  360.      tailored to your UPS.
  361.  
  362.   ╖  Download and investigate the more generic packages.  Note that some
  363.      of the more generic packages are actually more powerful, better
  364.      documented, and easier to use than their more specific
  365.      counterparts.
  366.  
  367.   ╖  If you still can't get things working, or if points are still
  368.      unclear, read this document more carefully, and hack away...
  369.  
  370.   5.1.  What you need to do (summary)
  371.  
  372.   ╖  Plug the computer into the UPS.
  373.  
  374.   ╖  Connect the computer's serial port to the UPS with a special cable.
  375.  
  376.   ╖  Run powerd (or some sort of equivalent) on the computer.
  377.  
  378.   ╖  Setup your init to do something reasonable on powerfail and powerok
  379.      events (like start a shutdown and kill any currently running
  380.      shutdowns, respectively, for example).
  381.  
  382.   5.2.  How it's supposed to work
  383.  
  384.      UPS's job
  385.         When the power goes out, the UPS continues to power the computer
  386.         and signals that the power went out by throwing a relay or
  387.         turning on an opticoupler on it's control port.
  388.  
  389.      Cable's job
  390.         The cable is designed so that when the UPS throws said relay,
  391.         this causes a particular serial port control line (typically
  392.         DCD) to go high.
  393.  
  394.      Powerd's job
  395.         The powerd daemon monitors the serial port.  Keeps
  396.         raised/lowered whatever serial port control lines the UPS needs
  397.         to have raised/lowered (typically, DTR must be kept high and
  398.         whatever line shuts off the UPS must be kept low).  When powerd
  399.         sees the UPS control line go high, it writes FAIL to
  400.         /etc/powerfail and sends the init process a SIGPWR signal.  When
  401.         the control line goes low again, it writes OK to /etc/powerfail
  402.         and sends init a SIGPWR signal.
  403.  
  404.      Init's job (aside from everything else it does)
  405.         When it receives a SIGPWR, it looks at /etc/powerfail.  If it
  406.         contains FAIL it runs the powerfail entry from /etc/inittab.  If
  407.         it contains OK it runs the powerokwait entry from inittab.
  408.  
  409.   5.3.  How to set things up
  410.  
  411.   The following presupposes that you have a cable that works properly
  412.   with powerd.  If you're not sure that your cable works (or how it
  413.   works), see section ``Reverse-engineering cables and hacking
  414.   powerd.c'' for information on dealing with poorly described cables and
  415.   reconfiguring powerd.c.  Sections ``Serial port pin assignments'' and
  416.   ``Ioctl to RS232 correspondence'' will also be useful.
  417.  
  418.   If you need to make a cable, see section ``How to make a cable'' for
  419.   the overall details, and the subsection of section ``Info on selected
  420.   UPSs'' that refers to your UPS.  The latter might also include
  421.   information on manufacturer supplied cables.  You may want to at least
  422.   skim all of section ``Info on selected UPSs'' because each section has
  423.   a few additional generally helpful details.
  424.  
  425.   ╖  Edit /etc/inittab.  Put in something like this:
  426.  
  427.      # What to do when power fails (Halt system & drain battery :):
  428.      pf::powerfail:/etc/powerfailscript +5
  429.  
  430.      # If power is back before shutdown, cancel the running shutdown.
  431.      pg:0123456:powerokwait:/etc/powerokscript
  432.  
  433.   ╖  Write scripts /etc/powerfailscript and /etc/powerokscript to
  434.      shutdown in 5 minutes (or whatever's appropriate) and kill any
  435.      existing shutdown, respectively.  Depending on the version of
  436.      shutdown that you're using, this will be either so trivial that
  437.      you'll dispense with the scripts, or be a 1 line bash script,
  438.      something along the lines of:
  439.  
  440.          kill `ps -aux | grep "shutdown" | grep -v grep | awk '{print $2}'`
  441.  
  442.   and you'll keep the scripts.  (In case it doesn't come out right, the
  443.   first single quote on the above line is a backquote, the second and
  444.   third are single quotes, and the last is also a backquote.)
  445.  
  446.   ╖  Tell init to re-process the inittab file with the command:
  447.  
  448.          telinit q
  449.  
  450.   ╖  Edit rc.local so that powerd gets run upon startup.  The syntax is:
  451.  
  452.          powerd <line>
  453.  
  454.   Replace <line> with the serial port that the modem is connected, such
  455.   as /dev/cua1.
  456.  
  457.   ╖  Connect computer's serial port to UPS's serial port.  DO NOT PLUG
  458.      THE COMPUTER INTO UPS YET.
  459.  
  460.   ╖  Plug a light into the UPS.
  461.  
  462.   ╖  Turn on the UPS and the light.
  463.  
  464.   ╖  Run powerd.
  465.  
  466.   ╖  Test the setup:
  467.  
  468.   ╖  Yank the UPS's plug.
  469.  
  470.   ╖  Check that the light stays on.
  471.  
  472.   ╖  Check that /etc/powerfailscript runs.
  473.  
  474.   ╖  Check that shutdown is running.
  475.  
  476.   ╖  Plug the UPS back in.
  477.  
  478.   ╖  Check that the light stays on.
  479.  
  480.   ╖  Check that /etc/powerokscript runs.
  481.  
  482.   ╖  Check that /etc/powerfailscript is not running.
  483.  
  484.   ╖  Check that shutdown is no longer running.
  485.  
  486.   ╖  Yank the UPS's plug again.  Leave it out and make sure that the
  487.      computer shuts down properly in the proper amount of time.
  488.  
  489.   ╖  The Dangerous Part. After everything seems to be proper, power down
  490.      the computer and plug it into the UPS.  Run a script that sync's
  491.      the hard disk every second or so.  Simultaneously run a second
  492.      script that keeps doing a find over your entire hard disk.  The
  493.      first is to make this a little safer and the second is to help draw
  494.      lots of power.  Now, pull the plug on the UPS, check again that
  495.      shutdown is running and wait.  Make sure that the computer shuts
  496.      down cleanly before the battery on the UPS gives out.  This is
  497.      dangerous because if the power goes out before the computer shuts
  498.      down, you can end up with a corrupt file system, and maybe even
  499.      lose all your files.  You'll probably want to do a full backup
  500.      before this test, and set the shutdown time extremely short to
  501.      begin with.
  502.  
  503.   Congratulations!  You now have a Linux computer that's protected by a
  504.   UPS and will shutdown cleanly when the power goes out!
  505.  
  506.   5.4.  User Enhancements
  507.  
  508.   ╖  Hack powerd.c to monitor the line indicating that the batteries are
  509.      low.  When the batteries get low, do an immediate shutdown.
  510.  
  511.   ╖  Modify the shutdown procedure so that if it's shutting down in a
  512.      powerfail situation, then it turns off the UPS after doing
  513.      everything necessary.
  514.  
  515.   6.  Hardware notes
  516.  
  517.   6.1.  How to make a cable
  518.  
  519.   This section is just from messages I've seen on the net.  I haven't
  520.   done it so I can't write from experience.  If anyone has, please write
  521.   this section for me :).  See also the message about the GPS1000
  522.   contained in section ``GPS1000 from ACCODATA'', not to mention all the
  523.   UPS specific data in section ``Info on selected UPSs''.
  524.  
  525.      >From miquels@caution.cistron.nl.mugnet.org Wed Jul 21 14:26:33 1993
  526.      Newsgroups: comp.os.linux
  527.      Subject: Re: UPS interface for Linux?
  528.      From: miquels@caution.cistron.nl.mugnet.org (Miquel van Smoorenburg)
  529.      Date: Sat, 17 Jul 93 18:03:37
  530.      Distribution: world
  531.      Organization: Cistron Electronics.
  532.  
  533.      In article <1993Jul15.184450.5193@excaliber.uucp>
  534.      joel@rac1.wam.umd.edu (Joel M. Hoffman) writes:
  535.      >I'm in the process of buying a UPS (Uninteruptable Power Supply), and
  536.      >notice that some of them have interfaces for LAN's to signal the LAN
  537.      >when the power fails.
  538.      >
  539.      >Is there such an interface for Linux?
  540.      >
  541.      >Thanks.
  542.      >
  543.      >-Joel
  544.      >(joel@wam.umd.edu)
  545.      >
  546.  
  547.      When I worked on the last versioon of SysVinit (Now version 2.4),
  548.      I temporarily had a UPS on my computer, so I added support for it.
  549.      You might have seen that in the latest <signal.h> header files there
  550.      is a #define SIGPWR 30 now :-). Anyway, I did not have such a special
  551.      interface but the output of most UPS's is just a relais that makes or breaks
  552.      on power interrupt. I thought up a simple way to connect this to the
  553.      DCD line of the serial port. In the SysVinit package there is a daemon
  554.      called 'powerd' that keeps an eye on that serial line and sends SIGPWR
  555.      to init when the status changes, so that init can do something (such as
  556.      bringing the system down within 5 minutes). How to connect the UPS to
  557.      the serial line is described in the source "powerd.c", but I will
  558.      draw it here for explanation:
  559.  
  560.                           +------------------------o  DTR
  561.                           |
  562.                         +---+
  563.                         |   | resistor
  564.                         |   | 10 kilo-Ohm
  565.                         |   |
  566.                         +---+                                To serial port.
  567.                           |
  568.             +-----o-------+------------------------o  DCD
  569.             |             |
  570.             o  UPS        |
  571.           \    relais     |
  572.            \              |
  573.             |             |
  574.             +-----o-------+------------------------o  GND
  575.  
  576.      Nice drawing eh?
  577.  
  578.      Hope this helps.
  579.      SysVinit can be found on sunsite (and tsx-11 probably) as
  580.      SysVinit2.4.tar.z
  581.  
  582.      Mike.
  583.  
  584.      --
  585.  
  586.      Miquel van Smoorenburg, <miquels@cistron.nl.mugnet.org>
  587.      Ibmio.com: cannot open CONFIG.SYS: file handle broke off.
  588.  
  589.      >From danny@caution.cistron.nl.mugnet.org Wed Jul 21 14:27:04 1993
  590.      Newsgroups: comp.os.linux
  591.      Subject: Re: UPS interface for Linux?
  592.      From: danny@caution.cistron.nl.mugnet.org (Danny ter Haar)
  593.      Date: Mon, 19 Jul 93 11:02:14
  594.      Distribution: world
  595.      Organization: Cistron Electronics.
  596.  
  597.      In article <9307174330@caution.cistron.nl.mugnet.org>
  598.      miquels@caution.cistron.nl.mugnet.org (Miquel van Smoorenburg) writes:
  599.      >How to connect the UPS to the serial line is described in the source
  600.      >"powerd.c", but I will draw it here for explanation:
  601.  
  602.      The drawing wasn't really clear, please use this one in stead !
  603.      >
  604.      >                     +------------------------o  DTR
  605.      >                     |
  606.      >                   +---+
  607.      >                   |   | resistor
  608.      >                   |   | 10 kilo-Ohm
  609.      >                   |   |
  610.      >                   +---+                                To serial port.
  611.      >                     |
  612.      >       +-----o-------+------------------------o  DCD
  613.      >       |
  614.      >       o  UPS
  615.      >     \    relais
  616.      >      \
  617.      >       |
  618.      >       +-----o--------------------------------o  GND
  619.      >
  620.  
  621.      The DTR is kept high, when the UPS's power input is gone it
  622.      will close the relais . The computer is monitoring
  623.      the DCD input port to go LOW . When this happens it will start a
  624.      shutdown sequence...
  625.  
  626.      _____
  627.      Danny
  628.  
  629.      --
  630.      <=====================================================================>
  631.      Danny ter Haar  <dannyth@hacktic.nl> or <danny@cistron.nl.mugnet.org>
  632.      Robins law #103: 'a couple of lightyears can't part good friends'
  633.  
  634.   6.2.  Reverse-engineering cables and hacking powerd.c
  635.  
  636.   Try to get documentation for the cables that your UPS seller supplies.
  637.   In particular find out:
  638.  
  639.   ╖  What lines need to be kept high.
  640.  
  641.   ╖  What line(s) turn off the UPS.
  642.  
  643.   ╖  What lines the UPS toggles to indicate that:
  644.  
  645.   ╖  Power is out.
  646.  
  647.   ╖  Battery is low.
  648.  
  649.   You then need to either hack powerd.c appropriately, or use one of the
  650.   above configurable packages (see the packages genpower-1.0.1.tgz,
  651.   powerd-2.0.tar.gz, or upsd-1.0.tgz described in section ``Software'').
  652.   If you use one of the packages, follow the instructions there.  If you
  653.   want to hack powerd.c, keep reading.
  654.  
  655.   If you have trouble getting the above information, or just want to
  656.   check it (a good idea) the following program  might help.  It's a
  657.   hacked version of powerd.c.  It allows you to set the necessary port
  658.   flags from the command line and then monitors the port, displaying the
  659.   control lines every second.  I used it as ``upscheck /dev/cua1 2''
  660.   (for example) to set the 2nd bit (DTR) and to clear the other bits.
  661.   The number base 2 indicates which bits to set, so for example to set
  662.   bits 1, 2 and 3, (and clear the others) use 7.  See the code for
  663.   details.
  664.  
  665.   Here's the (untested) upscheck.c program.  It's untested because I
  666.   edited the version I originally used to make it clearer, and can't
  667.   test the new version at the moment.
  668.  
  669.   /*
  670.    * upscheck     Check how UPS & computer communicate.
  671.    *
  672.    * Usage:       upscheck <device> <bits to set>
  673.    *              For example, upscheck /dev/cua4 4 to set bit 3 &
  674.    *              monitor /dev/cua4.
  675.    *
  676.    * Author:      Harvey J. Stein <hjstein@math.huji.ac.il>
  677.    *              (but really just a minor modification of Miquel van
  678.    *              Smoorenburg's <miquels@drinkel.nl.mugnet.org> powerd.c
  679.    *
  680.    * Version:     1.0 19940802
  681.    *
  682.    */
  683.   #include <sys/types.h>
  684.   #include <sys/ioctl.h>
  685.   #include <fcntl.h>
  686.   #include <errno.h>
  687.   #include <stdlib.h>
  688.   #include <unistd.h>
  689.   #include <stdio.h>
  690.   #include <signal.h>
  691.  
  692.   /* Main program. */
  693.   int main(int argc, char **argv)
  694.   {
  695.     int fd;
  696.  
  697.   /*  These TIOCM_* parameters are defined in <linux/termios.h>, which  */
  698.   /*  is indirectly included here.                                      */
  699.     int dtr_bit = TIOCM_DTR;
  700.     int rts_bit = TIOCM_RTS;
  701.     int set_bits;
  702.     int flags;
  703.     int status, oldstat = -1;
  704.     int count = 0;
  705.     int pc;
  706.  
  707.     if (argc < 2) {
  708.           fprintf(stderr, "Usage: upscheck <device> <bits-to-set>\n");
  709.           exit(1);
  710.     }
  711.  
  712.     /* Open monitor device. */
  713.     if ((fd = open(argv[1], O_RDWR | O_NDELAY)) < 0) {
  714.       fprintf(stderr, "upscheck: %s: %s\n", argv[1], sys_errlist[errno]);
  715.       exit(1);}
  716.  
  717.     /* Get the bits to set from the command line. */
  718.     sscanf(argv[2], "%d", &set_bits);
  719.  
  720.     while (1) {
  721.       /* Set the command line specified bits (& only the command line */
  722.       /* specified bits).                                             */
  723.       ioctl(fd, TIOCMSET, &set_bits);
  724.       fprintf(stderr, "Setting %o.\n", set_bits);
  725.  
  726.       sleep(1);
  727.  
  728.       /* Get the current line bits */
  729.       ioctl(fd, TIOCMGET, &flags);
  730.       fprintf(stderr, "Flags are %o.\n", flags);
  731.  
  732.   /*  Fiddle here by changing TIOCM_CTS to some other TIOCM until    */
  733.   /*  this program detects that the power goes out when you yank     */
  734.   /*  the plug on the UPS.  Then you'll know how to modify powerd.c. */
  735.       if (flags & TIOCM_CTS)
  736.         {
  737.           pc = 0 ;
  738.           fprintf(stderr, "power is up.\n");
  739.         }
  740.       else
  741.         {
  742.           pc = pc + 1 ;
  743.           fprintf(stderr, "power is down.\n");
  744.         }
  745.       }
  746.  
  747.     close(fd);
  748.   }
  749.  
  750.   6.3.  Serial port pin assignments
  751.  
  752.   The previous section presupposes knowledge of the correspondence
  753.   between terminal signals and serial port pins.  Here's a reference for
  754.   that correspondence, taken from David Tal's ``Frequently Used Cables
  755.   and Connectors'' document.  I'm including a diagram illustrating the
  756.   connectors, and a table listing the correspondence between pin numbers
  757.   and terminal line signals.
  758.  
  759.   If you need a general reference for cable wiring, connectors, etc,
  760.   then David Tal's would be a good one, but I can't seem to locate this
  761.   document on the net any more.  But I've found a good replacement.
  762.   It's The Hardware Book <http://www.blackdown.org/~hwb/hwb.html>.
  763.  
  764.   Other useful sites:
  765.  
  766.   ╖  Yost Serial Device Wiring Standard
  767.      <http://star.sols.pt/docs/yost.html> which contains interesting
  768.      information on how to use RJ-45 jacks and eight wire cables for all
  769.      serial port connections.
  770.  
  771.   ╖  Stokely Consulting <http://www.stokely.com/stokely> for general
  772.      Unix info, and in particular their Unix Serial Port Resources.
  773.  
  774.   ╖  Unix Workstation System Administration Education Certification
  775.      <http://www.uwsg.indiana.edu/usail/edcert/> which contains RS-232:
  776.      Connectors and Cabling
  777.      <http://www.uwsg.indiana.edu/usail/peripherals/serial/rs232/>
  778.  
  779.   Incidentally, it seems that the Linuxdoc-sgml package still doesn't
  780.   format tables very well in the html output.  If you want to be able to
  781.   read the following table, you're probably going to have to look at
  782.   either the DVI version or the plain text version of this document.
  783.  
  784.   |       |        |        |       |         |          |                                |
  785.   |DB-25  |  DB-9  |  Name  |  EIA  |  CCITT  |  DTE-DCE |  Description                   |
  786.   |Pin #  |  Pin # |        |       |         |          |                                |
  787.   |________|_________|_________|________|__________|___________|_______________                  |
  788.   |1      |        |  FG    |  AA   |  101    |  ---     | Frame Ground/Chassis GND       |
  789.   |2      |  3     |  TD    |  BA   |  103    |  --->    | Transmitted Data, TxD          |
  790.   |3      |  2     |  RD    |  BB   |  104    |  <---    |  Received Data, RxD            |
  791.   |4      |  7     |  RTS   |  CA   |  105    |  --->    | Request To Send                |
  792.   |5      |  8     |  CTS   |  CB   |  106    |  <---    |  Clear To Send                 |
  793.   |6      |  6     |  DSR   |  CC   |  107    |  <---    |  Data Set Ready                |
  794.   |7      |  5     |  SG    |  AB   |  102    |  ----    | Signal Ground, GND             |
  795.   |8      |  1     |  DCD   |  CF   |  109    |  <---    |  Data Carrier Detect           |
  796.   |9      |        |  --    |  --   |  -      |  -       | Positive DC test voltage       |
  797.   |10     |        |  --    |  --   |  -      |  -       | Negative DC test voltage       |
  798.   |11     |        |  QM    |  --   |  -      |  <---    |  Equalizer mode                |
  799.   |12     |        |  SDCD  |  SCF  |  122    |  <---    |  Secondary Data Carrier Detect |
  800.   |13     |        |  SCTS  |  SCB  |  121    |  <---    |  Secondary Clear To Send       |
  801.   |14     |        |  STD   |  SBA  |  118    |  --->    | Secondary Transmitted Data     |
  802.   |15     |        |  TC    |  DB   |  114    |  <---    |  Transmitter (signal) Clock    |
  803.   |16     |        |  SRD   |  SBB  |  119    |  <---    |  Secondary Receiver Clock      |
  804.   |17     |        |  RC    |  DD   |  115    |  --->    | Receiver (signal) Clock        |
  805.   |18     |        |  DCR   |  --   |  -      |  <---    |  Divided Clock Receiver        |
  806.   |19     |        |  SRTS  |  SCA  |  120    |  --->    | Secondary Request To Send      |
  807.   |20     |  4     |  DTR   |  CD   |  108.2  |  --->    | Data Terminal Ready            |
  808.   |21     |        |  SQ    |  CG   |  110    |  <---    |  Signal Quality Detect         |
  809.   |22     |  9     |  RI    |  CE   |  125    |  <---    |  Ring Indicator                |
  810.   |23     |        |  --    |  CH   |  111    |  --->    | Data rate selector             |
  811.   |24     |        |  --    |  CI   |  112    |  <---    |  Data rate selector            |
  812.   |25     |        |  TC    |  DA   |  113    |  <---    |  Transmitted Clock             |
  813.  
  814.       Pin Assignment for the Serial Port (RS-232C), 25-pin and 9-pin
  815.           1                         13         1         5
  816.         _______________________________      _______________
  817.         \  . . . . . . . . . . . . .  /      \  . . . . .  /    RS232-connectors
  818.          \  . . . . . . . . . . . .  /        \  . . . .  /     seen from outside
  819.           ---------------------------          -----------      of computer.
  820.           14                      25            6       9
  821.  
  822.      DTE : Data Terminal Equipment (i.e. computer)
  823.      DCE : Data Communications Equipment (i.e. modem)
  824.      RxD : Data received; 1 is transmitted "low", 0 as "high"
  825.      TxD : Data sent; 1 is transmitted "low", 0 as "high"
  826.      DTR : DTE announces that it is powered up and ready to communicate
  827.      DSR : DCE announces that it is ready to communicate; low=modem hangup
  828.      RTS : DTE asks DCE for permission to send data
  829.      CTS : DCE agrees on RTS
  830.      RI  : DCE signals the DTE that an establishment of a connection is attempted
  831.      DCD : DCE announces that a connection is established
  832.  
  833.   6.4.  Ioctl to RS232 correspondence
  834.  
  835.   Since you also might need to modify powerd.c to raise and lower the
  836.   correct lines, you might also need the numeric values of different
  837.   terminal signals.  The can be found in /usr/include/linux/termios.h,
  838.   but are reproduced here for reference.  Since they could change,
  839.   you're best off confirming these values against said file.
  840.  
  841.   /* modem lines */
  842.   #define TIOCM_LE        0x001
  843.   #define TIOCM_DTR       0x002
  844.   #define TIOCM_RTS       0x004
  845.   #define TIOCM_ST        0x008
  846.   #define TIOCM_SR        0x010
  847.   #define TIOCM_CTS       0x020
  848.   #define TIOCM_CAR       0x040
  849.   #define TIOCM_RNG       0x080
  850.   #define TIOCM_DSR       0x100
  851.   #define TIOCM_CD        TIOCM_CAR
  852.   #define TIOCM_RI        TIOCM_RNG
  853.  
  854.   Note that the 3rd column is in Hex.
  855.  
  856.   7.  What to do when you're really stuck
  857.  
  858.   Here's a novel solution to UPS control for when the UPS and the
  859.   computer just aren't on speaking terms.  I must say that every time I
  860.   read this, I'm struck by how clever a solution it is.
  861.  
  862.   From: " Raymond A. Ingles" <inglesra@frc.com>
  863.   To: hjstein@math.huji.ac.il
  864.   Subject: UPS HOWTO tip
  865.   Date: Mon, 24 Feb 1997 11:48:32 -0500 (EST)
  866.  
  867.    I don't know if others would find this useful, but I thought I might
  868.   pass this along for possible inclusion in the HOWTO. Thanks for
  869.   maintaining a HOWTO that I found very useful!
  870.  
  871.   -----------------
  872.  
  873.    My fiancee bought me a UPS as a present, a Tripp-Lite 400, I believe. It
  874.   was very welcome and seems to operate as expected, but unfortunately
  875.   doesn't have a serial interface to let the computer know the line power
  876.   has failed. It's apparently intended for home or office use where the
  877.   computer will not be left unattended.
  878.  
  879.    This, of course, was unacceptable and I began working on a line monitor,
  880.   planning on opening up the case and figuring out how to add the hardware
  881.   that the manufacturer had left out. Then I realized that there was a
  882.   quicker and simpler and cheaper (if somewhat less functional) way.
  883.  
  884.    I had an old 2400 baud modem that I wasn't using, and hooked it up to an
  885.   unused serial port on my computer. I then plugged the modem into a surge
  886.   supressor plugged into the wall power. I set up powerd with the options
  887.   as follows:
  888.  
  889.   -----
  890.   serialline    /dev/ttyS1
  891.   monitor     DCD
  892.   failwhen    low
  893.   -----
  894.  
  895.    Now, when the wall power fails (or, since that hasn't happened lately,
  896.   when I pull the surge supressor from the wall to test this setup) the modem
  897.   fails but the UPS starts supplying power to the computer. When powerd
  898.   notices the modem has dropped DCD, it triggers the powerfail sequence.
  899.  
  900.    Obviously, this has some limitations. You can't tell from the modem when
  901.   the battery is low and so on. You can only tell that the wall power has
  902.   failed. Still, it's certainly cheap and I hate to see functioning
  903.   computer equipment lie unused. These days you should be able to get a
  904.   2400 baud modem for very nearly free.
  905.  
  906.    I'd still suggest getting a real UPS with full communication capability.
  907.   But if you're stuck with a less-functional one, this may at least make it
  908.   useful.
  909.  
  910.    Sincerely,
  911.  
  912.    Ray Ingles               (810) 377-7735                inglesra@frc.com
  913.  
  914.    "Anybody who has ever seen a photograph showing the kind of damage that
  915.   a trout traveling that fast can inflict on the human skull knows that
  916.   such photographs are very valuable. I paid $20 for mine." - Dave Barry
  917.  
  918.   8.  Info on selected UPSs
  919.  
  920.   This section contains UPS specific information.  What I'd like is to
  921.   have the UPS control port information (what each pin does and needs to
  922.   have done), information on the manufacturer supplied cable (what it
  923.   connects where), and a hacked version of powerd.c which works with the
  924.   UPS.  What I currently have is fairly complete descriptions of setting
  925.   up each UPS.  I'd try to distill out the relevant information, but
  926.   since I can't test each UPS, it's hard to decide exactly what's
  927.   relevant.  Furthermore, each UPS seems to have some additional quirks
  928.   that are nicely described by the authors of each section.  So for now
  929.   I'm leaving everything in.  Makes for a hefty Howto.
  930.  
  931.   Please send me your experiences for inclusion here.
  932.  
  933.   8.1.  General Experiences.
  934.  
  935.   I've been saving peoples comments, but haven't gotten permission yet
  936.   to include them here.  Here's a general summary of what I've heard
  937.   from people.
  938.  
  939.   APC: Won't release info on their smart mode without your signature on
  940.   a non-disclosure agreement.  Thus, people are forced to run their
  941.   smart UPSs in the dumb mode as outlined above.  Various people have
  942.   had varying amounts of success reverse engineering
  943.  
  944.   Best: Helpful and friendly.  Supply source code and documentation both
  945.   for dumb modes and smart modes.
  946.  
  947.   TrippLite: One person reported that TrippLite won't release info
  948.   either.
  949.  
  950.   Upsonic: One person reported that Upsonic has discussed technical
  951.   details over the phone, answered questions via fax and are generally
  952.   helpful.
  953.  
  954.   8.2.  Advice 1200 A
  955.  
  956.   UPS from Advice Electronics, Tel Aviv Israel (they stick their own
  957.   name on the things).
  958.  
  959.   I don't recommend them.  Our experiences with them have been very bad.
  960.   We've twice had a 17" monitor fry when the power failed.  We've had
  961.   computers spontaneously reboot when the power failed.
  962.  
  963.   None the less, for completeness, here's he UPS Control Port's pin
  964.   specifications.
  965.  
  966.   ╖  2 - Power Fail.
  967.  
  968.   ╖  5 - Battery Low.
  969.  
  970.   ╖  6 - Shut Down UPS.
  971.  
  972.   ╖  4 - Common ground for pin 2, 5, 6.
  973.  
  974.   They also gave me the following picture which didn't help me, but may
  975.   help you if you want to build a cable yourself:
  976.  
  977.            2 ----------+
  978.                        |
  979.                        \
  980.                         \|
  981.                          |--------------
  982.                         /|
  983.                       \/      <--- The "\/" here indicates the type of
  984.                       |            this transister.  I forget what
  985.                       |            denotes what, but this one points
  986.                    +-----+         away from the center line.
  987.                   /  /  /
  988.  
  989.            5 ----------+
  990.                        |
  991.                        \
  992.                         \|
  993.                          |--------------
  994.                         /|
  995.                       \/
  996.                       |
  997.                       |
  998.                    +-----+
  999.                   /  /  /
  1000.  
  1001.                          +-------------
  1002.                          |
  1003.                          /
  1004.                 10K    |/
  1005.            6 --\/\/\/--|
  1006.                        |\
  1007.                          \/
  1008.                          |
  1009.                          |
  1010.                       +-----+
  1011.                      /  /  /
  1012.  
  1013.            4 ----------+
  1014.                        |
  1015.                        |
  1016.                     +-----+
  1017.                    /  /  /
  1018.  
  1019.   Cable supplied
  1020.  
  1021.   They first gave me a cable that was part of a DOS UPS control package
  1022.   called RUPS.  I used this for testing.  When I was satisfied, they
  1023.   gave me a cable they use for Netware servers connected to UPSs.  It
  1024.   functioned identically.  Here are the details:
  1025.  
  1026.   ╖  DTR - Powers cable (make powerd.c keep it high).
  1027.  
  1028.   ╖  CTS - Power out (stays high and goes low when power goes out).
  1029.  
  1030.   ╖  DSR - Battery low (stays high.  Goes low when battery does).
  1031.  
  1032.   ╖  RTS - Turns off UPS (keep it low.  Set it high to turn off UPS).
  1033.  
  1034.   (The powerd.c that comes with SysVinit set or left RTS high, causing
  1035.   the UPS to shut off immediately when powerd was started up!)
  1036.   8.3.  Trust Energy Protector 400/650
  1037.  
  1038.   This section is good for more than just the Trust Energy Protector.
  1039.   It illustrates how to work with the new features of init.
  1040.  
  1041.   How to use a Trust Energy Protector 400/650 under Linux
  1042.  
  1043.   by Ciro Cattuto <mailto:ciro@stud.unipg.it>
  1044.  
  1045.   Version 1.0 - 31 March 1997
  1046.  
  1047.   8.3.1.  The computer to UPS connection
  1048.  
  1049.   The Trust Energy Protector 400/650 is equipped with a remote signal
  1050.   port.  Using a properly designed cable, it is possible to connect the
  1051.   UPS port to the serial port of a computer, thus making it aware of
  1052.   power failure events.
  1053.  
  1054.   8.3.1.1.  The UPS signal port
  1055.  
  1056.   These are the pin assignments for the DB-9 signal port of the Trust
  1057.   Energy Protector 400/650, as described in the user's manual:
  1058.  
  1059.      pin 2
  1060.         The relay will close when input power fails.
  1061.  
  1062.      pin 4
  1063.         Common for pins 2 and 5.
  1064.  
  1065.      pin 5
  1066.         The relay will close when the battery inside the Trust Energy
  1067.         Protector 400/650 has less than 1.5 minutes of backup time left.
  1068.  
  1069.      pin 6
  1070.         The user may send a high level signal (+5V - +12V) for over 1ms
  1071.         to turn off the Trust Energy Protector 400/650. However this
  1072.         option can only be activated when the input power fails.
  1073.  
  1074.      pin 7
  1075.         Common for pin 6.
  1076.  
  1077.   8.3.1.2.  The Cable
  1078.  
  1079.   This is the cable I used to connect the UPS to the serial port of my
  1080.   computer:
  1081.  
  1082.   computer side (DB-25)               UPS side (DB-9)
  1083.   ===================================================
  1084.  
  1085.    6 DSR --+             [R] = 10 kilo-Ohm resistor
  1086.            |
  1087.   20 DTR --+----+
  1088.            |    |
  1089.           [R]  [R]                           +--- 7
  1090.            |    |                            |
  1091.    8 DCD --+----|-----------        ---------|--- 2
  1092.                 |                            |
  1093.    7 GND -------|-----------        ---------+--- 4
  1094.                 |             ....
  1095.    5 CTS -------+-----------        ------------- 5
  1096.  
  1097.    2 TX  -------------------        ------------- 6
  1098.  
  1099.   ===================================================
  1100.  
  1101.   In the case of a DB-9 serial port, the pins 6,20,8,7,5,2 are mapped to
  1102.   pins 6,4,1,5,8,3.
  1103.  
  1104.   8.3.1.3.  How the cable works
  1105.  
  1106.   The computer raises DTR and checks whether DSR is high, to ensure that
  1107.   the cable is connected to the computer. While the power is good, DCD
  1108.   and CTS are both high (because of the pull-up resistors).
  1109.  
  1110.   When the power fails, the relay between pins 2 and 4 of the UPS port
  1111.   closes, and DCD becomes low, signalling the failure condition.
  1112.  
  1113.   Similarly, when the UPS batteries are getting low, the relay between
  1114.   pins 5 and 4 closes, thus lowering CTS.
  1115.  
  1116.   During a power failure the computer is able to turn off the UPS by
  1117.   raising TX for over 1ms. This can be easily accomplished sending a
  1118.   0xFF byte to the serial port, at a low baud rate.
  1119.  
  1120.   8.3.2.  The powerd daemon
  1121.  
  1122.   To make use of the information available at the serial port we need to
  1123.   run a program which monitors the port, decodes the signals and sends
  1124.   the appropriate messages to the operating system, i.e. to the init
  1125.   process.  The init process can execute scripts and programs designed
  1126.   to handle (gracefully!) the power failure event.
  1127.  
  1128.   8.3.2.1.  Compiling powerd
  1129.  
  1130.   In Appendix A you'll find the source code of powerd, the daemon I use
  1131.   to monitor the Trust Energy Protector 400/650.  To compile it you will
  1132.   need the source code of the sysvinit package (I used the code from
  1133.   sysvinit-2.60). Just overwrite the original powerd.c and compile it.
  1134.  
  1135.   8.3.2.2.  How powerd works
  1136.  
  1137.   As soon as powerd starts it opens the serial device connected to the
  1138.   UPS and forces DTR high. It then forks a daemon and exits, leaving the
  1139.   daemon running. The powerd daemon can be in one of three states:
  1140.  
  1141.      State 0 - POWER IS GOOD
  1142.         In this state powerd reads the serial port every T0_SLEEP
  1143.         seconds (see the #define lines at the beginning of the code).
  1144.         If DCD drops, powerd switches to state 1. If CTS drops powerd
  1145.         switches to state 2 (this shouldn't happen without DCD dropping
  1146.         before, but I decided to stay on the safe side).
  1147.  
  1148.      State 1 - POWER FAILURE
  1149.         A power failure was detected. DCD is low and powerd reads the
  1150.         UPS port every T1_SLEEP seconds. If DCD becomes high, it
  1151.         switches to state 0. If CTS drops, it switches to state 2.
  1152.  
  1153.      State 2 - POWER CRITICAL
  1154.         UPS batteries are low. The powerd daemon will remain in this
  1155.         state.
  1156.  
  1157.   Each time powerd changes state, it notifies the init process, so that
  1158.   the appropriate action can be taken. These events are logged using the
  1159.   system logging facility.
  1160.  
  1161.   If DSR is low there must be something wrong with the cable.  Powerd
  1162.   keeps monitoring the DSR line, and every two minutes sends a warning
  1163.   message to the system logging facility.
  1164.  
  1165.   8.3.2.3.  Running powerd
  1166.  
  1167.   The powerd daemon should be launched from the system initialization
  1168.   scripts, during system startup. I added the following lines to my
  1169.   /etc/rc.d/rc.local script:
  1170.  
  1171.        # Add support for the UPS
  1172.        echo "Starting powerd daemon..."
  1173.        rm -f /etc/turnUPSoff
  1174.        stty -crtscts speed 75 < /dev/cua3 > /dev/null
  1175.        if [ -x /usr/sbin/powerd ]; then
  1176.                /usr/sbin/powerd /dev/cua3
  1177.        fi
  1178.  
  1179.   First we remove (if present) the file /etc/turnUPSoff.  This file is
  1180.   used by the system shutdown script (/etc/rc.d/rc.0, in my case) to
  1181.   decide whether we want to turn the UPS off.  See later in this
  1182.   document for more information.
  1183.  
  1184.   Then we disable hardware flow control on the serial device connected
  1185.   to the UPS, and set its baud rate to 75.  Now we're confident that the
  1186.   TX signal will stay high for a time long enough to turn the UPS off,
  1187.   if we send a character to the serial port (again, see later).
  1188.  
  1189.   Finally we launch the powerd daemon, specifying the serial port to
  1190.   monitor. Notice that we're not going to read characters from the
  1191.   serial device, so don't worry if you have interrupt conflicts -
  1192.   they'll do no harm.
  1193.  
  1194.   8.3.3.  The inittab file and the shutdown scripts
  1195.  
  1196.   The powerd process is now running, and it will send signals to init
  1197.   whenever a power failure occurs. Now we have to configure the system
  1198.   so that it can react in a useful way when those signals are received.
  1199.  
  1200.   8.3.3.1.  Modifying inittab
  1201.  
  1202.   Add the following lines near the beginning of your /etc/inittab file:
  1203.  
  1204.        # What to do when power fails (delayed shutdown).
  1205.        pf::powerfail:/etc/powerfail_script
  1206.  
  1207.        # If power is back before shutdown, cancel the running shutdown.
  1208.        pg::powerokwait:/etc/powerokay_script
  1209.  
  1210.        # If UPS batteries are getting low, do an immediate shutdown.
  1211.        pc::powerfailnow:/etc/powerfailnow_script
  1212.  
  1213.   8.3.3.2.  The scripts
  1214.  
  1215.   The scripts powerfail_script, powerokay_script and powerfailnow_script
  1216.   are executed when init receives the corresponding signal. They have
  1217.   the responsibility of shutting down the system in a clean way or
  1218.   cancelling a running shutdown in case power comes back.  These are the
  1219.   scripts I'm currently using:
  1220.  
  1221.   /etc/powerfail_script:
  1222.  
  1223.        #!/bin/sh
  1224.        /bin/sync
  1225.        /usr/bin/sleep 10m
  1226.        kill -9 `ps auxw | grep "shutdown" | grep -v grep | awk '{print $2}'`
  1227.        > /etc/turnUPSoff
  1228.        /sbin/shutdown -t30 -h +3 "POWER FAILURE"
  1229.  
  1230.   My Trust Energy Protector 400 powers only the computer, so I have
  1231.   quite a long backup time. Since power failures only last for some
  1232.   minutes in my zone, the system responds to a blackout in the following
  1233.   way: it waits for 10 minutes (usually the power comes back before) and
  1234.   then halts the system, allowing the users to close their applications
  1235.   and leave the machine. Before issuing the shutdown command, I make
  1236.   sure that there are no running shutdowns. I also create the file
  1237.   /etc/turnUPSoff, so that the system will turn off the UPS.
  1238.  
  1239.   /etc/powerokay_script:
  1240.  
  1241.        #!/bin/sh
  1242.        kill `ps auxw | grep "powerfail_script" | grep -v grep | awk '{print $2}'`
  1243.        kill -9 `ps auxw | grep "shutdown" | grep -v grep | awk '{print $2}'`
  1244.        rm -f /etc/turnUPSoff
  1245.  
  1246.   If power comes back, we kills the running powerfail_script and any
  1247.   running shutdown. We also remove /etc/turnUPSoff.
  1248.  
  1249.   /etc/powerfailnow_script:
  1250.  
  1251.        #!/bin/sh
  1252.        kill -9 `ps auxw | grep "shutdown" | grep -v grep | awk '{print $2}'`
  1253.        > /etc/turnUPSoff
  1254.        /sbin/shutdown -h now "UPS batteries low. IMMEDIATE SHUTDOWN."
  1255.  
  1256.   If batteries are getting low, we make sure that there are no running
  1257.   shutdowns, create the /etc/turnUPSoff file and then shutdown the
  1258.   system immediately.
  1259.  
  1260.   8.3.3.3.  The system shutdown script
  1261.  
  1262.   When system shutdown is complete, we can turn off the UPS raising the
  1263.   TX signal of the serial port for over 1ms.  The serial device is
  1264.   already properly configured (see the stty command in the rc.local
  1265.   script). If the file /etc/turnUPSoff is present, we send the byte 0xff
  1266.   (all '1' bits) to the serial port.
  1267.  
  1268.   To do this, add the following lines near the bottom of your system
  1269.   shutdown script (/etc/rc.d/rc.0, in my case).  The proper place
  1270.   depends on the way your system is configured, but it should be okay to
  1271.   insert the lines before the echo command which prints the "System is
  1272.   halted" message.
  1273.  
  1274.        # Is this a powerfail situation?
  1275.        if [ -f /etc/turnUPSoff ]; then
  1276.          echo "Turning off UPS. Bye."
  1277.          sleep 5
  1278.          echo -e "\377" > /dev/cua3
  1279.          exit 1
  1280.        fi
  1281.  
  1282.   8.3.4.  General remarks
  1283.  
  1284.   This document contains things I learned while trying to configure *my*
  1285.   Linux system to use the Trust Energy Protector 400.  Some informations
  1286.   (the path of the system inizialization scripts, for example) may be
  1287.   specific to my system, and you probably will need some customization.
  1288.   However, I hope this document will be a useful trace for those trying
  1289.   to use a Trust Energy Protector 400/650 under Linux. If you experience
  1290.   difficulties, look for general information in the rest of this UPS-
  1291.   Howto.  Good luck!
  1292.  
  1293.   8.3.4.1.  Feedback
  1294.  
  1295.   I would greatly appreciate receiving feedback about this document, so
  1296.   that I can polish it and correct possible mistakes (I know the English
  1297.   is not very good, but I'm Italian after all!).  Direct any
  1298.   comments/suggestions/critics to the following e-mail address:
  1299.  
  1300.   ciro@stud.unipg.it
  1301.  
  1302.   If you have problems using Trust Energy Protector 400/650 under Linux,
  1303.   feel free to contact me.  I'll try to help you.
  1304.  
  1305.   8.3.4.2.  Legal Issues
  1306.  
  1307.   I have no relation at all with Trust Networking Products.
  1308.  
  1309.   The information contained in this document comes "as is".  Use it at
  1310.   your own risk. I can't be held responsible for any damage or loss of
  1311.   data resulting from the use of the code and information given here.
  1312.  
  1313.   Ciro Cattuto
  1314.  
  1315.   -----
  1316.  
  1317.   8.3.5.  Appendix A  -  Source code for the powerd daemon
  1318.  
  1319.   powerd.c:
  1320.  
  1321.   /*
  1322.    * powerd       Catch power failure signals from
  1323.    *              a Trust Energy Protector 400/650
  1324.    *              and notify init
  1325.    *
  1326.    * Usage:       powerd /dev/cua3 (or any other serial device)
  1327.    *
  1328.    * Author:      Ciro Cattuto <ciro@stud.unipg.it>
  1329.    *
  1330.    * Version 1.0 - 31 March 1997
  1331.    *
  1332.    * This code is heavily based on the original powerd.c code
  1333.    * by Miquel van Smoorenburg <miquels@drinkel.ow.org>.
  1334.    *
  1335.    * This program is free software; you can redistribute it and/or
  1336.    * modify it under the terms of the GNU General Public License
  1337.    * as published by the Free Software Foundation; either version
  1338.    * 2 of the License, or (at your option) any later version.
  1339.    *
  1340.    */
  1341.  
  1342.   /* state 0 - power is good */
  1343.   #define T0_SLEEP        10      /* interval between port reads, in seconds */
  1344.   #define T0_DCD          3       /* number of seconds DCD has to be high
  1345.                                      to cause an action                      */
  1346.   #define T0_CTS          3       /* number of seconds CTS has to be high
  1347.                                      to cause an action                      */
  1348.   /* state 1 - power is failing */
  1349.   #define T1_SLEEP        2       /* interval between ports reads            */
  1350.   #define T1_DCD          3       /* same as T0_DCD                          */
  1351.   #define T1_CTS          3       /* same as T0_CTS                          */
  1352.  
  1353.   #define DSR_SLEEP       2
  1354.   #define DSR_TRIES       60
  1355.  
  1356.   /* Use the new way of communicating with init. */
  1357.   #define NEWINIT
  1358.  
  1359.   #include <sys/types.h>
  1360.   #include <sys/stat.h>
  1361.   #include <sys/ioctl.h>
  1362.   #include <fcntl.h>
  1363.   #include <errno.h>
  1364.   #include <stdlib.h>
  1365.   #include <unistd.h>
  1366.   #include <stdio.h>
  1367.   #include <signal.h>
  1368.   #include <syslog.h>
  1369.   #include <string.h>
  1370.   #include "paths.h"
  1371.   #ifdef NEWINIT
  1372.   #include "initreq.h"
  1373.   #endif
  1374.  
  1375.   #ifndef SIGPWR
  1376.   #  define SIGPWR SIGUSR1
  1377.   #endif
  1378.  
  1379.   #ifdef NEWINIT
  1380.   void alrm_handler()
  1381.   {
  1382.   }
  1383.   #endif
  1384.  
  1385.   /* Tell init that the power has gone (1), is back (0),
  1386.      or the UPS batteries are low (2). */
  1387.   void powerfail(int event)
  1388.   {
  1389.     int fd;
  1390.   #ifdef NEWINIT
  1391.     struct init_request req;
  1392.  
  1393.     /* Fill out the request struct. */
  1394.     memset(&req, 0, sizeof(req));
  1395.     req.magic = INIT_MAGIC;
  1396.     switch (event)
  1397.           {
  1398.           case 0:
  1399.                   req.cmd = INIT_CMD_POWEROK;
  1400.                   break;
  1401.           case 1:
  1402.                   req.cmd = INIT_CMD_POWERFAIL;
  1403.                   break;
  1404.           case 2:
  1405.           default:
  1406.                   req.cmd = INIT_CMD_POWERFAILNOW;
  1407.           }
  1408.  
  1409.     /* Open the fifo (with timeout) */
  1410.     signal(SIGALRM, alrm_handler);
  1411.     alarm(3);
  1412.     if ((fd = open(INIT_FIFO, O_WRONLY)) >= 0
  1413.                   && write(fd, &req, sizeof(req)) == sizeof(req)) {
  1414.           close(fd);
  1415.           return;
  1416.     }
  1417.     /* Fall through to the old method.. */
  1418.   #endif
  1419.  
  1420.     /* Create an info file for init. */
  1421.     unlink(PWRSTAT);
  1422.     if ((fd = open(PWRSTAT, O_CREAT|O_WRONLY, 0644)) >= 0) {
  1423.     switch (event)
  1424.           {
  1425.           case 0:
  1426.                   write(fd, "OK\n", 3);
  1427.                   break;
  1428.  
  1429.           case 1:
  1430.                   write(fd, "FAIL\n", 5);
  1431.                   break;
  1432.  
  1433.           case 2:
  1434.           default:
  1435.                   write(fd, "LOW\n", 4);
  1436.                   break;
  1437.           }
  1438.     close(fd);
  1439.     }
  1440.  
  1441.     kill(1, SIGPWR);
  1442.   }
  1443.  
  1444.   /* Main program. */
  1445.   int main(int argc, char *argv[])
  1446.   {
  1447.     int fd;
  1448.     int dtr_bit = TIOCM_DTR;
  1449.     int flags;
  1450.     int DCD, CTS;
  1451.     int status = -1;
  1452.     int DCD_count = 0, CTS_count = 0;
  1453.     int tries;
  1454.  
  1455.     if (argc < 2) {
  1456.           fprintf(stderr, "Usage: powerd <device>\n");
  1457.           exit(1);
  1458.     }
  1459.  
  1460.     /* Start syslog. */
  1461.     openlog("powerd", LOG_CONS|LOG_PERROR, LOG_DAEMON);
  1462.  
  1463.     /* Open monitor device. */
  1464.     if ((fd = open(argv[1], O_RDWR | O_NDELAY)) < 0) {
  1465.           syslog(LOG_ERR, "%s: %s", argv[1], sys_errlist[errno]);
  1466.           closelog();
  1467.           exit(1);
  1468.     }
  1469.  
  1470.     /* Line is opened, so DTR is high. Force it anyway to be sure. */
  1471.     ioctl(fd, TIOCMBIS, &dtr_bit);
  1472.  
  1473.     /* Daemonize. */
  1474.     switch(fork()) {
  1475.           case 0: /* Child */
  1476.                   closelog();
  1477.                   setsid();
  1478.                   break;
  1479.           case -1: /* Error */
  1480.                   syslog(LOG_ERR, "can't fork.");
  1481.                   closelog();
  1482.                   exit(1);
  1483.           default: /* Parent */
  1484.                   closelog();
  1485.                   exit(0);
  1486.     }
  1487.  
  1488.     /* Restart syslog. */
  1489.     openlog("powerd", LOG_CONS, LOG_DAEMON);
  1490.  
  1491.     /* Now sample the DCD line. */
  1492.     while(1) {
  1493.           /* Get the status. */
  1494.           ioctl(fd, TIOCMGET, &flags);
  1495.  
  1496.           /* Check the connection: DSR should be high. */
  1497.           tries = 0;
  1498.           while((flags & TIOCM_DSR) == 0) {
  1499.                   /* Keep on trying, and warn every two minutes. */
  1500.                   if ((tries % DSR_TRIES) == 0)
  1501.                       syslog(LOG_ALERT, "UPS connection error");
  1502.                   sleep(DSR_SLEEP);
  1503.                   tries++;
  1504.                   ioctl(fd, TIOCMGET, &flags);
  1505.           }
  1506.           if (tries > 0)
  1507.                   syslog(LOG_ALERT, "UPS connection OK");
  1508.  
  1509.           /* Calculate present status. */
  1510.           DCD = flags & TIOCM_CAR;
  1511.           CTS = flags & TIOCM_CTS;
  1512.  
  1513.           if (status == -1)
  1514.                   {
  1515.                   status = (DCD != 0) ? 0 : 1;
  1516.                   if (DCD == 0)
  1517.                           {
  1518.                           syslog(LOG_ALERT, "Power Failure. UPS active.");
  1519.                           powerfail(1);
  1520.                           }
  1521.                   }
  1522.  
  1523.           switch (status)
  1524.                   {
  1525.                   case 0:
  1526.                           if ((DCD != 0) && (CTS != 0))
  1527.                                   {
  1528.                                   DCD_count = 0;
  1529.                                   CTS_count = 0;
  1530.                                   sleep(T0_SLEEP);
  1531.                                   continue;
  1532.                                   }
  1533.                           if (DCD == 0)
  1534.                                   DCD_count++;
  1535.                           if (CTS == 0)
  1536.                                   CTS_count++;
  1537.                           if ((DCD_count < T0_DCD) && (CTS_count < T0_CTS))
  1538.                                   {
  1539.                                   sleep(1);
  1540.                                   continue;
  1541.                                   }
  1542.                           if (CTS_count == T0_CTS)
  1543.                                   {
  1544.                                   status = 2;
  1545.                                   syslog(LOG_ALERT, "UPS batteries low!");
  1546.                                   break;
  1547.                                   }
  1548.                           status = 1;
  1549.                           DCD_count = 0;
  1550.                           syslog(LOG_ALERT, "Power Failure. UPS active.");
  1551.                           break;
  1552.  
  1553.                   case 1:
  1554.                           if ((DCD == 0) && (CTS != 0))
  1555.                                   {
  1556.                                   DCD_count = 0;
  1557.                                   CTS_count = 0;
  1558.                                   sleep(T1_SLEEP);
  1559.                                   continue;
  1560.                                   }
  1561.                           if (DCD != 0)
  1562.                                   DCD_count++;
  1563.                           if (CTS == 0)
  1564.                                   CTS_count++;
  1565.                           if ((DCD_count < T1_DCD) && (CTS_count < T1_CTS))
  1566.                                   {
  1567.                                   sleep(1);
  1568.                                   continue;
  1569.                                   }
  1570.                           if (CTS_count == T1_CTS)
  1571.                                   {
  1572.                                   status = 2;
  1573.                                   syslog(LOG_ALERT, "UPS batteries low!");
  1574.                                   break;
  1575.                                   }
  1576.                           status = 0;
  1577.                           DCD_count = 0;
  1578.                           CTS_count = 0;
  1579.                           syslog(LOG_ALERT, "Power okay.");
  1580.                           break;
  1581.  
  1582.                   case 2:
  1583.                           sleep(1);
  1584.                           continue;
  1585.                   default:
  1586.                           break;
  1587.                   }
  1588.  
  1589.           powerfail(status);
  1590.     }
  1591.     /* Never happens */
  1592.     return(0);
  1593.   }
  1594.  
  1595.   8.4.  Sustainer S-40a
  1596.  
  1597.   Information on the Sustainer S-40a.
  1598.  
  1599.   From: fnevgeny@plasma-gate.weizmann.ac.il (Evgeny Stambulchik)
  1600.   To: hjstein@math.huji.ac.il, hjstein@math.huji.ac.il, hjstein@math.huji.ac.il,
  1601.           hjstein@math.huji.ac.il
  1602.   Subject: UPS-HowTo add-ons
  1603.   Date: Sun, 10 Sep 1995 13:09:50 +0300 (IST)
  1604.  
  1605.   Hi Harvey,
  1606.  
  1607.   This is an addition to your UPS-HowTo. I'm using Sustainer S-40a UPS for a few
  1608.   months with unipower package (now it's called genpower) and home-made cable
  1609.   constructed as follows (I've sent all this stuff to Tom Webster, author of the
  1610.   package, too, and it should appear in the next version):
  1611.  
  1612.            UPS SIDE                                   LINUX SIDE
  1613.  
  1614.                  2 POWER FAIL                             1(8)
  1615.      +-----------o-------------------------+----------------o  DCD
  1616.      |                                     |
  1617.      o                                     |
  1618.       /                                    |
  1619.      /                                     |
  1620.      |           4 COMMON                  |              5(7)
  1621.      +-----------o------+------------------|----------------o  GND
  1622.      |                  |                  |
  1623.      \                  |                  |
  1624.       \                 |                  |
  1625.      o                  |                  |
  1626.      |           5 BATT | LOW              |              8(5)
  1627.      +-----------o------|------------------|--------+-------o  CTS
  1628.                         |                  |        |
  1629.                         |                +-+-+    +-+-+
  1630.                         |                |   |    |   |
  1631.                         |    3 resistors |   |    |   |
  1632.                         |                |   |    |   |
  1633.                         |    by 10 kOhm  |   |    |   |
  1634.                         |                +-+-+    +-+-+
  1635.                         |                  |        |     4(20)
  1636.                         |                  +--------+-------o  DTR
  1637.                         |
  1638.   |              6 SHUT | DOWN              +-------+     7(4)
  1639.   +-+       +----o------|-------------------+       +-------o  RTS
  1640.     \       |           |                   +-------+
  1641.      \|    -+-          |
  1642.       | <- \ /          |
  1643.      /|    -+-          |
  1644.     /       |    7      |
  1645.     |       +----o------+
  1646.   --+--
  1647.    ---
  1648.     -
  1649.  
  1650.   NOTE!!!: Shutdown pins in the tech info supplied with UPS (4 and 6) are given
  1651.   incorrectly! The valid ones are 6 and 7, as shown above.
  1652.   Note2: Pin numbers on the PC side in the brackets are for 25-pin connector,
  1653.   outside - for 9-pin one.
  1654.  
  1655.   Here's the unipowerd.h file I used:
  1656.  
  1657.   /************************************************************************/
  1658.   /* File Name            : unipowerd.h                                   */
  1659.   /* Program Name         : unipowerd                   Version: 1.0.0    */
  1660.   /* Author               : Tom Webster <webster@kaiwan.com>              */
  1661.   /* Created              : 1994/04/20                                    */
  1662.   /* Last Modified By     : Tom Webster                 Date: 1995/04/09  */
  1663.   /* Last Modified By     : Evgeny Stambulchik (for Sustainer UPS)        */
  1664.   /*                                                                      */
  1665.   /* Compiler (created)   : GCC 2.5.8                                     */
  1666.   /* Compiler (env)       : Linux 1.0.9                                   */
  1667.   /* ANSI C Compatable    : No                                            */
  1668.   /* POSIX Compatable     : Yes?                                          */
  1669.   /*                                                                      */
  1670.   /* Purpose              : Header file for unipowerd.                    */
  1671.   /*                      : Contains the configuration information for    */
  1672.   /*                      : unipowerd.  Edit this file as indicated       */
  1673.   /*                      : below to activate features and to customize   */
  1674.   /*                      : unipowerd for your UPS.                       */
  1675.   /*                                                                      */
  1676.   /* Copyright            : GNU Copyleft                                  */
  1677.   /************************************************************************/
  1678.  
  1679.   /* The following are the RS232 control lines      */
  1680.   /*                                                */
  1681.   /*                                            D D */
  1682.   /*                                            T C */
  1683.   /* Macro           English                    E E */
  1684.   /* ---------------------------------------------- */
  1685.   /* TIOCM_DTR       DTR - Data Terminal Ready  --> */
  1686.   /* TIOCM_RTS       RTS - Ready to send        --> */
  1687.   /* TIOCM_CTS       CTS - Clear To Send        <-- */
  1688.   /* TIOCM_CAR       DCD - Data Carrier Detect  <-- */
  1689.   /* TIOCM_RNG       RI  - Ring Indicator       <-- */
  1690.   /* TIOCM_DSR       DSR - Data Signal Ready    <-- */
  1691.  
  1692.   #define HIGH            (1)
  1693.   #define LOW             0
  1694.   #define PWRSTAT         "/etc/powerstatus"
  1695.   #define UPSSTAT         "/etc/upsstatus"
  1696.  
  1697.   /* CABLEPOWER is the line which provides power to */
  1698.   /* the cable for normal monitoring activities.    */
  1699.   #define CABLEPOWER      TIOCM_DTR
  1700.  
  1701.   #define POWERBIT        TIOCM_CAR
  1702.   #define POWEROK         HIGH
  1703.  
  1704.   /* Define CABLECHECK as 1 to check for low battery */
  1705.   /* Define CABLECHECK as 0 value to skip            */
  1706.   #define CABLECHECK      0
  1707.   #define CABLEBIT        TIOCM_RNG
  1708.   #define CABLEOK         HIGH
  1709.  
  1710.   /* Define BATTCHECK as 1 to check for low battery  */
  1711.   /* Define BATTCHECK as 0 value to skip.            */
  1712.   #define BATTCHECK       1
  1713.   #define BATTBIT         TIOCM_CTS
  1714.   #define BATTOK          HIGH
  1715.  
  1716.   /* Define INVERTERKILL as 1 to hndle killing the inverter */
  1717.   /* Define INVERTERKILL as 0 value to skip.                */
  1718.   /* INVERTERBIT is the line which will kill the inverter   */
  1719.   /*    while the UPS is in powerfail mode.                 */
  1720.   /* INVERTERTIME is the time in seconds to hold the line   */
  1721.   /*    defiined by INVERTERBIT high to kill the inverter.  */
  1722.   #define INVERTERKILL    1
  1723.   #define INVERTERBIT     TIOCM_RTS
  1724.   #define INVERTERTIME    5
  1725.  
  1726.   /************************************************************************/
  1727.   /* End of File unipowerd.h                                              */
  1728.   /************************************************************************/
  1729.  
  1730.   I'm aware that current name of the package is genpower. I haven't try it yet as
  1731.   see no reason to switch to the new version meantime; the former seems to work
  1732.   very stable. Nevertheless, here is the add-on for genpower-1.0.1's genpowerd.h
  1733.   file (hopefully, I "translated" unipowerd.h correctly):
  1734.   Add-on for genpower-1.0.1's genpowerd.h file:
  1735.  
  1736.   /* Evgeny's Sustainer S-40A */
  1737.    {"sustainer",   {TIOCM_DTR,0}, {TIOCM_RTS,1},  5, {TIOCM_CAR,0}, {TIOCM_CTS,0},
  1738.   {0,0}}
  1739.  
  1740.   Evgeny
  1741.  
  1742.   8.5.  Systel
  1743.  
  1744.   Another Israeli company.  I never ended up purchasing a UPS from them,
  1745.   but they were very good about getting me detailed documentation on
  1746.   their communication port.  It should be easy enough to control their
  1747.   UPS.  Their phone number is 972-8-409-019 (972-8-407-216 for fax).
  1748.  
  1749.   8.6.  Deltec Power, Fiskars Power Systems and Exide.
  1750.  
  1751.   Fiskars <http://www.fiskars.fi/> is a Finnish holding company.  They
  1752.   used to own Deltec Power <http://www.deltecpower.com>.  In March of
  1753.   1996 Fiskars sold Deltec Power to Exide Electronics Group
  1754.   <http://www.exide.com/exide>.  At that time, Deltec Power was one of
  1755.   the world's largest makers of UPSs.
  1756.  
  1757.   Under Fiskars, Deltec used to make the PowerServers 10, 20, 30, and
  1758.   40.  The Deltec Power home page mentions other UPSs.  I don't know if
  1759.   they're just renames of the above.
  1760.  
  1761.   The good news is that Timo Kettunen sent me information on how to
  1762.   interface to these UPSs.
  1763.  
  1764.   The bad news is that he asked that I not include the info.
  1765.  
  1766.   The good news is that they don't want the information made public
  1767.   because they're going to have a commercial offering for Linux.
  1768.  
  1769.   The bad news is that you can't interface to their UPSs until they come
  1770.   out with their commercial product.
  1771.  
  1772.   In any case, it seems like it's the usual control line deal.  Maybe
  1773.   someone else has one of these and can reverse engineer the details (or
  1774.   convince someone there to talk).
  1775.  
  1776.   As an aside, I emailed Deltec Power and Exide asking them about Linux
  1777.   support.  Deltec responded within a couple of days.  They had this to
  1778.   say:
  1779.  
  1780.   From: Tony Tartol <ttartol@smtplink.deltecpower.com>
  1781.   To: abel@netvision.net.il
  1782.   Subject:  Linux support. -Reply
  1783.   Date: Fri, 28 Mar 1997 08:54:16 -0800
  1784.  
  1785.   There are documents that come with Linux describing how to
  1786.   make your own cable, but we do not recommend or support
  1787.   this.  We have developed a shutdown and monitoring package
  1788.   called LanSafe III.  You can get a data sheet from our web
  1789.   page.  The version of LanSafe III that will support Linux will be
  1790.   available in May.
  1791.  
  1792.   >>> Harvey J. Stein <abel@netvision.net.il> 03/27/97
  1793.   12:32pm >>>
  1794.  
  1795.   Do you have any software or documentation for connecting
  1796.   PCs running
  1797.   Linux to your UPSs?
  1798.  
  1799.   Thanks,
  1800.  
  1801.   --  Dr. Harvey J. Stein
  1802.   Author of the Linux UPS Howto
  1803.   Berger Financial Research abel@netvision.net.il
  1804.  
  1805.   8.7.  Beaver model UB500 UPS
  1806.  
  1807.   dan@fch.wimsey.bc.ca (Dan Fandrich) writes:
  1808.  
  1809.   I seem to have gotten my old Beaver model UB500 UPS working with
  1810.   genpower.  The interface uses RS-232 compatible voltage levels, so
  1811.   installing it is a snap.  There is a DE-9 female connector on the back
  1812.   which plugs directly into a 9-pin PC serial port using a plain 9-pin
  1813.   video monitor extension cable.
  1814.  
  1815.   The DIP switches allow quite versatile pinouts.  To emulate genpower's
  1816.   apc1-nt type of UPS, they must be set as follows:
  1817.  
  1818.            |   |       |                       |   |   |   |   |
  1819.            |1  |  on   |  (CTS = power fail)   |   |   |   |   |
  1820.            |2  |  off  |  (CTS = low battery)  |   |   |   |   |
  1821.            |3  |  off  |  (DSR = power fail)   |   |   |   |   |
  1822.            |4  |  off  |  (DSR = low battery)  |   |   |   |   |
  1823.            |5  |  off  |  (CD = power fail)    |   |   |   |   |
  1824.            |6  |  on   |  (CD = low battery)   |   |   |   |   |
  1825.            |7  |  off  |  (RI = power fail)    |   |   |   |   |
  1826.            |8  |  off  |  (RI = low battery)   |   |   |   |   |
  1827.            |9  |  on   |  (DTR = inverter off) |   |   |   |   |
  1828.            |10 |  off  |  (RTS = inverter off) |   |   |   |   |
  1829.  
  1830.                DIP switch SW601 for Beaver model UB500 UPS.
  1831.  
  1832.   The switches form groups of adjacent pairs for each output pin.  They
  1833.   are mutually exclusive--don't try to turn on both switch 5 and 6
  1834.   simultaneously, for example, or you'll be shorting the low battery and
  1835.   power fail signals.
  1836.  
  1837.   That's all there is to it.  Feel free to add this do your
  1838.   documentation.
  1839.  
  1840.   8.8.  Sendom
  1841.  
  1842.   Documentation on using the Sendom UPS.
  1843.  
  1844.        From: charli <mefistos@impsat1.com.ar>
  1845.        To: hjstein@math.huji.ac.il
  1846.        Subject: ups howto contribution
  1847.        Date: Wed, 13 Nov 1996 19:07:41 -0200
  1848.  
  1849.        hjstein@math.huji.ac.il
  1850.  
  1851.        sir:
  1852.  
  1853.        i connected a sendom ups with the help of your UPS-howto and man powerd
  1854.        and discovered something useful. perhaps this thing extends to some
  1855.        other ups.
  1856.        im using slackware 3.0 distribution. i has the soft configuration in
  1857.        /etc/inittab already done. its only needed to add the /rc.local powerd
  1858.        /cuaX
  1859.  
  1860.        i used the man powerd diagram:
  1861.                9pin    25pin
  1862.  
  1863.        DTR     4       20      ---------
  1864.                                 |      >
  1865.        DSR     6       6       --      < 10k
  1866.                                        >
  1867.        DCD     1       8       -------------------------
  1868.                                                        relais
  1869.        GND     5       7       -------------------------
  1870.  
  1871.        the fact is that the sendom ups dont use relais but some electronic
  1872.        solid state device, and it works one way BUT NO THE OTHER. so if you
  1873.        make the cable and doesnt work, first try inverting the cable in the
  1874.        ups "relais"
  1875.  
  1876.        i hope this can be useful, if you want to include this somewhere, feel
  1877.        free to correct my english. please aknowledge this mail even with an
  1878.        empty
  1879.        mail so i know it arrived
  1880.        end
  1881.  
  1882.   8.9.  Best
  1883.  
  1884.   Information on Best UPSs is available on at the Best Power
  1885.   <http://www.bestpower.com/index.html> website.  Their website includes
  1886.   the checkups.tar (section ``Software'') package for communicating with
  1887.   Best UPSs, both in smart mode and in dumb mode, and it includes source
  1888.   code, so you can compile it under Linux.
  1889.   8.9.1.  Best Fortress LI-950
  1890.  
  1891.   Some comments on the Best Fortress.
  1892.  
  1893.        From lnz@dandelion.com Wed May 31 19:53:09 1995
  1894.        Newsgroups: comp.os.linux.hardware
  1895.        Subject: Re: UPS for use with Linux?
  1896.        From: Leonard N. Zubkoff <lnz@dandelion.com>
  1897.        Date: 25 May 1995 16:27:55 -0700
  1898.        Organization: Dandelion Digital
  1899.        NNTP-Posting-Host: dandelion.com
  1900.        NNTP-Posting-User: root
  1901.        In-reply-to: nautix@community.net's message of 23 May 1995 09:41:40 -0700
  1902.  
  1903.        In article <3pt384$sic@odin.community.net> nautix@community.net writes:
  1904.  
  1905.          Ditto what Craig says.  APC was very uncooperative, but I have only
  1906.          good things to say about Best.  I use their Fortress LI 660 model;
  1907.          660 VA, lots of status features on the front, etc.  The CheckUPS
  1908.          software costs extra and needs some hacking to fit into my
  1909.          FSSTND-ish file system (the directories and file names are hard-coded
  1910.          to fit into SunOS 4.1.x).  I'd be happy to send you my diffs, if
  1911.          you want them.  (I love it when a vendor ships the source as
  1912.          a normal business practice!)
  1913.  
  1914.          The CheckUPS software is limited to doing automagic shutdowns, though.
  1915.          The UPS can give lots of status information; CheckUPS only asks for
  1916.          ``If the power has failed, how much battery time remains?''
  1917.  
  1918.          Best follows up on their customer satisfaction cards, too.
  1919.          I indicated that I was dissappointed that CheckUPS didn't do more
  1920.          status reporting (like input voltage, output voltage, percent load,
  1921.          etc.), which is available from the UPS.  I asked for a the
  1922.          spec on the interface lingo; they said ``sure'' and had it to me in
  1923.          2 days, free.  A full-featured UPS status checker is on my back burner.
  1924.          Does anyone see a demand for such a utility?
  1925.  
  1926.        Let me add yet another recommendation for Best Power.  I just purchased a
  1927.        Fortress LI-950, though I declined on the CheckUPS software.  Unlike some
  1928.        other brands, a simple three wire cable is all that's needed to connect the
  1929.        Fortress to a serial port -- no need for pull-up circuitry in the cabling.
  1930.        A few minutes hacking and I had program to act as both a shutdown monitor
  1931.        daemon, and to kill the inverter output when the system is shutdown while
  1932.        on battery power.
  1933.  
  1934.        I may eventually want to use the smarter serial communication mode rather
  1935.        than the simple contact mode, so I asked Best technical support for the
  1936.        documentation, and it arrived today, a week after I called them.  Once I
  1937.        peruse the documentation I'll decide if a smarter interface is really
  1938.        worthwhile, especially since at some point I'll need to shut down two
  1939.        networked machines sharing the UPS.
  1940.  
  1941.                        Leonard
  1942.  
  1943.   8.9.2.  Best Ferrups
  1944.  
  1945.   In addition to the doumentation and softare on Best's web site, you
  1946.   could also use the bestups-0.9.tar.gz (section ``Software'') package.
  1947.   We've just started testing it with our 5kva FERRUPS.
  1948.  
  1949.   The basic idea is that there are two modules.  One which fields
  1950.   information requests on a network port, relays those requests to the
  1951.   UPS, and returns the results.  The second module talks to the first,
  1952.   interprets the results, and responds with either OK or FAIL.
  1953.  
  1954.   This is sufficient to allow the powerd-2.0.tar.gz package (section
  1955.   ``Software'') to do the rest of the work.
  1956.  
  1957.   The details can be gotten from the bestups-0.9.tar.gz package (section
  1958.   ``Software'').
  1959.  
  1960.   Incidentally, our 5kva Ferrups has performed flawlessly in keeping our
  1961.   10 computers and 30 screens humming.
  1962.  
  1963.   8.10.  GPS1000 from ACCODATA
  1964.  
  1965.      >From hennus@sky.nl.mugnet.org Thu Mar 10 15:10:22 1994
  1966.      Newsgroups: comp.os.linux.help
  1967.      Subject: Re: auto-shutdown with UPS
  1968.      From: hennus@sky.nl.mugnet.org (Hennus Bergman)
  1969.      Date: Tue, 1 Mar 1994 22:17:45 GMT
  1970.      Distribution: world
  1971.      Organization: The Organization For Removal Of On-Screen Logos
  1972.  
  1973.      In article <CRAFFERT.94Feb28125452@nostril.lehman.com>,
  1974.      Colin Owen Rafferty <craffert@nostril.lehman.com> wrote:
  1975.      >I am about to buy an Uninterruptable Power Supply for my machine, and
  1976.      >I would like to get one that has the "auto-shutdown" feature.
  1977.      >
  1978.      I just got one of those real cheap :-)
  1979.      It's a GPS1000 by ACCODATA. Anybody know how good the output
  1980.      signal of these things is? [Don't have a scope myself :-(]
  1981.  
  1982.      >I assume that these each have some kind of serial connection that
  1983.      >tells the system information about it.
  1984.      >
  1985.      I took it apart to find out how it worked. There were three optocouplers
  1986.      (two output, one input) connected to a 9 pin connector at the back.
  1987.      One turns on when the power fails, and goes off again when the power
  1988.      returns. While the power is off, you can use the `input' to shut the
  1989.      battery off. [It releases the power-relay.] The third one is some kind
  1990.      of feedback to tell that it did accepted the `shut-down command'.
  1991.      I think the interface for my UPS was designed to be connected to TTL-level
  1992.      signals, but with some resistors it could be connected to serial port.
  1993.      It's wired in such a way that using a RS-232 port you cannot use both
  1994.      output optocouplers; but the shutdown feedback is not necessary anyway,
  1995.      just use the important one. ;-)
  1996.      [Note that it is possible to blow the transistor part in optocouplers
  1997.      with RS-232 levels if you wire it the wrong way round ;-)]
  1998.  
  1999.      I was hoping I would be able to connect it to my unused game port,
  2000.      but that doesn't have an output, does it?
  2001.      I'll probably end up getting an extra printer port for this.
  2002.  
  2003.      Not all UPS' use optocouplers, some use simple relays, which are
  2004.      less critical to connect, but of course not as `nice'.
  2005.  
  2006.      >Has anyone written a package that watches the UPS and does a shutdown
  2007.      >(or something) when the power is off?
  2008.      SysVinit-2.4 (and probably 2.5 as well) has a `powerd' daemon that
  2009.      continually watches a serial port for presence of the CD (Carrier
  2010.      Detect) line and signals init when it drops. Init then activates
  2011.      shutdown with a time delay. If the power returns within a few minutes
  2012.      the shutdown is cancelled. Very Nice.
  2013.      The only problem I had with it is that it doesn't actually tell the
  2014.      UPS to turn off when the shutdown is complete. It just sits there with
  2015.      a root prompt. I'll probably write a small program to shut it down
  2016.      >from /etc/brc. RSN.
  2017.  
  2018.      >    Colin Rafferty, Lehman Brothers <craffert@lehman.com>
  2019.  
  2020.      Hennus Bergman
  2021.  
  2022.   8.11.  TrippLite BC750LAN (Standby UPS)
  2023.  
  2024.   Tom Webster (webster@kaiwan.com, the author of the genpower package)
  2025.   sent me information on the TrippLite BC750LAN.  If you have one of
  2026.   these, your probably best off using his package.
  2027.   But, for completeness, here's his cable wiring diagram (done by trial
  2028.   and error, and without documentation):
  2029.  
  2030.                  UPS                System
  2031.                 DB-25               DB-25
  2032.                   1 <-------------->  1       Ground
  2033.  
  2034.                   2 <-------------->  4       Power Fail
  2035.                   8 <-------------->  8       Sensing Circuit
  2036.  
  2037.                   3 <-------------->  2       Inverter Shutdown
  2038.                  20 <--------------> 22       Circuit
  2039.  
  2040.   8.12.  APC
  2041.  
  2042.   If the above plethora of APC packages doesn't get you running, maybe
  2043.   the following sections will help.
  2044.  
  2045.   8.12.1.  APC Back-UPS
  2046.  
  2047.   There seems to be some controversy as to the accuracy of the
  2048.   information here on APC Back-UPSs.  So, please be careful.  I'm
  2049.   prefacing this section with one message of caution I received.  It
  2050.   might not make a lot of sense before the rest of this section is read,
  2051.   but this way, at least you're more likely to see it.  And again, since
  2052.   I don't have any APC UPS units, I can't verify the accuracy of either
  2053.   of these messages.
  2054.  
  2055.   8.12.1.1.  A message of caution
  2056.  
  2057.   From ind43@sun1000.ci.pwr.wroc.pl Sun Oct  9 11:00:42 1994
  2058.   Newsgroups: comp.os.linux.admin
  2059.   Subject: BUPS-HOWTO warning
  2060.   From: ind43@sun1000.ci.pwr.wroc.pl (Marek Michalkiewicz)
  2061.   Date: 6 Oct 1994 18:38:15 GMT
  2062.   Organization: Technical Univeristy of Wroclaw
  2063.   NNTP-Posting-Host: ci3ux.ci.pwr.wroc.pl
  2064.   X-Newsreader: TIN [version 1.2 PL2]
  2065.  
  2066.   If you want to connect the APC Back-UPS to your Linux box, this might
  2067.   be of interest to you.
  2068.  
  2069.   There is a good BUPS-HOWTO which describes how to do this. But it has
  2070.   one "bug".
  2071.  
  2072.   The RTS serial port signal is used to shut down the UPS. The UPS will
  2073.   shut down only if it operates from its battery. The manual says that
  2074.   the shutdown signal must be high for at least 0.5s. But few milliseconds
  2075.   is enough, at least for my APC Back-UPS 600.
  2076.  
  2077.   Using RTS to shut down the UPS can be dangerous, because the RTS goes
  2078.   high when the serial device is opened. The backupsd program then turns
  2079.   RTS off, but it is on (high) for a moment. This kills the power when
  2080.   backupsd is first started and there is a power failure at this time.
  2081.   This can happen for example when the UPS is shut down, unattended,
  2082.   and the power comes back for a while.
  2083.  
  2084.   Either start backupsd before mounting any filesystems for read-write,
  2085.   or (better) use TX (pin 3) instead of RTS (pin 7) to shut down the
  2086.   UPS (pin numbers are for 9-pin plug). Use ioctl(fd, TCSBRKP, 10);
  2087.   to make TX high for one second, for example. Using TX should be safe.
  2088.   Maybe I will post the diffs if time permits...
  2089.  
  2090.   -- Marek Michalkiewicz
  2091.   ind43@ci3ux.ci.pwr.wroc.pl
  2092.  
  2093.   8.12.1.2.  BUPS-HOWTO
  2094.  
  2095.   Luminated Software Group Presents
  2096.  
  2097.   HOWTO use Back-UPS (by APC) (to keep your linux box from frying)
  2098.  
  2099.   Version: 1.01  BETA
  2100.  
  2101.   Document by: Christian G. Holtje <docwhat@uiuc.edu> Cabling info and
  2102.   help: Ben Galliart <bgallia@orion.it.luc.edu>
  2103.  
  2104.   This document, under one condition, is placed in Public Domain. The
  2105.   one condition is that credit is given where credit is due.  Modify
  2106.   this as much as you want, just give some credit to us who worked.
  2107.  
  2108.   *******************************************************************************
  2109.   Warning!  I, nor any of us who have written or helped with this
  2110.   document, make and guarantees or claims for this text/source/hints.
  2111.   If anything is damaged, we take NO RESPONSIBILITY!  This works to the
  2112.   BEST OF OUR KNOWLEDGE, but we may have made mistakes.  So be careful!
  2113.   *******************************************************************************
  2114.  
  2115.   Al right, you just bought (or are going to buy) a Back-UPS from APC.
  2116.   (Other brands might be able to use this info, with little or no
  2117.   modification, but we don't know)  You've looked at the price of the
  2118.   Power-Chute software/cabling, and just are not sure it's worth the
  2119.   price.  Well, I made my own cable, and my own software and am using it
  2120.   to automatically shut off the power to my linux box when a power
  2121.   failure hits.  Guess what?  You can too!
  2122.  
  2123.   *** The Cable ***
  2124.  
  2125.   This was the hardest part to figure out (I know little about hardware,
  2126.   so Ben did the most work for this).  To build one, you need to buy
  2127.   from your local radio shack (or other part supplier) this stuff:
  2128.  
  2129.        1 9-Position Male D-Subminature Connector (solder-type)
  2130.                [Radio Shack cat. no. 276-1537c]
  2131.        1 9-Position Female D-Subminature Connector (solder-type)
  2132.                [Radio Shack cat. no. 276-1538c]
  2133.        2 casings for the above plugs (usually sold separately)
  2134.        Some stranded wire (wire made of strands, not solid wire)
  2135.  
  2136.   You also need, but may be able to borrow:
  2137.  
  2138.        1 soldering iron
  2139.        solder
  2140.  
  2141.   Okay...this is how you connect it up!
  2142.  
  2143.   These diagrams are looking into the REVERSE SIDE (the side where you
  2144.   solder the wire onto the plugs)  The letters G, R, and B represent the
  2145.   colors of the wires I used, and help to distinguish one line from the
  2146.   next.  (NOTE:  I'm use standard rs-232 (as near as we can tell)
  2147.   numbering.  The APC book uses different numbers.  Ignore them!  Use
  2148.   ours...I already changed the numbers for you!)
  2149.  
  2150.           ---------------------     Male Side! (This goes into the UPS)
  2151.            \  B   R  *  *  * /
  2152.              \  *  *  *  G  /
  2153.                ------------
  2154.  
  2155.           ---------------------     Female Side! (This goes into your COM port)
  2156.            \  R   *  *  *  G /
  2157.              \  *  B  *  *  /
  2158.                ------------
  2159.  
  2160.   For those who like the numbers better:
  2161.  
  2162.                Male            Female
  2163.        ---------------------------------------
  2164.                1               7               Black
  2165.                2               1               Red
  2166.                9               5               Green
  2167.  
  2168.   ---------Aside:  What the rs-232 pins are for!----------- Since we had
  2169.   to dig this info up anyway:
  2170.  
  2171.   >From the REAR (the soldering side) the pins are numbered so:
  2172.  
  2173.           ---------------------
  2174.            \  1   2  3  4  5 /
  2175.              \  6  7  8  9  /
  2176.                ------------
  2177.  
  2178.   The pins mean:
  2179.  
  2180.                Number  Name                    Abbr. (Sometimes written with D prefix)
  2181.                1       Carrier Detect          CD
  2182.                2       Receive Data            RD
  2183.                3       Transmit Data           TD(?)
  2184.                4       Data Terminal Ready     DTR
  2185.                5       Signal Ground           Gnd
  2186.                6       Data Set Ready          DSR
  2187.                7       Request to Send         RTS(?)
  2188.                8       Clear to Send           CS
  2189.                9       Ring Indicator          RI
  2190.  
  2191.   What we did is connect the UPS's RS-232 Line Fail Output to the CD,
  2192.   the UPS's chassis to Gnd, and the UPS's RS-232 Shut Down Input to RTS.
  2193.   Easy now that we told you, no?
  2194.  
  2195.   I have no idea if the software below will work, if you purchase the
  2196.   cable from APC.  It might, and it might not.
  2197.  
  2198.   *** The Software ***
  2199.  
  2200.   Okay, I use the SysVInit package by Miquel van Smoorenburg for Linux.
  2201.   (see end for file locations, credits, email addresses, etc.)  I don't
  2202.   know what would have to be changed to use someone elses init, but I
  2203.   know this code (following) will work with Miquel's stuff.  Just so I
  2204.   give credit where credit's due.  I looked at Miquel's code to figure
  2205.   out how ioctl()'s worked.  If I didn't have that example, I'd have
  2206.   been in trouble.  I also used the powerfail() routine (verbatim, I
  2207.   think), since it must interact with his init, I thought that he should
  2208.   know best.  The .c file is at the end of this document, and just needs
  2209.   to be clipped off.  To clip the file, edit away and extra '.sigs' and
  2210.   junk.  This document should end on the line /* End of File */.....cut
  2211.   the rest.
  2212.  
  2213.   This program can either be run as a daemon to check the status of the
  2214.   UPS and report it to init, or it can be run to send the kill-power
  2215.   command to the UPS.  The power will only be killed if there is a power
  2216.   problem, and the UPS is running off the battery.  Once the power is
  2217.   restored, it turns back on.
  2218.  
  2219.   To run as a daemon, just type: backupsd /dev/backups
  2220.  
  2221.   /dev/backups is a link to /dev/cua0 at the moment (COM 1, for you
  2222.   DOSers).  The niceness of the link is that I can just re-link the
  2223.   device if I change to com 2 or 3.
  2224.  
  2225.   Then, if the power dies init will run the commands for the powerwait.
  2226.   An example (This is from my /etc/inittab):
  2227.  
  2228.        #Here are the actions for powerfailure.
  2229.        pf::powerwait:/etc/rc.d/rc.power start
  2230.        po::powerokwait:/etc/rc.d/rc.power stop
  2231.  
  2232.   The powerwait will run, if the power goes down, and powerokwait will
  2233.   run if the power comes back up.
  2234.  
  2235.   Here is my entire rc.power:
  2236.  
  2237.        #! /bin/sh
  2238.        #
  2239.        # rc.power      This file is executed by init when there is a powerfailure.
  2240.        #
  2241.        # Version:      @(#)/etc/rc.d/rc.power   1.50    1994-08-10
  2242.        #
  2243.        # Author:       Christian Holtje, <docwhat@uiuc.edu>
  2244.        #
  2245.  
  2246.          # Set the path.
  2247.          PATH=/sbin:/etc:/bin:/usr/bin:/sbin/dangerous
  2248.  
  2249.          # Find out how we were called.
  2250.          case "$1" in
  2251.                start)
  2252.                        echo "Warning there is Power problems."  | wall
  2253.                        # Save current Run Level
  2254.                        ps | gawk '{ if (($5 == "init") && ($1 == "1")) print $6 }' \
  2255.                                 | cut -f2 -d[ | cut -f1 -d] \
  2256.                                 > /tmp/run.level.power
  2257.                        /sbin/shutdown -h +1m
  2258.                        ;;
  2259.                stop)
  2260.                        echo "Power is back up.  Attempting to halt shutdown." | wall
  2261.                        shutdown -c
  2262.                        ;;
  2263.                *)
  2264.                        echo "Usage:  $0 [start|stop]"
  2265.                        exit 1
  2266.                        ;;
  2267.          esac
  2268.  
  2269.   Pretty nifty, no?  Actually, there is a problem here...I haven't had
  2270.   time to figure it out...If there is a 'sh' wizard out there....
  2271.  
  2272.   There is one little detail left, that is having the UPS turn off the
  2273.   power if it was halted with the power out.  This is accomplished by
  2274.   adding this line into the end of your halt script:
  2275.  
  2276.          /sbin/backupsd /dev/backups killpower
  2277.  
  2278.   This will only kill the power if there is no power being supplied to
  2279.   your UPS.
  2280.  
  2281.   *** Testing the stuff ***
  2282.  
  2283.   This is just a short section saying this:
  2284.  
  2285.   BE CAREFUL!
  2286.  
  2287.   I recommend backing up your linux partitions, syncing several times
  2288.   before testing and just being careful in general.  Of course, I'm just
  2289.   recommending this.  I wasn't careful at all, and had to clean my
  2290.   partition several times testing my config.  But it works.  :)
  2291.  
  2292.   *** Where to Get It ***
  2293.  
  2294.   Miquel van Smoorenburg's SysVInit can be gotten at:
  2295.  
  2296.   sunsite.unc.edu:/pub/Linux/system/Daemons/SysVinit-2.50.tgz
  2297.  
  2298.   and a fix for some bash shells is right next-door as:
  2299.  
  2300.   sunsite.unc.edu:/pub/Linux/system/Daemons/SysVinit-2.50.patch1
  2301.  
  2302.   As to getting this HOWTO, you can email me.  docwhat@uiuc.edu  with
  2303.   the subject saying 'request' and the keyword 'backups' in body of the
  2304.   letter.  (I may automate this, and other stuff)
  2305.  
  2306.   *** Credit Where Credit's Due Dept. ***
  2307.  
  2308.   Thanks to Miquel van Smoorenburg <miquels@drinkel.nl.mugnet.org> for
  2309.   his wonderful SysVInit package and his powerd.c which helped me very
  2310.   much.
  2311.  
  2312.   Christian Holtje <docwhat@uiuc.edu> Documentation backupsd.c (what
  2313.   wasn't Miquel's) rc.power
  2314.  
  2315.   Ben Galliart <bgallia@orion.it.luc.edu> The cable Information for the
  2316.   RS-232 standard Lousy Jokes (none quoted here)
  2317.  
  2318.   /*  backupsd.c -- Simple Daemon to catch power failure signals from a
  2319.    *                Back-UPS (from APC).
  2320.    *
  2321.    *  Parts of the code are from Miquel van Smoorenburg's powerd.c
  2322.    *  Other parts are original from Christian Holtje <docwhat@uiuc.edu>
  2323.    *  I believe that it is okay to say that this is Public Domain, just
  2324.    *  give credit, where credit is due.
  2325.    *
  2326.    *  Disclaimer:  We make NO claims to this software, and take no
  2327.    *               resposibility for it's use/misuse.
  2328.    */
  2329.  
  2330.   #include <sys/types.h>
  2331.   #include <sys/ioctl.h>
  2332.   #include <fcntl.h>
  2333.   #include <errno.h>
  2334.   #include <stdlib.h>
  2335.   #include <unistd.h>
  2336.   #include <stdio.h>
  2337.   #include <signal.h>
  2338.  
  2339.   /* This is the file needed by SysVInit */
  2340.   #define PWRSTAT         "/etc/powerstatus"
  2341.  
  2342.   void powerfail(int fail);
  2343.  
  2344.   /* Main program. */
  2345.   int main(int argc, char **argv)
  2346.   {
  2347.     int fd;
  2348.     int killpwr_bit = TIOCM_RTS;
  2349.     int flags;
  2350.     int status, oldstat = -1;
  2351.     int count = 0;
  2352.  
  2353.     if (argc < 2) {
  2354.           fprintf(stderr, "Usage: %s <device> [killpower]\n", argv[0]);
  2355.           exit(1);
  2356.     }
  2357.  
  2358.     /* Open the the device */
  2359.     if ((fd = open(argv[1], O_RDWR | O_NDELAY)) < 0) {
  2360.           fprintf(stderr, "%s: %s: %s\n", argv[0], argv[1], sys_errlist[errno]);
  2361.           exit(1);
  2362.     }
  2363.  
  2364.     if ( argc >= 3  && (strcmp(argv[2], "killpower")==0) )
  2365.         {
  2366.             /* Let's kill the power! */
  2367.             fprintf(stderr, "%s: Attempting to kill the power!\n",argv[0] );
  2368.             ioctl(fd, TIOCMBIS, &killpwr_bit);
  2369.             /* Hmmm..... If you have a power outtage, you won't make it! */
  2370.             exit(0);
  2371.         }
  2372.     else
  2373.         /* Since we don't want to kill the power, clear the RTS. (killpwr_bit) */
  2374.         ioctl(fd, TIOCMBIC, &killpwr_bit);
  2375.  
  2376.   /* Become a daemon. */
  2377.     switch(fork()) {
  2378.     case 0: /* I am the child. */
  2379.                   setsid();
  2380.                   break;
  2381.     case -1: /* Failed to become daemon. */
  2382.                   fprintf(stderr, "%s: can't fork.\n", argv[0]);
  2383.                   exit(1);
  2384.     default: /* I am the parent. */
  2385.                   exit(0);
  2386.     }
  2387.  
  2388.     /* Now sample the DCD line. */
  2389.     while(1) {
  2390.         ioctl(fd, TIOCMGET, &flags);
  2391.         status = (flags & TIOCM_CD);
  2392.         /* Did DCD jumps to high? Then the power has failed. */
  2393.         if (oldstat == 0 && status != 0) {
  2394.             count++;
  2395.             if (count > 3) powerfail(0);
  2396.             else { sleep(1); continue; }
  2397.         }
  2398.         /* Did DCD go down again? Then the power is back. */
  2399.         if (oldstat > 0 && status == 0) {
  2400.             count++;
  2401.             if (count > 3) powerfail(1);
  2402.             else { sleep(1); continue; }
  2403.         }
  2404.         /* Reset count, remember status and sleep 2 seconds. */
  2405.         count = 0;
  2406.         oldstat = status;
  2407.         sleep(2);
  2408.     }
  2409.     /* Error! (shouldn't happen) */
  2410.     return(1);
  2411.   }
  2412.  
  2413.   /* Tell init the power has either gone or is back. */
  2414.   void powerfail(ok)
  2415.   int ok;
  2416.   {
  2417.     int fd;
  2418.  
  2419.     /* Create an info file needed by init to shutdown/cancel shutdown */
  2420.     unlink(PWRSTAT);
  2421.     if ((fd = open(PWRSTAT, O_CREAT|O_WRONLY, 0644)) >= 0) {
  2422.           if (ok)
  2423.                   write(fd, "OK\n", 3);
  2424.           else
  2425.                   write(fd, "FAIL\n", 5);
  2426.           close(fd);
  2427.     }
  2428.     kill(1, SIGPWR);
  2429.   }
  2430.  
  2431.   /* End of File */
  2432.  
  2433.   8.12.1.3.  More notes
  2434.  
  2435.   From ockers@carnot02.maem.umr.edu Mon Jan 16 15:27:29 1995
  2436.   Newsgroups: comp.os.linux.hardware
  2437.   Subject: Back-UPS, backupsd, and low battery signal
  2438.   From: ockers@carnot02.maem.umr.edu (Jim Ockers)
  2439.   Date: 12 Jan 1995 04:22:44 GMT
  2440.   Reply-To: ockers@umr.edu
  2441.   Organization: the all-male wasteland of Rolla, MO
  2442.   NNTP-Posting-Host: carnot02.maem.umr.edu
  2443.   X-Newsreader: TIN [version 1.2 PL2]
  2444.  
  2445.   Hello all,
  2446.  
  2447.   I use the backupsd on my linux system and I like it a lot.  I also
  2448.   run Windows NT when I have to and it has a UPS daemon too.  The pinouts
  2449.   required by Windows NT are different from the ones you specify in the
  2450.   program but that is easily changed since I have the source for your
  2451.   program..
  2452.  
  2453.   Anyways I was browsing through the Windows NT knowledge base (KB) and
  2454.   found something interesting.  If you look in the documentation for your
  2455.   Back-UPS under "computer interface port" you will see that this UPS will
  2456.   send a Low Battery signal at least two minutes before the battery fails.
  2457.  
  2458.   At least the manual for my Back-UPS 400 says that...
  2459.  
  2460.   However they also speak some Electrical Engineering gibberish ("Outputs ...
  2461.   are actually open collector outputs which must be pulled up to a common
  2462.   referenced supply no greater than +40 Vdc.  The transistors are capable
  2463.   of a maximum non-inductive load of 25mAdc.)
  2464.  
  2465.   Well that means nothing to me, but what I discovered in the NT KB was
  2466.   that it is possible to use the low battery signal in the same manner that
  2467.   the other signals are used.  The output from pin 5 on the UPS should go
  2468.   to the pin on which you are reading the LowBatt signal into the computer.
  2469.   When that line goes high, the battery is running out of charge.  When
  2470.   the situation is normal, that line will be low.  (Hi/Lo in a standard
  2471.   RS-232 signal, just like the other lines.)
  2472.  
  2473.   What they don't tell you in the APC manual, and they should, is that
  2474.   you need to buy a 10 KOhm resistor (50 cents at Radio Shack) and connect
  2475.   pins 5 and 8 on the UPS side using the resistor.  Pin 8 provides the
  2476.   "common referenced supply no greater than 40vdc".  Here's how you would
  2477.   make the cable (the 1st three lines are the same as the HOWTO):
  2478.  
  2479.          PC side                         UPS side
  2480.   pin      7 <------------------------------> 1                 ShutDownUPS
  2481.            1 <------------------------------> 2                 LineFail
  2482.            5 <------------------------------> 4 (same as 9 )    GND
  2483.            ? your choice  <-----------------> 5                 LowBatt
  2484.                                               |
  2485.                                                > 10
  2486.                                               <  KOhm
  2487.                                               |
  2488.                                               8
  2489.  
  2490.   So then when the LowBatt line is HIGH then the computer has 2 minutes
  2491.   to shut down before the battery runs out.
  2492.  
  2493.   This is not mentioned in the Back-UPS HOWTO nor is it addressed in the
  2494.   backupsd source.  However I would think that it would be a Good Thing
  2495.   to have in there; especially since a power failure would not require
  2496.   a shutdown unless the UPS batteries were low.  In most cases it would
  2497.   mean that the backupsd could send a warning to everyone if the LineFails,
  2498.   and give everyone a one (or two) minute warning when the batteries start
  2499.   running down.
  2500.  
  2501.   As far as I know this applies to all the APC Back-UPS and Smart-UPS
  2502.   products.  These instructions were for a Smart-UPS 900,1250, and 2000
  2503.   according to the NT KB.  However they have been tested with a Back-UPS
  2504.   400 running Windows NT and everything works properly...
  2505.  
  2506.   I'd sure like to have a backupsd that handled the LowBatt situation too.
  2507.   Does anyone feel like modifying the backupsd.c source so that it will do
  2508.   this too?  (I can't program in C yet...)
  2509.  
  2510.   P.S. The APC manual says to use only pin 4 as the common and even though
  2511.   in the diagram it says that pin 9 is connected to pin 4 you might want to
  2512.   be sure and use pin 4 .  This differs from the instructions in the HOWTO.
  2513.  
  2514.   P.P.S. I mailed this to the Back-UPS HOWTO authors.
  2515.  
  2516.   --
  2517.   Jim  (ockers@umr.edu)                   Ask me about Linux!
  2518.   http://www.umr.edu/~ockers/ - home page
  2519.  
  2520.   From: Peter Kammer <pkammer@liege.ICS.UCI.EDU>
  2521.   To: "Harvey J. Stein" <hjstein@math.huji.ac.il>
  2522.   cc: "Christian G. Holtje" <docwhat@uiuc.edu>
  2523.   Subject: UPS-Howto--minor correction
  2524.   Date: Mon, 07 Oct 1996 12:00:16 -0700
  2525.  
  2526.   Mr. Stein,
  2527.  
  2528.           Let me first thank you for putting together and maintaining the
  2529.   Linux UPS-HowTo document.  I recently attached a APC Back-UPS 400 to a
  2530.   a Linux box and the document turned out to be very helpful.
  2531.           I would like to suggest a correction to the the text diagrams which
  2532.   accompany the description in section 11.5.2.  The diagrams are presented as
  2533.   being the rear of the plug.  This in mind, the diagram of the male is
  2534.   backwards:
  2535.  
  2536.            ---------------------     Male Side! (This goes into the UPS)
  2537.             \  B   R  *  *  * /
  2538.               \  *  *  *  G  /
  2539.                 ------------
  2540.  
  2541.   _From the rear_, the pins on the male connector are numbered
  2542.   right-to-left.  The correct diagram should be:
  2543.  
  2544.            ---------------------     Male Side! (This goes into the UPS)
  2545.             \  *   *  *  R  B /
  2546.               \  G  *  *  *  /
  2547.                 ------------
  2548.  
  2549.   Similarly, the numbered diagram should be labeled as for the rear of the
  2550.   female plug.
  2551.  
  2552.            ---------------------
  2553.             \  1   2  3  4  5 /
  2554.               \  6  7  8  9  /
  2555.                 ------------
  2556.  
  2557.   The rear of the male is numbered the reverse:
  2558.  
  2559.            ---------------------
  2560.             \  5   4  3  2  1 /
  2561.               \  9  8  7  6  /
  2562.                 ------------
  2563.  
  2564.   This caused us some confusion until we realized our mistake.  With four
  2565.   different configurations to be aware of (front, rear) x (male, female) it
  2566.   is easy to get confused.  Even now, reference in hand, I keep reexamining
  2567.   my diagrams.
  2568.  
  2569.   It might also be helpful to add a reference to the APC technical document
  2570.   for the Back-UPS line which is available on-line at:
  2571.  
  2572.      http://www.apcc.com/english/techs/techref4/224e.htm
  2573.  
  2574.   Once we corrected our wiring, setting up the software was relatively simple
  2575.   thanks to your documentation.  We used the alternative (using TD to kill
  2576.   the UPS power rather than RTS) wiring scheme and ran into few problems.
  2577.   Your efforts in maintaining this information are much appreciated.
  2578.  
  2579.   ------------
  2580.   Peter Kammer                       Dept. of Information and Computer Science
  2581.   pkammer@ics.uci.edu                University of California
  2582.   http://www.ics.uci.edu/~pkammer/   Irvine, CA 92697-3425
  2583.  
  2584.   8.12.2.  APC Smart-UPS
  2585.  
  2586.   Many people have APC Smart UPSs.  There seem to be packages for using
  2587.   them in smart modes (see the afore mentioned packages
  2588.   Enhanced_APC_UPSD-v1.4.tar.gz, apcd-0.5.tar.gz, and
  2589.   smupsd-0.7-1.i386.rpm described in section ``Software'').  I don't
  2590.   know how the support in each package is.  It seems that APC still
  2591.   refuses to release the protocol for the ``smart'' mode without a non-
  2592.   disclosure agreement, so everyone's left reverse engineering it.
  2593.  
  2594.   The general consensus is to buy from a brand which does release the
  2595.   information, such as Best.
  2596.  
  2597.   Another possibility is to run the SCO Unix version of APC's Powerchute
  2598.   UPS control software under Linux via the iBCS compatibility package.
  2599.   I'm told by Clive A. Stubbings (cas@vjet.demon.co.uk) that this works
  2600.   nicely after some install script adjustments.  He says that the only
  2601.   problem is "the GUI stuff seems to have difficulty controlling non-
  2602.   local UPSs across the net".
  2603.  
  2604.   If you have an APC Smart-UPS, and you can't get any of the above
  2605.   software to work in smart mode, you can still use it in dumb mode.
  2606.   The following sections detail how to do that.  In particular, I've
  2607.   received messages from people regarding the Model 600, the Model 700,
  2608.   and the model 1400.  You'll probably have to hack powerd.c as outlined
  2609.   in section ``Reverse-engineering cables and hacking powerd.c''.
  2610.  
  2611.   8.12.2.1.  APC Smart-UPS, Model 600
  2612.  
  2613.   From dangit@netcom.com Mon Aug 22 10:16:23 1994
  2614.   Newsgroups: comp.os.linux.misc
  2615.   Subject: UPS Monitoring Cable For APC
  2616.   From: dangit@netcom.com (Lam Dang)
  2617.   Date: Fri, 19 Aug 1994 11:56:28 GMT
  2618.   Organization: NETCOM On-line Communication Services (408 261-4700 guest)
  2619.   X-Newsreader: TIN [version 1.2 PL1]
  2620.  
  2621.   [Didn't make it the first time.]
  2622.  
  2623.   A few netters have asked about UPS monitoring cables.  This is what I
  2624.   found when I made one for my APC Smart-UPS, Model 600.  A disclaimer is in
  2625.   order.  This is just an experimenter's report; use it at your own risks.
  2626.   Please read the User's Manual first, especially Section 6.4, Computer
  2627.   Interface Port.
  2628.  
  2629.   The cable is to run between a 9-pin female connector on the UPS and a
  2630.   25-pin male connector on the PC.  Since I cut off one end of a 9-pin
  2631.   cable and replaced it with a 25-pin connector, I had to be VERY
  2632.   CAREFUL ABOUT PIN NUMBERS.  The 25-pin hood is big enough to contain a
  2633.   voltage regulator and two resistors.  I got all the materials (listed
  2634.   below) from Radio Shack for less than 10 bucks.  As required by Windows NT
  2635.   Advanced Server 3.5 (Beta 2), the "interface" between the UPS connector
  2636.   and the PC connector is as follows:
  2637.  
  2638.           UPS (9-pin)              PC (25-pin)
  2639.  
  2640.           1 (Shutdown)             20 (DTR)
  2641.           3 (Line Fail)             5 (CTS)
  2642.           4 (Common)                7 (GND)
  2643.           5 (Low Battery)           8 (DCD)
  2644.           9 (Chassis Ground)        1 (Chassis Ground)
  2645.  
  2646.   This is pretty straightforward.  You can use UPS pin 6 instead of 3
  2647.   (they're the inverse of each other).  The complication is in pulling up
  2648.   UPS open collector pins 3 (or 6) and 5.
  2649.  
  2650.   This APC model provides an unregulated output of 24 Vdc at UPS pin 8. The
  2651.   output voltage is available all the time (at least until some time after
  2652.   Low Battery has been signalled).  The supply is limited to 40 mA.  To
  2653.   pull up, UPS pin 8 is input to a +5 Vdc voltage regulator.  The output of
  2654.   the regulator goes into two 4.7K resistors.  The other end of one
  2655.   resistor connects both UPS pin 3 (Line Fail) and PC pin 5 (CTS).  That
  2656.   of the other resistor connects both UPS pin 5 (Low Battery) and PC pin 8
  2657.   (DCD).  The two resistors draw about 2 mA when closed.
  2658.  
  2659.   Test your cable without connecting it to the PC.  When the UPS is on
  2660.   line, pins 5 (CTS) and 8 (DCD) at the PC end of the cable should be very
  2661.   close to 5 Vdc, and applying a high to pin 20 (DTR) for 5 seconds should
  2662.   have no effect.  Now pull the power plug to put the UPS on battery.  Pin
  2663.   5 (CTS) should go down to zero Vdc, pin 8 (DCD) should stay the same at 5
  2664.   Vdc, and applying a high to pin 20 (DTR), e.g., by shorting pins 8 and 20,
  2665.   should shut down the UPS after about 15 seconds.
  2666.  
  2667.   Keep the UPS on battery until Low Battery is lighted on its front panel.
  2668.   Now pin 8 (DCD) should go down to zero Vdc too.  Wait until the UPS
  2669.   battery is recharged.  Then connect your cable to the PC, disable the UPS
  2670.   option switches by turning all of them ON, and run your favorite UPS
  2671.   monitoring software.
  2672.  
  2673.   For those who want to run it with Windows NT Advanced Server, the UPS
  2674.   interface voltages are NEGATIVE for both power failure (using UPS pin 3)
  2675.   and low battery conditions, and POSITIVE for remote shutdown.  Serial
  2676.   line parameters such as baud rate don't matter.
  2677.  
  2678.   I haven't tested my cable with Linux powerd.  When you do, please let us
  2679.   know.  I run NT as often as Linux on the same PC.  I must conform to NT's
  2680.   UPS scheme.  Perhaps somebody can modify powerd to work with it and post
  2681.   the source code here.
  2682.  
  2683.   List of materials:
  2684.  
  2685.           1 shielded D-sub connector hood (Radio Shack 276-1510)
  2686.           1 25-pin female D-sub crimp-type connector (276-1430)
  2687.           1 7805 +5Vdc voltage regulator (276-1770)
  2688.           2 4.7K resistors
  2689.           1 component perfboard (276-148)
  2690.           1 cable with at least one 9-pin male connector.
  2691.  
  2692.   You'll need a multimeter, a soldering iron, and a couple of hours.
  2693.  
  2694.   Hope this helps.
  2695.  
  2696.   Regards,
  2697.  
  2698.   --
  2699.   Lam Dang
  2700.   dangit@netcom.com
  2701.  
  2702.   8.12.2.2.  APC Smart-UPS 700
  2703.  
  2704.   Here're some details for running an APC Smart-UPS 700 in dumb mode.
  2705.  
  2706.   It has a clever usage of a transistor in the cable so that the UPS
  2707.   will turn off when the computer is turned off.  And it includes a
  2708.   powerd.c which also does a fast low battery shutdown.
  2709.  
  2710.   Also, note that Markus' is also using init's new capabilities.  So we
  2711.   have here another illustration of how to use the new init to your
  2712.   advantage.
  2713.  
  2714.   From: Markus Eiden <Markus@eiden.de>
  2715.   Sender: eiden@eiden.de
  2716.   To: "Harvey J. Stein" <abel@netvision.net.il>
  2717.   Subject: Re: APC Smart-UPS
  2718.   Date: Sun, 30 Mar 1997 16:21:05 +0200
  2719.  
  2720.   I'm using an APC Smart-UPS 700 for my Linux box, running 2.0.21 on an
  2721.   ASUS-Board.
  2722.  
  2723.   To use some features of the UPS you need four things:
  2724.  
  2725.   1) You have to build a RS232-cable with a small interface.
  2726.   2) You need the powerd-source from the sysvinit-package (I use version 2.65
  2727.       from Miquel van Smoorenburg). Then you have to patch his powerd.
  2728.   3) You have to change your /etc/inittab
  2729.   4) You need a script to run some commands if the power is down or battery
  2730.      is low.
  2731.  
  2732.   Some features:
  2733.  
  2734.   When the power goes down, a script will start and a syslog-entry is done.
  2735.  
  2736.   If the battery is low, an other  script will start
  2737.   (which shutdown your computer of course) and a syslog-entry is done.
  2738.  
  2739.   If you shutdown your computer and the power is down, the UPS will be shut
  2740.   down too.
  2741.  
  2742.    1)Let's start with the cable:
  2743.   ================================
  2744.  
  2745.   If you have a look at the back side of you UPS you will see a female
  2746.   connector like this:
  2747.  
  2748.                8             1: Shutdown the UPS when the power is down and
  2749.                                  pin 1 is high.
  2750.        X   X   X   X         3: Goes low on "Linefail"
  2751.      X   X   X   X   X       4: GND
  2752.                              5: Goes low on  "Low battery"
  2753.      1       3   4   5       8: +24V
  2754.  
  2755.   On the other hand at the back side of your PC there exist a male
  2756.   connector like this:
  2757.  
  2758.            8       6         1: DCD
  2759.        X   X   X   X         4: DTR
  2760.      X   X   X   X   X       5: GND
  2761.      5   4           1       6: DSR
  2762.                              8: CTS
  2763.  
  2764.   You have to build the following interface between these connectors:
  2765.  
  2766.    PC                                                           UPS
  2767.  
  2768.                                            #------------------  (8)
  2769.                                            |
  2770.                                           470 Ohm
  2771.                                            |
  2772.              #-----#-----#-----#-----#-----#----- ca. 9-12V
  2773.              |     |     |     |     |     |
  2774.              47    3.3   3.3   3.3   1     470
  2775.              kOhm  kOhm  kOhm  kOhm  kOhm  Ohm
  2776.              |     |     |     |     |     |
  2777.    (8) ------------------------#     |     |
  2778.              |     |     |           |     |
  2779.    (6) ------------#------------------------------------------- (5)
  2780.              |           |           |     |
  2781.    (1) ------------------#------------------------------------- (3)
  2782.              |                       |     |
  2783.              |                      C#------------------------- (1)
  2784.              |                      -|     |
  2785.              |                    B/       |
  2786.    (4) ------#-----12kOhm---------|        |
  2787.                                    \>E     |
  2788.                                    |       |
  2789.    (5)-----------------------------#-------#------------------- (4)
  2790.  
  2791.     -I use a "BC140" - transistor, but nearly any simple NPN-transistor
  2792.      should work  ;-)
  2793.  
  2794.     -The transistor works as an "inverter". If you shutdown your PC,
  2795.      AND the power ist down, then pin 4(PC) goes low and 1(UPS) goes
  2796.      high. This shuts down the UPS  for saving batteries power.
  2797.  
  2798.    2) The powerd-Source:
  2799.   =======================
  2800.  
  2801.   I patched the powerd-source very little (so it is really the source
  2802.   of Miquel).
  2803.  
  2804.   (a) Give an "alert" to the syslogd if 8(PC, CTS) is down (Cause
  2805.        the cable is not connected)
  2806.  
  2807.   (b) DCD droped to zero => power has failed => call powerfail(0)
  2808.       => Give INIT_CMD_POWERFAIL to the init-process
  2809.  
  2810.   (c) DCD comes up again => power is back => call powerfail(1)
  2811.       => Give INIT_CMD_POWEROK to the init-process
  2812.  
  2813.   (d) DSR and DCD are dropped to zero => power has failed and
  2814.       battery is low => call powerfail(2) => Give
  2815.       INIT_CMD_POWERFAILNOW to the init-process
  2816.  
  2817.    Thats it.
  2818.  
  2819.   ------------------------------>8---- Schnipp ----------------------------
  2820.  
  2821.   /*
  2822.    * powerd       Monitor the DCD line of a serial port connected to
  2823.    *              an UPS. If the power goes down, notify init.
  2824.    *              If the power comes up again, notify init again.
  2825.    *              As long as the power is OK, the DCD line should be
  2826.    *              "HIGH". When the power fails, DCD should go "LOW".
  2827.    *              Powerd keeps DTR high so that you can connect
  2828.    *              DCD and DTR with a resistor of 10 Kilo Ohm and let the
  2829.    *              UPS or some relais pull the DCD line to ground.
  2830.    *              You also need to connect DTR and DSR together. This
  2831.    *              way, powerd can check now and then if DSR is high
  2832.    *              so it knows the UPS is connected!!
  2833.    *
  2834.    * Usage:       powerd /dev/cua4 (or any other serial device).
  2835.    *
  2836.    * Author:      Miquel van Smoorenburg, <miquels@drinkel.cistron.nl>.
  2837.    *              Some minor changes by Markus Eiden, <Markus@Eiden.de>
  2838.    *              for the APC-Smart-UPS-powerd.
  2839.    *
  2840.    * Version:     1.31,  29-Feb-1996.
  2841.    *
  2842.    *              This program was originally written for my employer,
  2843.    *                      ** Cistron Electronics **
  2844.    *              who has given kind permission to release this program
  2845.    *              for general puppose.
  2846.    *
  2847.    *              Copyright 1991-1996 Cistron Electronics.
  2848.    *
  2849.    *              This program is free software; you can redistribute it and/or
  2850.    *              modify it under the terms of the GNU General Public License
  2851.    *              as published by the Free Software Foundation; either version
  2852.    *              2 of the License, or (at your option) any later version.
  2853.    *
  2854.    *              Some minor changes for the APC-powerd by Markus Eiden
  2855.    *              Markus@Eiden.de
  2856.    */
  2857.  
  2858.   /* Use the new way of communicating with init. */
  2859.   #define NEWINIT
  2860.  
  2861.   #include <sys/types.h>
  2862.   #include <sys/stat.h>
  2863.   #include <sys/ioctl.h>
  2864.   #include <fcntl.h>
  2865.   #include <errno.h>
  2866.   #include <stdlib.h>
  2867.   #include <unistd.h>
  2868.   #include <stdio.h>
  2869.   #include <signal.h>
  2870.   #include <syslog.h>
  2871.   #include <string.h>
  2872.   #include "paths.h"
  2873.   #ifdef NEWINIT
  2874.   #include "initreq.h"
  2875.   #endif
  2876.  
  2877.   #ifndef SIGPWR
  2878.   #  define SIGPWR SIGUSR1
  2879.   #endif
  2880.  
  2881.   #ifdef NEWINIT
  2882.   void alrm_handler()
  2883.   {
  2884.   }
  2885.   #endif
  2886.  
  2887.   /* Tell init the power has either gone or is back. */
  2888.   void powerfail(ok)
  2889.   int ok;
  2890.   {
  2891.     int fd;
  2892.   #ifdef NEWINIT
  2893.     struct init_request req;
  2894.  
  2895.     /* Fill out the request struct. */
  2896.     memset(&req, 0, sizeof(req));
  2897.     req.magic = INIT_MAGIC;
  2898.  
  2899.     /* INIT_CMD_* are definied in initreq.h                   *
  2900.      * Have a look at  init.c and /etc/inittab                *
  2901.      *                                                        *
  2902.      * ok=0 -> INIT_CMD_POWERFAIL      -> powerwait           *
  2903.      * ok=1 -> INIT_CMD_POWEROK        -> powerokwait         *
  2904.      * ok=2 -> INIT_CMD_POWERFAILNOW   -> powerfailnow        */
  2905.  
  2906.     switch (ok) {
  2907.       case 0 : req.cmd = INIT_CMD_POWERFAIL;
  2908.                /* Linefail -> warning */
  2909.                break;
  2910.       case 1 : req.cmd = INIT_CMD_POWEROK;
  2911.                /* Power is back -> cancel warning */
  2912.                break;
  2913.       case 2 : req.cmd = INIT_CMD_POWERFAILNOW;
  2914.                /* Linefail and LowBatt -> reboot */
  2915.                break;
  2916.                }
  2917.  
  2918.     /* Open the fifo (with timeout) */
  2919.     signal(SIGALRM, alrm_handler);
  2920.     alarm(3);
  2921.     if ((fd = open(INIT_FIFO, O_WRONLY)) >= 0
  2922.                   && write(fd, &req, sizeof(req)) == sizeof(req)) {
  2923.           close(fd);
  2924.           return;
  2925.     }
  2926.     /* Fall through to the old method.. */
  2927.   #endif
  2928.  
  2929.     /* Create an info file for init. */
  2930.     unlink(PWRSTAT);
  2931.     if ((fd = open(PWRSTAT, O_CREAT|O_WRONLY, 0644)) >= 0) {
  2932.           if (ok)
  2933.                   write(fd, "OK\n", 3);
  2934.           else
  2935.                   write(fd, "FAIL\n", 5);
  2936.           close(fd);
  2937.     }
  2938.     kill(1, SIGPWR);
  2939.   }
  2940.  
  2941.   /* Main program. */
  2942.   int main(int argc, char **argv)
  2943.   {
  2944.     int fd;
  2945.     int dtr_bit = TIOCM_DTR;
  2946.     int flags;
  2947.     int status, oldstat = -1;
  2948.     int count = 0;
  2949.     int tries = 0;
  2950.     int powerfailed = 0;
  2951.     int rebootnow   = 0;
  2952.     if (argc < 2) {
  2953.           fprintf(stderr, "Usage: powerd <device>\n");
  2954.           exit(1);
  2955.     }
  2956.  
  2957.     /* Start syslog. */
  2958.     openlog("powerd", LOG_CONS|LOG_PERROR, LOG_DAEMON);
  2959.  
  2960.     /* Open monitor device. */
  2961.     if ((fd = open(argv[1], O_RDWR | O_NDELAY)) < 0) {
  2962.           syslog(LOG_ERR, "%s: %s", argv[1], sys_errlist[errno]);
  2963.           closelog();
  2964.           exit(1);
  2965.     }
  2966.  
  2967.     /* Line is opened, so DTR is high. Force it anyway to be sure. */
  2968.  
  2969.     /* USE: low Batt -> Reboot -> DTR goes low                     *
  2970.      * transistor is open -> shutdown-pin  of the UPS goes         *
  2971.      * high -> UPS goes down after about 20s. If there is a        *
  2972.      * linefail and the computer is off, the                       *
  2973.      * UPS goes down. If the power is back, the                    *
  2974.      * UPS goes on, the computer boots, and powerd                 *
  2975.      * is startet.                                                 */
  2976.  
  2977.    /* Verwendung: Die UPS meldet low Batt -> Reboot -> DTR geht   *
  2978.      * auf Low -> Transistor oeffnet -> Shutdown der UPS geht auf  *
  2979.      * High -> UPS schaltet sich nach circa 20s aus. Bei jedem     *
  2980.      * Linefail und ausgeschaltetem Computer, schaltet sich die    *
  2981.      * UPS aus. Kommt der Strom zurueck, dann schaltet sich die    *
  2982.      * UPS selbstaendig ein, der Computer bootet, und der powerd   *
  2983.      * wird gestartet.                                             */
  2984.  
  2985.     ioctl(fd, TIOCMBIS, &dtr_bit);
  2986.  
  2987.     /* Daemonize. */
  2988.     switch(fork()) {
  2989.           case 0: /* Child */
  2990.                   closelog();
  2991.                   setsid();
  2992.                   break;
  2993.           case -1: /* Error */
  2994.                   syslog(LOG_ERR, "can't fork.");
  2995.                   closelog();
  2996.                   exit(1);
  2997.           default: /* Parent */
  2998.                   closelog();
  2999.                   exit(0);
  3000.     }
  3001.  
  3002.     /* Restart syslog. */
  3003.     openlog("powerd", LOG_CONS, LOG_DAEMON);
  3004.  
  3005.      syslog(LOG_INFO, "APCpowerd started...");
  3006.  
  3007.     /* Now sample the DCD line. */
  3008.     while(1) {
  3009.           /* Get the status. */
  3010.           ioctl(fd, TIOCMGET, &flags);
  3011.  
  3012.           /* Check the connection: CTS should be high. */
  3013.           tries = 0;
  3014.           /* TIOCM_*- have a look at  .../ams/termios.h */
  3015.           while((flags & TIOCM_CTS) == 0) {
  3016.                   /* Keep on trying, and warn every two minutes. */
  3017.                   if ((tries % 60) == 0)
  3018.                       syslog(LOG_ALERT, "UPS connection error");
  3019.                   sleep(2);
  3020.                   tries++;
  3021.                   ioctl(fd, TIOCMGET, &flags);
  3022.           }
  3023.           if (tries > 0)
  3024.                   syslog(LOG_ALERT, "UPS connection OK");
  3025.  
  3026.           /* Calculate present status. */
  3027.           status = (flags & TIOCM_CAR);
  3028.  
  3029.           /* Did DCD drop to zero? Then the power has failed. */
  3030.           if (oldstat != 0 && status == 0) {
  3031.                   count++;
  3032.                   if (count > 3) {
  3033.                           powerfailed = 1;
  3034.                           powerfail(0);
  3035.                           }
  3036.                   else {
  3037.                           sleep(1);
  3038.                           continue;
  3039.                   }
  3040.           }
  3041.           /* Did DCD come up again? Then the power is back. */
  3042.           if (oldstat == 0 && status > 0) {
  3043.                   count++;
  3044.                   if (count > 3) {
  3045.                           powerfailed = 0;
  3046.  
  3047.                           /* eigentlich unnoetig: */
  3048.                           rebootnow = 0;
  3049.  
  3050.                           powerfail(1);
  3051.                           }
  3052.                   else {
  3053.                           sleep(1);
  3054.                           continue;
  3055.                   }
  3056.           }
  3057.  
  3058.           /* Low battery and Linefail ? */
  3059.           if (rebootnow==0)
  3060.           if (powerfailed==1)
  3061.           if ((flags & TIOCM_DSR) == 0)
  3062.           {
  3063.              rebootnow=1;
  3064.              powerfail(2);
  3065.  
  3066.           }
  3067.  
  3068.           /* Reset count, remember status and sleep 2 seconds. */
  3069.           count = 0;
  3070.           oldstat = status;
  3071.           sleep(2);
  3072.     }
  3073.     /* Never happens */
  3074.     return(0);
  3075.   }
  3076.  
  3077.   ------------------- schnap ------------ 8<-----------------------------
  3078.  
  3079.    3) Change your inittab:
  3080.   =========================
  3081.  
  3082.   Init gets the INIT_CMDs and will start a script:
  3083.  
  3084.   pf::powerwait:/sbin/init.d/powerfail    start
  3085.   pn::powerfailnow:/sbin/init.d/powerfail now
  3086.   po::powerokwait:/sbin/init.d/powerfail  stop
  3087.  
  3088.   (Which means for example: if the power has failed (powerwait) start the
  3089.   script /sbin/init.d/powerfail with the parameter "start".)
  3090.  
  3091.   4) The powerfail-Script
  3092.   ========================
  3093.  
  3094.   ------------------ 8< ------- schnipp ---------------
  3095.  
  3096.   #! /bin/sh
  3097.   # Copyright (c) 1997 Markus Eiden, Markus@Eiden.de
  3098.   #
  3099.  
  3100.   case "$1" in
  3101.       start)
  3102.           echo "THE POWER IS DOWN!" | wall
  3103.           logger "Powerfail"
  3104.           ;;
  3105.       now)
  3106.           echo "BATTERY IS LOW! Shutdown in 1 minute" | wall
  3107.           logger "Battery is low, shutdown in 1 minute"
  3108.           sync
  3109.           /sbin/shutdown -r -t 5 +1
  3110.           ;;
  3111.       stop)
  3112.           echo "THE POWER IS BACK!!" | wall
  3113.           logger "Power is back"
  3114.  
  3115.           /sbin/shutdown -c >/dev/null 2>/dev/null
  3116.  
  3117.           ;;
  3118.     *)
  3119.           echo "Usage: $0 {start|now|stop}"
  3120.           exit 1
  3121.           ;;
  3122.   esac
  3123.  
  3124.   exit 0
  3125.  
  3126.   --------------------- >8 ----------- schnapp -------------
  3127.  
  3128.   Well, that should be easy ;-)
  3129.  
  3130.   You are ready now, but be careful: It works for me, but I really can't
  3131.   guarantee that any of this will work for you.
  3132.  
  3133.   Some advice at the end:  If /sbin/init.d/powerfail shuts down your
  3134.   PC  then DTR goes down, so the shutdown pin (UPS) goes high.
  3135.   >From that time it takes about 20 or 30 seconds for the UPS to shut down.
  3136.   It is your job to prevent your Linux-box from booting within these 20
  3137.   seconds (in particular to mount the filesystem). On my system it was no
  3138.   problem. There are four easy ways to prevent the PC from the fast booting:
  3139.    1) The BIOS should do some routines (Like searching the number of
  3140.        tracks of your floppydisk if you have one)
  3141.  
  3142.    2) If you have LILO installed, tell him to wait.
  3143.  
  3144.    3) You do nothing (like I did)
  3145.  
  3146.    4) You buy some more memory so that counting the memory takes 30 seconds.
  3147.       That should be about 1024 Megabytes ;-).
  3148.  
  3149.   Markus Eiden
  3150.  
  3151.   Markus@Eiden.de
  3152.  
  3153.   --
  3154.   -----------------------------------------------------------------------
  3155.   StR Dipl.-Ing. Markus Eiden \\://                       Markus@eiden.de
  3156.   Am alten Sportplatz 3       (o -)        http://www.rp.schule.de/eiden/
  3157.   D-67599 Gundheim      ---ooO-(_)-Ooo---             NIC-HDL: ME256-RIPE
  3158.  
  3159.   8.12.2.3.  APC Smart-UPS 1400
  3160.  
  3161.   Another day, another APC.  This is for the Smart-UPS 1400, in dumb
  3162.   mode.
  3163.  
  3164.   From: "Slavik Terletsky" <ts@polynet.lviv.ua>
  3165.   To: hjstein@math.huji.ac.il
  3166.   Subject: my contribution to UPS HOWTO
  3167.   Date: Mon, 27 Jan 1997 21:10:16 +0000
  3168.  
  3169.   Hello
  3170.   I just hacked ups daemon, if you want, you may enclose it
  3171.   in your UPS HOWTO document (i used some info from).
  3172.   Please replay.
  3173.   --
  3174.  
  3175.   UPS daemon for FreeBSD (2.1.5 - tested).
  3176.   Interacts with APC Smart-UPS 1400.
  3177.  
  3178.   Connection scheme:
  3179.  
  3180.   UPS (pin, signal name)          PC (pin, signal name)
  3181.   ----------------------          ---------------------
  3182.   1 Shutdown              >----------->   4 Data Terminal Ready
  3183.   2 Line Failed           >----------->   8 Clear To Send
  3184.   4 Common                >----------->   5 Ground
  3185.   5 Battery Low           >--------+-->   1 Data Carrier Detector
  3186.   8 Battery (+24V)        >--|10K|-+
  3187.  
  3188.   UPSD DESCRIPTION
  3189.  
  3190.   usage: upsd <device> [wait [script]]
  3191.  
  3192.   device  - device name upsd interacts thru (e.g. /dev/cuaa1)
  3193.   wait    - time (secs) to wait before running script, (default value 0 sec).
  3194.   script  - system shutdown script (default /etc/rc.shutdown).
  3195.  
  3196.   Actions:
  3197.   upsd logs all the changes of UPS status (power {up,down}, battery {low,ok}).
  3198.   When "power down" and "battery low" upsd activates UPS SHUTDOWN signal,
  3199.   waits for a <wait> seconds, and then runs system shutdown script - <script>.
  3200.  
  3201.   Script sample:
  3202.  
  3203.   #!/bin/sh
  3204.   # Script is executed when system is going down.
  3205.  
  3206.   PATH=/sbin:/bin:/usr/sbin:/usr/bin
  3207.  
  3208.   echo "System is going DOWN right NOW" | wall
  3209.  
  3210.   reboot
  3211.  
  3212.   Upsd source:
  3213.   /* UPS daemon
  3214.    * Copyright 1997 Slavik Terletsky. All rights reserved.
  3215.    * Author: Slavik Terletsky <ts@polynet.lviv.ua>
  3216.    * System: FreeBSD
  3217.    */
  3218.   #include <stdio.h>
  3219.   #include <stdlib.h>
  3220.   #include <signal.h>
  3221.   #include <syslog.h>
  3222.   #include <unistd.h>
  3223.   #include <varargs.h>
  3224.   #include <fcntl.h>
  3225.   #include <errno.h>
  3226.   #include <sys/uio.h>
  3227.   #include <sys/types.h>
  3228.   #include <sys/ioctl.h>
  3229.   #include <sys/ttycom.h>
  3230.  
  3231.   int status;
  3232.   int wait = 0;
  3233.   FILE *fd;
  3234.   char *scr = "/etc/rc.shutdown";
  3235.   char *idf = "/var/run/upsd.pid";
  3236.  
  3237.   void upsterm();
  3238.   void upsdown(int);
  3239.  
  3240.   int main(int argc, char *argv[]) {
  3241.    int pd;
  3242.    int zero = 0;
  3243.    char d5, d6, d7;
  3244.    char low = 0;
  3245.    char pow = 1;
  3246.  
  3247.    /* check arguments */
  3248.    switch(argc) {
  3249.    case  4:
  3250.    scr = argv[3];
  3251.    case  3:
  3252.    wait = atoi(argv[2]);
  3253.    case  2:
  3254.    break;
  3255.    default:
  3256.    fprintf(stderr, "usage: %s <device> [wait [script]]\n", argv[0]);
  3257.    exit(1);
  3258.    }
  3259.  
  3260.    /* check if script exists */
  3261.    if(!(fd = fopen(scr, "r"))) {
  3262.    fprintf(stderr, "fopen: %s: %s\n", scr, sys_errlist[errno]);
  3263.    exit(1);
  3264.    }
  3265.    fclose(fd);
  3266.  
  3267.    /* check if upsd is already running */
  3268.    if(fd = fopen(idf, "r")) {
  3269.    fprintf(stderr, "fopen: %s: File already exists\n", idf);
  3270.    exit(1);
  3271.    }
  3272.  
  3273.    /* become a daemon */
  3274.    switch(fork()) {
  3275.    case -1:       /* error */
  3276.    fprintf(stderr, "fork: %s\n", sys_errlist[errno]);
  3277.    exit(1);
  3278.    case  0:       /* child */
  3279.    break;
  3280.    default:       /* parent */
  3281.    exit(0);
  3282.    }
  3283.  
  3284.    /* save the pid */
  3285.    if(!(fd = fopen(idf, "w"))) {
  3286.    fprintf(stderr, "fopen: %s: %s\n", idf, sys_errlist[errno]);
  3287.    exit(1);
  3288.    }
  3289.    fprintf(fd, "%d\n", (int)getpid());
  3290.    fclose(fd);
  3291.  
  3292.    /* open monitor device */
  3293.    if((pd = open(argv[1], O_RDWR | O_NDELAY)) < 0) {
  3294.    fprintf(stderr, "open: %s: %s\n", argv[1], sys_errlist[errno]);
  3295.    exit(1);
  3296.    }
  3297.  
  3298.    /* daemon is alive */
  3299.    openlog("upsd", LOG_PID, LOG_DAEMON);
  3300.    syslog(LOG_INFO, "daemon started");
  3301.  
  3302.    /* signal reaction */
  3303.    (void)signal(SIGTERM, upsterm);
  3304.  
  3305.    /* monitor device */
  3306.    while(1) {
  3307.    /* clear bits */
  3308.    if(ioctl(pd, TIOCMSET, &zero) < 0) {
  3309.     fprintf(stderr, "ioctl: %s\n", sys_errlist[errno]);
  3310.     exit(1);
  3311.    }
  3312.  
  3313.    /* get device status */
  3314.    if(ioctl(pd, TIOCMGET, &status) < 0) {
  3315.     fprintf(stderr, "ioctl: %s\n", sys_errlist[errno]);
  3316.     exit(1);
  3317.    }
  3318.  
  3319.    /* determin status */
  3320.    d5 = status & 0x20;
  3321.    d6 = status & 0x40;
  3322.    d7 = status & 0x80;
  3323.  
  3324.    /* power up */
  3325.    if(!(d7 + d5)) {
  3326.     if(!pow) {
  3327.      syslog(LOG_CRIT, "power up");
  3328.      pow = 1;
  3329.     }
  3330.    /* power down */
  3331.    } else {
  3332.     if(pow) {
  3333.      syslog(LOG_CRIT, "power down");
  3334.      pow = 0;
  3335.     }
  3336.    }
  3337.  
  3338.    /* battery low */
  3339.    if(!d6 && !low) {
  3340.     syslog(LOG_ALERT, "battery low");
  3341.     low = 1;
  3342.  
  3343.     /* down ups */
  3344.     if(!pow) {
  3345.      upsdown(pd);
  3346.     }
  3347.    }
  3348.  
  3349.    /* battery ok */
  3350.    if(d6 && low) {
  3351.     syslog(LOG_CRIT, "battery ok");
  3352.     low = 0;
  3353.    }
  3354.  
  3355.    sleep(1);
  3356.    }
  3357.  
  3358.    /* not reached */
  3359.    return 0;
  3360.   }
  3361.  
  3362.   void upsterm() {
  3363.    /* log termination message */
  3364.    syslog(LOG_INFO, "daemon terminated");
  3365.  
  3366.    /* remove pid file */
  3367.    unlink(idf);
  3368.  
  3369.    exit(0);
  3370.   }
  3371.  
  3372.   void upsdown(int pd) {
  3373.    /* log shutdown message */
  3374.    syslog(LOG_ALERT, "system is going down");
  3375.  
  3376.    /* remove pid file */
  3377.    unlink(idf);
  3378.  
  3379.    /* save our filesystem */
  3380.    system("/bin/sync");
  3381.    system("/bin/sync");
  3382.    system("/bin/sync");
  3383.  
  3384.    /* shutdown ups */
  3385.    status = TIOCM_DTR;
  3386.    if(ioctl(pd, TIOCMSET, &status) < 0) {
  3387.    fprintf(stderr, "ioctl: %s\n", sys_errlist[errno]);
  3388.    exit(1);
  3389.    }
  3390.  
  3391.    /* wait and then run script */
  3392.    sleep(wait);
  3393.    system(scr);
  3394.   }
  3395.   # Slavik Terletsky      # University "Lvivska Poytechnika" #
  3396.   # Network Administrator # mailto:ts@polynet.lviv.ua        #
  3397.  
  3398.   9.  How to shutdown other machines on the same UPS
  3399.  
  3400.   Some people (myself included) have several computers running Linux
  3401.   connected to one UPS.  One computer monitors the UPS and needs to get
  3402.   the other computers to shut down when the power goes out.
  3403.  
  3404.   We assume the computers can communicate over a network.  Call the
  3405.   computer that monitors the UPS the master and the other computers the
  3406.   slaves.
  3407.  
  3408.   In the old days this required some fancy programming.
  3409.  
  3410.   These days, the best thing to do is to pick up either the
  3411.   powerd-2.0.tar.gz package or the upsd-1.0.tgz package (see section
  3412.   ``Software''), and follow the instructions.  Both are able to run on
  3413.   the slaves in a mode where they connect over the network to a powerd
  3414.   or upsd process running on the master to query the status of the UPS.
  3415.   Some of the APC specific packages seem to have this ability too.
  3416.  
  3417.   Note, though, that if your network is insecure, you might want to add
  3418.   a little security to this, lest someone spoof the slave powerd
  3419.   processes into thinking that the power is out.
  3420.  
  3421.   Another possibility is to go for SNMP (Simple Network Management
  3422.   Protocol).  Detailing the use of SNMP is beyond the scope of this
  3423.   document, not to mention currently being beyond me.
  3424.  
  3425.