2 * Copyright (c) 1992, 1993, 1995 Eugene W. Stark
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by Eugene W. Stark.
16 * 4. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY EUGENE W. STARK (THE AUTHOR) ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
23 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * $FreeBSD: src/sys/i386/isa/tw.c,v 1.38 2000/01/29 16:00:32 peter Exp $
32 * $DragonFly: src/sys/dev/misc/tw/tw.c,v 1.12 2005/06/11 00:27:09 dillon Exp $
39 * Driver configuration parameters
43 * Time for 1/2 of a power line cycle, in microseconds.
44 * Change this to 10000 for 50Hz power. Phil Sampson
45 * (vk2jnt@gw.vk2jnt.ampr.org OR sampson@gidday.enet.dec.com)
46 * reports that this works (at least in Australia) using a
47 * TW7223 module (a local version of the TW523).
49 #define HALFCYCLE 8333 /* 1/2 cycle = 8333us at 60Hz */
52 * Undefine the following if you don't have the high-resolution "microtime"
53 * routines (leave defined for FreeBSD, which has them).
58 * End of driver configuration parameters
62 * FreeBSD Device Driver for X-10 POWERHOUSE (tm)
63 * Two-Way Power Line Interface, Model #TW523
65 * written by Eugene W. Stark (stark@cs.sunysb.edu)
70 * The TW523 is a carrier-current modem for home control/automation purposes.
77 * (201) 784-9700 or 1-800-526-0027
79 * X-10 Home Controls Inc.
80 * 1200 Aerowood Drive, Unit 20
81 * Mississauga, Ontario
82 * (416) 624-4446 or 1-800-387-3346
84 * The TW523 is designed for communications using the X-10 protocol,
85 * which is compatible with a number of home control systems, including
86 * Radio Shack "Plug 'n Power(tm)" and Stanley "Lightmaker(tm)."
87 * I bought my TW523 from:
89 * Home Control Concepts
90 * 9353-C Activity Road
94 * They supplied me with the TW523 (which has an RJ-11 four-wire modular
95 * telephone connector), a modular cable, an RJ-11 to DB-25 connector with
96 * internal wiring, documentation from X-10 on the TW523 (very good),
97 * an instruction manual by Home Control Concepts (not very informative),
98 * and a floppy disk containing binary object code of some demonstration/test
99 * programs and of a C function library suitable for controlling the TW523
100 * by an IBM PC under MS-DOS (not useful to me other than to verify that
101 * the unit worked). I suggest saving money and buying the bare TW523
102 * rather than the TW523 development kit (what I bought), because if you
103 * are running FreeBSD you don't really care about the DOS binaries.
105 * The interface to the TW-523 consists of four wires on the RJ-11 connector,
106 * which are jumpered to somewhat more wires on the DB-25 connector, which
107 * in turn is intended to plug into the PC parallel printer port. I dismantled
108 * the DB-25 connector to find out what they had done:
110 * Signal RJ-11 pin DB-25 pin(s) Parallel Port
111 * Transmit TX 4 (Y) 2, 4, 6, 8 Data out
112 * Receive RX 3 (G) 10, 14 -ACK, -AutoFeed
113 * Common 2 (R) 25 Common
114 * Zero crossing 1 (B) 17 or 12 -Select or +PaperEnd
116 * NOTE: In the original cable I have (which I am still using, May, 1997)
117 * the Zero crossing signal goes to pin 17 (-Select) on the parallel port.
118 * In retrospect, this doesn't make a whole lot of sense, given that the
119 * -Select signal propagates the other direction. Indeed, some people have
120 * reported problems with this, and have had success using pin 12 (+PaperEnd)
121 * instead. This driver searches for the zero crossing signal on either
122 * pin 17 or pin 12, so it should work with either cable configuration.
123 * My suggestion would be to start by making the cable so that the zero
124 * crossing signal goes to pin 12 on the parallel port.
126 * The zero crossing signal is used to synchronize transmission to the
127 * zero crossings of the AC line, as detailed in the X-10 documentation.
128 * It would be nice if one could generate interrupts with this signal,
129 * however one needs interrupts on both the rising and falling edges,
130 * and the -ACK signal to the parallel port interrupts only on the falling
131 * edge, so it can't be done without additional hardware.
133 * In this driver, the transmit function is performed in a non-interrupt-driven
134 * fashion, by polling the zero crossing signal to determine when a transition
135 * has occurred. This wastes CPU time during transmission, but it seems like
136 * the best that can be done without additional hardware. One problem with
137 * the scheme is that preemption of the CPU during transmission can cause loss
138 * of sync. The driver tries to catch this, by noticing that a long delay
139 * loop has somehow become foreshortened, and the transmission is aborted with
140 * an error return. It is up to the user level software to handle this
141 * situation (most likely by retrying the transmission).
144 #include <sys/param.h>
145 #include <sys/systm.h>
146 #include <sys/conf.h>
147 #include <sys/kernel.h>
149 #include <sys/syslog.h>
150 #include <sys/select.h>
151 #include <sys/poll.h>
152 #include <sys/thread2.h>
155 #include <sys/time.h>
156 #endif /* HIRESTIME */
158 #include <bus/isa/i386/isa_device.h>
161 * Transmission is done by calling write() to send three byte packets of data.
162 * The first byte contains a four bit house code (0=A to 15=P).
163 * The second byte contains five bit unit/key code (0=unit 1 to 15=unit 16,
164 * 16=All Units Off to 31 = Status Request). The third byte specifies
165 * the number of times the packet is to be transmitted without any
166 * gaps between successive transmissions. Normally this is 2, as per
167 * the X-10 documentation, but sometimes (e.g. for bright and dim codes)
168 * it can be another value. Each call to write can specify an arbitrary
169 * number of data bytes. An incomplete packet is buffered until a subsequent
170 * call to write() provides data to complete it. At most one packet will
171 * actually be processed in any call to write(). Successive calls to write()
172 * leave a three-cycle gap between transmissions, per the X-10 documentation.
174 * Reception is done using read().
175 * The driver produces a series of three-character packets.
176 * In each packet, the first character consists of flags,
177 * the second character is a four bit house code (0-15),
178 * and the third character is a five bit key/function code (0-31).
179 * The flags are the following:
182 #define TW_RCV_LOCAL 1 /* The packet arrived during a local transmission */
183 #define TW_RCV_ERROR 2 /* An invalid/corrupted packet was received */
186 * IBM PC parallel port definitions relevant to TW523
189 #define tw_data 0 /* Data to tw523 (R/W) */
191 #define tw_status 1 /* Status of tw523 (R) */
192 #define TWS_RDATA 0x40 /* tw523 receive data */
193 #define TWS_OUT 0x20 /* pin 12, out of paper */
195 #define tw_control 2 /* Control tw523 (R/W) */
196 #define TWC_SYNC 0x08 /* tw523 sync (pin 17) */
197 #define TWC_ENA 0x10 /* tw523 interrupt enable */
200 * Miscellaneous defines
203 #define TWUNIT(dev) (minor(dev)) /* Extract unit number from device */
205 static int twprobe(struct isa_device *idp);
206 static int twattach(struct isa_device *idp);
208 struct isa_driver twdriver = {
209 twprobe, twattach, "tw"
212 static d_open_t twopen;
213 static d_close_t twclose;
214 static d_read_t twread;
215 static d_write_t twwrite;
216 static d_poll_t twpoll;
218 #define CDEV_MAJOR 19
219 static struct cdevsw tw_cdevsw = {
221 /* maj */ CDEV_MAJOR,
233 /* strategy */ nostrategy,
239 * Software control structure for TW523
242 #define TWS_XMITTING 1 /* Transmission in progress */
243 #define TWS_RCVING 2 /* Reception in progress */
244 #define TWS_WANT 4 /* A process wants received data */
245 #define TWS_OPEN 8 /* Is it currently open? */
247 #define TW_SIZE 3*60 /* Enough for about 10 sec. of input */
248 #define TW_MIN_DELAY 1500 /* Ignore interrupts of lesser latency */
250 static struct tw_sc {
251 u_int sc_port; /* I/O Port */
252 u_int sc_state; /* Current software control state */
253 struct selinfo sc_selp; /* Information for select() */
254 u_char sc_xphase; /* Current state of sync (for transmitter) */
255 u_char sc_rphase; /* Current state of sync (for receiver) */
256 u_char sc_flags; /* Flags for current reception */
257 short sc_rcount; /* Number of bits received so far */
258 int sc_bits; /* Bits received so far */
259 u_char sc_pkt[3]; /* Packet not yet transmitted */
260 short sc_pktsize; /* How many bytes in the packet? */
261 u_char sc_buf[TW_SIZE]; /* We buffer our own input */
262 int sc_nextin; /* Next free slot in circular buffer */
263 int sc_nextout; /* First used slot in circular buffer */
264 /* Callout for canceling our abortrcv timeout */
265 struct callout abortrcv_ch;
267 int sc_xtimes[22]; /* Times for bits in current xmit packet */
268 int sc_rtimes[22]; /* Times for bits in current rcv packet */
269 int sc_no_rcv; /* number of interrupts received */
270 #define SC_RCV_TIME_LEN 128
271 int sc_rcv_time[SC_RCV_TIME_LEN]; /* usec time stamp on interrupt */
272 #endif /* HIRESTIME */
275 static int tw_zcport; /* offset of port for zero crossing signal */
276 static int tw_zcmask; /* mask for the zero crossing signal */
278 static void twdelay25(void);
279 static void twdelayn(int n);
280 static void twsetuptimes(int *a);
281 static int wait_for_zero(struct tw_sc *sc);
282 static int twputpkt(struct tw_sc *sc, u_char *p);
283 static ointhand2_t twintr;
284 static int twgetbytes(struct tw_sc *sc, u_char *p, int cnt);
285 static timeout_t twabortrcv;
286 static int twsend(struct tw_sc *sc, int h, int k, int cnt);
287 static int next_zero(struct tw_sc *sc);
288 static int twchecktime(int target, int tol);
289 static void twdebugtimes(struct tw_sc *sc);
292 * Counter value for delay loop.
293 * It is adjusted by twprobe so that the delay loop takes about 25us.
296 #define TWDELAYCOUNT 161 /* Works on my 486DX/33 */
297 static int twdelaycount;
300 * Twdelay25 is used for very short delays of about 25us.
301 * It is implemented with a calibrated delay loop, and should be
302 * fairly accurate ... unless we are preempted by an interrupt.
304 * We use this to wait for zero crossings because the X-10 specs say we
305 * are supposed to assert carrier within 25us when one happens.
306 * I don't really believe we can do this, but the X-10 devices seem to be
310 static void twdelay25(void)
313 for(cnt = twdelaycount; cnt; cnt--); /* Should take about 25us */
317 * Twdelayn is used to time the length of the 1ms carrier pulse.
318 * This is not very critical, but if we have high-resolution time-of-day
319 * we check it every apparent 200us to make sure we don't get too far off
320 * if we happen to be interrupted during the delay.
323 static void twdelayn(int n)
331 #endif /* HIRESTIME */
339 if(d >= 0 && d < 1000000) return;
341 #endif /* HIRESTIME */
345 static int twprobe(idp)
346 struct isa_device *idp;
352 sc.sc_port = idp->id_iobase;
353 /* Search for the zero crossing signal at ports, bit combinations. */
354 tw_zcport = tw_control;
355 tw_zcmask = TWC_SYNC;
356 sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
357 if(wait_for_zero(&sc) < 0) {
358 tw_zcport = tw_status;
360 sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
362 if(wait_for_zero(&sc) < 0)
365 * Iteratively check the timing of a few sync transitions, and adjust
366 * the loop delay counter, if necessary, to bring the timing reported
367 * by wait_for_zero() close to HALFCYCLE. Give up if anything
368 * ridiculous happens.
370 if(twdelaycount == 0) { /* Only adjust timing for first unit */
371 twdelaycount = TWDELAYCOUNT;
372 for(tries = 0; tries < 10; tries++) {
373 sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
374 if(wait_for_zero(&sc) >= 0) {
375 d = wait_for_zero(&sc);
376 if(d <= HALFCYCLE/100 || d >= HALFCYCLE*100) {
380 twdelaycount = (twdelaycount * d)/HALFCYCLE;
385 * Now do a final check, just to make sure
387 sc.sc_xphase = inb(idp->id_iobase + tw_zcport) & tw_zcmask;
388 if(wait_for_zero(&sc) >= 0) {
389 d = wait_for_zero(&sc);
390 if(d <= (HALFCYCLE * 110)/100 && d >= (HALFCYCLE * 90)/100) return(8);
395 static int twattach(idp)
396 struct isa_device *idp;
401 idp->id_ointr = twintr;
402 sc = &tw_sc[unit = idp->id_unit];
403 sc->sc_port = idp->id_iobase;
406 callout_init(&sc->abortrcv_ch);
407 cdevsw_add(&tw_cdevsw, -1, unit);
408 make_dev(&tw_cdevsw, unit, 0, 0, 0600, "tw%d", unit);
412 int twopen(dev, flag, mode, td)
418 struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
421 if(sc->sc_state == 0) {
422 sc->sc_state = TWS_OPEN;
423 sc->sc_nextin = sc->sc_nextout = 0;
425 outb(sc->sc_port+tw_control, TWC_ENA);
431 int twclose(dev, flag, mode, td)
437 struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
441 outb(sc->sc_port+tw_control, 0);
446 int twread(dev, uio, ioflag)
452 struct tw_sc *sc = &tw_sc[TWUNIT(dev)];
456 cnt = MIN(uio->uio_resid, 3);
457 if((error = twgetbytes(sc, buf, cnt)) == 0) {
458 error = uiomove(buf, cnt, uio);
464 int twwrite(dev, uio, ioflag)
470 int house, key, reps;
474 sc = &tw_sc[TWUNIT(dev)];
476 * Note: Although I had intended to allow concurrent transmitters,
477 * there is a potential problem here if two processes both write
478 * into the sc_pkt buffer at the same time. The following code
479 * is an additional critical section that needs to be synchronized.
482 cnt = MIN(3 - sc->sc_pktsize, uio->uio_resid);
483 error = uiomove(&(sc->sc_pkt[sc->sc_pktsize]), cnt, uio);
488 sc->sc_pktsize += cnt;
489 if(sc->sc_pktsize < 3) { /* Only transmit 3-byte packets */
495 * Collect house code, key code, and rep count, and check for sanity.
497 house = sc->sc_pkt[0];
499 reps = sc->sc_pkt[2];
500 if(house >= 16 || key >= 32) {
505 * Synchronize with the receiver operating in the bottom half, and
506 * also with concurrent transmitters.
507 * We don't want to interfere with a packet currently being received,
508 * and we would like the receiver to recognize when a packet has
509 * originated locally.
511 while(sc->sc_state & (TWS_RCVING | TWS_XMITTING)) {
512 error = tsleep((caddr_t)sc, PCATCH, "twwrite", 0);
518 sc->sc_state |= TWS_XMITTING;
520 * Everything looks OK, let's do the transmission.
522 crit_exit(); /* Enable interrupts because this takes a LONG time */
523 error = twsend(sc, house, key, reps);
525 sc->sc_state &= ~TWS_XMITTING;
528 if(error) return(EIO);
533 * Determine if there is data available for reading
536 int twpoll(dev, events, td)
544 sc = &tw_sc[TWUNIT(dev)];
546 /* XXX is this correct? the original code didn't test select rw mode!! */
547 if (events & (POLLIN | POLLRDNORM)) {
548 if(sc->sc_nextin != sc->sc_nextout)
549 revents |= events & (POLLIN | POLLRDNORM);
551 selrecord(td, &sc->sc_selp);
561 #define X10_START_LENGTH 4
562 static char X10_START[] = { 1, 1, 1, 0 };
565 * Each bit of the 4-bit house code and 5-bit key code
566 * is transmitted twice, once in true form, and then in
567 * complemented form. This is already taken into account
568 * in the following tables.
571 #define X10_HOUSE_LENGTH 8
572 static char X10_HOUSE[16][8] = {
573 { 0, 1, 1, 0, 1, 0, 0, 1 }, /* A = 0110 */
574 { 1, 0, 1, 0, 1, 0, 0, 1 }, /* B = 1110 */
575 { 0, 1, 0, 1, 1, 0, 0, 1 }, /* C = 0010 */
576 { 1, 0, 0, 1, 1, 0, 0, 1 }, /* D = 1010 */
577 { 0, 1, 0, 1, 0, 1, 1, 0 }, /* E = 0001 */
578 { 1, 0, 0, 1, 0, 1, 1, 0 }, /* F = 1001 */
579 { 0, 1, 1, 0, 0, 1, 1, 0 }, /* G = 0101 */
580 { 1, 0, 1, 0, 0, 1, 1, 0 }, /* H = 1101 */
581 { 0, 1, 1, 0, 1, 0, 1, 0 }, /* I = 0111 */
582 { 1, 0, 1, 0, 1, 0, 1, 0 }, /* J = 1111 */
583 { 0, 1, 0, 1, 1, 0, 1, 0 }, /* K = 0011 */
584 { 1, 0, 0, 1, 1, 0, 1, 0 }, /* L = 1011 */
585 { 0, 1, 0, 1, 0, 1, 0, 1 }, /* M = 0000 */
586 { 1, 0, 0, 1, 0, 1, 0, 1 }, /* N = 1000 */
587 { 0, 1, 1, 0, 0, 1, 0, 1 }, /* O = 0100 */
588 { 1, 0, 1, 0, 0, 1, 0, 1 } /* P = 1100 */
591 #define X10_KEY_LENGTH 10
592 static char X10_KEY[32][10] = {
593 { 0, 1, 1, 0, 1, 0, 0, 1, 0, 1 }, /* 01100 => 1 */
594 { 1, 0, 1, 0, 1, 0, 0, 1, 0, 1 }, /* 11100 => 2 */
595 { 0, 1, 0, 1, 1, 0, 0, 1, 0, 1 }, /* 00100 => 3 */
596 { 1, 0, 0, 1, 1, 0, 0, 1, 0, 1 }, /* 10100 => 4 */
597 { 0, 1, 0, 1, 0, 1, 1, 0, 0, 1 }, /* 00010 => 5 */
598 { 1, 0, 0, 1, 0, 1, 1, 0, 0, 1 }, /* 10010 => 6 */
599 { 0, 1, 1, 0, 0, 1, 1, 0, 0, 1 }, /* 01010 => 7 */
600 { 1, 0, 1, 0, 0, 1, 1, 0, 0, 1 }, /* 11010 => 8 */
601 { 0, 1, 1, 0, 1, 0, 1, 0, 0, 1 }, /* 01110 => 9 */
602 { 1, 0, 1, 0, 1, 0, 1, 0, 0, 1 }, /* 11110 => 10 */
603 { 0, 1, 0, 1, 1, 0, 1, 0, 0, 1 }, /* 00110 => 11 */
604 { 1, 0, 0, 1, 1, 0, 1, 0, 0, 1 }, /* 10110 => 12 */
605 { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }, /* 00000 => 13 */
606 { 1, 0, 0, 1, 0, 1, 0, 1, 0, 1 }, /* 10000 => 14 */
607 { 0, 1, 1, 0, 0, 1, 0, 1, 0, 1 }, /* 01000 => 15 */
608 { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 }, /* 11000 => 16 */
609 { 0, 1, 0, 1, 0, 1, 0, 1, 1, 0 }, /* 00001 => All Units Off */
610 { 0, 1, 0, 1, 0, 1, 1, 0, 1, 0 }, /* 00011 => All Units On */
611 { 0, 1, 0, 1, 1, 0, 0, 1, 1, 0 }, /* 00101 => On */
612 { 0, 1, 0, 1, 1, 0, 1, 0, 1, 0 }, /* 00111 => Off */
613 { 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }, /* 01001 => Dim */
614 { 0, 1, 1, 0, 0, 1, 1, 0, 1, 0 }, /* 01011 => Bright */
615 { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0 }, /* 01101 => All LIGHTS Off */
616 { 0, 1, 1, 0, 1, 0, 1, 0, 1, 0 }, /* 01111 => Extended Code */
617 { 1, 0, 0, 1, 0, 1, 0, 1, 1, 0 }, /* 10001 => Hail Request */
618 { 1, 0, 0, 1, 0, 1, 1, 0, 1, 0 }, /* 10011 => Hail Acknowledge */
619 { 1, 0, 0, 1, 1, 0, 0, 1, 1, 0 }, /* 10101 => Preset Dim 0 */
620 { 1, 0, 0, 1, 1, 0, 1, 0, 1, 0 }, /* 10111 => Preset Dim 1 */
621 { 1, 0, 1, 0, 0, 1, 0, 1, 0, 1 }, /* 11000 => Extended Data (analog) */
622 { 1, 0, 1, 0, 0, 1, 1, 0, 1, 0 }, /* 11011 => Status = on */
623 { 1, 0, 1, 0, 1, 0, 0, 1, 1, 0 }, /* 11101 => Status = off */
624 { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 } /* 11111 => Status request */
628 * Tables for mapping received X-10 code back to house/key number.
631 static short X10_HOUSE_INV[16] = {
632 12, 4, 2, 10, 14, 6, 0, 8,
633 13, 5, 3, 11, 15, 7, 1, 9
636 static short X10_KEY_INV[32] = {
637 12, 16, 4, 17, 2, 18, 10, 19,
638 14, 20, 6, 21, 0, 22, 8, 23,
639 13, 24, 5, 25, 3, 26, 11, 27,
640 15, 28, 7, 29, 1, 30, 9, 31
643 static char *X10_KEY_LABEL[32] = {
672 "Extended Data (analog)",
678 * Transmit a packet containing house code h and key code k
681 #define TWRETRY 10 /* Try 10 times to sync with AC line */
683 static int twsend(sc, h, k, cnt)
688 int port = sc->sc_port;
691 * Make sure we get a reliable sync with a power line zero crossing
693 for(i = 0; i < TWRETRY; i++) {
694 if(wait_for_zero(sc) > 100) goto insync;
696 log(LOG_ERR, "TWXMIT: failed to sync.\n");
701 * Be sure to leave 3 cycles space between transmissions
703 for(i = 6; i > 0; i--)
704 if(next_zero(sc) < 0) return(-1);
706 * The packet is transmitted cnt times, with no gaps.
710 * Transmit the start code
712 for(i = 0; i < X10_START_LENGTH; i++) {
713 outb(port+tw_data, X10_START[i] ? 0xff : 0x00); /* Waste no time! */
715 if(i == 0) twsetuptimes(sc->sc_xtimes);
716 if(twchecktime(sc->sc_xtimes[i], HALFCYCLE/20) == 0) {
717 outb(port+tw_data, 0);
720 #endif /* HIRESTIME */
721 twdelayn(1000); /* 1ms pulse width */
722 outb(port+tw_data, 0);
723 if(next_zero(sc) < 0) return(-1);
726 * Transmit the house code
728 for(i = 0; i < X10_HOUSE_LENGTH; i++) {
729 outb(port+tw_data, X10_HOUSE[h][i] ? 0xff : 0x00); /* Waste no time! */
731 if(twchecktime(sc->sc_xtimes[i+X10_START_LENGTH], HALFCYCLE/20) == 0) {
732 outb(port+tw_data, 0);
735 #endif /* HIRESTIME */
736 twdelayn(1000); /* 1ms pulse width */
737 outb(port+tw_data, 0);
738 if(next_zero(sc) < 0) return(-1);
741 * Transmit the unit/key code
743 for(i = 0; i < X10_KEY_LENGTH; i++) {
744 outb(port+tw_data, X10_KEY[k][i] ? 0xff : 0x00);
746 if(twchecktime(sc->sc_xtimes[i+X10_START_LENGTH+X10_HOUSE_LENGTH],
747 HALFCYCLE/20) == 0) {
748 outb(port+tw_data, 0);
751 #endif /* HIRESTIME */
752 twdelayn(1000); /* 1ms pulse width */
753 outb(port+tw_data, 0);
754 if(next_zero(sc) < 0) return(-1);
761 * Waste CPU cycles to get in sync with a power line zero crossing.
762 * The value returned is roughly how many microseconds we wasted before
763 * seeing the transition. To avoid wasting time forever, we give up after
764 * waiting patiently for 1/4 sec (15 power line cycles at 60 Hz),
765 * which is more than the 11 cycles it takes to transmit a full
769 static int wait_for_zero(sc)
772 int i, old, new, max;
773 int port = sc->sc_port + tw_zcport;
776 max = 10000; /* 10000 * 25us = 0.25 sec */
779 new = inb(port) & tw_zcmask;
791 * Wait for the next zero crossing transition, and if we don't have
792 * high-resolution time-of-day, check to see that the zero crossing
793 * appears to be arriving on schedule.
794 * We expect to be waiting almost a full half-cycle (8.333ms-1ms = 7.333ms).
795 * If we don't seem to wait very long, something is wrong (like we got
796 * preempted!) and we should abort the transmission because
797 * there's no telling how long it's really been since the
798 * last bit was transmitted.
801 static int next_zero(sc)
806 if((d = wait_for_zero(sc)) < 0) {
808 if((d = wait_for_zero(sc)) < 6000 || d > 8500) {
809 /* No less than 6.0ms, no more than 8.5ms */
810 #endif /* HIRESTIME */
811 log(LOG_ERR, "TWXMIT framing error: %d\n", d);
818 * Put a three-byte packet into the circular buffer
819 * Should be called from a critical section.
822 static int twputpkt(sc, p)
828 for(i = 0; i < 3; i++) {
829 next = sc->sc_nextin+1;
830 if(next >= TW_SIZE) next = 0;
831 if(next == sc->sc_nextout) { /* Buffer full */
833 log(LOG_ERR, "TWRCV: Buffer overrun\n");
837 sc->sc_buf[sc->sc_nextin] = *p++;
838 sc->sc_nextin = next;
840 if(sc->sc_state & TWS_WANT) {
841 sc->sc_state &= ~TWS_WANT;
842 wakeup((caddr_t)(&sc->sc_buf));
844 selwakeup(&sc->sc_selp);
849 * Get bytes from the circular buffer
850 * Should be called from a critical section.
853 static int twgetbytes(sc, p, cnt)
861 while(sc->sc_nextin == sc->sc_nextout) { /* Buffer empty */
862 sc->sc_state |= TWS_WANT;
863 error = tsleep((caddr_t)(&sc->sc_buf), PCATCH, "twread", 0);
868 *p++ = sc->sc_buf[sc->sc_nextout++];
869 if(sc->sc_nextout >= TW_SIZE) sc->sc_nextout = 0;
875 * Abort reception that has failed to complete in the required time.
882 struct tw_sc *sc = arg;
886 sc->sc_state &= ~TWS_RCVING;
887 /* simply ignore single isolated interrupts. */
888 if (sc->sc_no_rcv > 1) {
889 sc->sc_flags |= TW_RCV_ERROR;
890 pkt[0] = sc->sc_flags;
893 log(LOG_ERR, "TWRCV: aborting (%x, %d)\n", sc->sc_bits, sc->sc_rcount);
901 tw_is_within(int value, int expected, int tolerance)
904 diff = value - expected;
907 if (diff < tolerance)
913 * This routine handles interrupts that occur when there is a falling
914 * transition on the RX input. There isn't going to be a transition
915 * on every bit (some are zero), but if we are smart and keep track of
916 * how long it's been since the last interrupt (via the zero crossing
917 * detect line and/or high-resolution time-of-day routine), we can
918 * reconstruct the transmission without having to poll.
921 static void twintr(unit)
924 struct tw_sc *sc = &tw_sc[unit];
933 * Ignore any interrupts that occur if the device is not open.
935 if(sc->sc_state == 0) return;
936 newphase = inb(port + tw_zcport) & tw_zcmask;
941 * If we aren't currently receiving a packet, set up a new packet
942 * and put in the first "1" bit that has just arrived.
943 * Arrange for the reception to be aborted if too much time goes by.
945 if((sc->sc_state & TWS_RCVING) == 0) {
947 twsetuptimes(sc->sc_rtimes);
948 #endif /* HIRESTIME */
949 sc->sc_state |= TWS_RCVING;
951 if(sc->sc_state & TWS_XMITTING) sc->sc_flags = TW_RCV_LOCAL;
952 else sc->sc_flags = 0;
954 sc->sc_rphase = newphase;
955 /* 3 cycles of silence = 3/60 = 1/20 = 50 msec */
956 callout_reset(&sc->abortrcv_ch, hz / 20, twabortrcv, sc);
957 sc->sc_rcv_time[0] = tv.tv_usec;
961 callout_reset(&sc->abortrcv_ch, hz / 20, twabortrcv, sc);
962 newphase = inb(port + tw_zcport) & tw_zcmask;
964 /* enforce a minimum delay since the last interrupt */
965 delay = tv.tv_usec - sc->sc_rcv_time[sc->sc_no_rcv - 1];
968 if (delay < TW_MIN_DELAY)
971 sc->sc_rcv_time[sc->sc_no_rcv] = tv.tv_usec;
972 if (sc->sc_rcv_time[sc->sc_no_rcv] < sc->sc_rcv_time[0])
973 sc->sc_rcv_time[sc->sc_no_rcv] += 1000000;
978 * The second and third bits are a special case.
980 if (sc->sc_rcount < 3) {
983 tw_is_within(delay, HALFCYCLE, HALFCYCLE / 6)
985 newphase != sc->sc_rphase
991 * Invalid start code -- abort reception.
993 sc->sc_state &= ~TWS_RCVING;
994 sc->sc_flags |= TW_RCV_ERROR;
995 callout_stop(&sc->abortrcv_ch);
996 log(LOG_ERR, "TWRCV: Invalid start code\n");
1001 if(sc->sc_rcount == 3) {
1003 * We've gotten three "1" bits in a row. The start code
1004 * is really 1110, but this might be followed by a zero
1005 * bit from the house code, so if we wait any longer we
1006 * might be confused about the first house code bit.
1007 * So, we guess that the start code is correct and insert
1008 * the trailing zero without actually having seen it.
1009 * We don't change sc_rphase in this case, because two
1010 * bit arrivals in a row preserve parity.
1016 * Update sc_rphase to the current phase before returning.
1018 sc->sc_rphase = newphase;
1023 * Now figure out what the current bit is that just arrived.
1024 * The X-10 protocol transmits each data bit twice: once in
1025 * true form and once in complemented form on the next half
1026 * cycle. So, there will be at least one interrupt per bit.
1027 * By comparing the phase we see at the time of the interrupt
1028 * with the saved sc_rphase, we can tell on which half cycle
1029 * the interrupt occrred. This assumes, of course, that the
1030 * packet is well-formed. We do the best we can at trying to
1031 * catch errors by aborting if too much time has gone by, and
1032 * by tossing out a packet if too many bits arrive, but the
1033 * whole scheme is probably not as robust as if we had a nice
1034 * interrupt on every half cycle of the power line.
1035 * If we have high-resolution time-of-day routines, then we
1036 * can do a bit more sanity checking.
1040 * A complete packet is 22 half cycles.
1042 if(sc->sc_rcount <= 20) {
1044 int bit = 0, last_bit;
1045 if (sc->sc_rcount == 4)
1046 last_bit = 1; /* Start (1110) ends in 10, a 'one' code. */
1048 last_bit = sc->sc_bits & 0x1;
1049 if ( ( (last_bit == 1)
1050 && (tw_is_within(delay, HALFCYCLE * 2, HALFCYCLE / 6)))
1051 || ( (last_bit == 0)
1052 && (tw_is_within(delay, HALFCYCLE * 1, HALFCYCLE / 6))))
1054 else if ( ( (last_bit == 1)
1055 && (tw_is_within(delay, HALFCYCLE * 3, HALFCYCLE / 6)))
1056 || ( (last_bit == 0)
1057 && (tw_is_within(delay, HALFCYCLE * 2, HALFCYCLE / 6))))
1060 sc->sc_flags |= TW_RCV_ERROR;
1061 log(LOG_ERR, "TWRCV: %d cycle after %d bit, delay %d%%\n",
1062 sc->sc_rcount, last_bit, 100 * delay / HALFCYCLE);
1064 sc->sc_bits = (sc->sc_bits << 1) | bit;
1066 sc->sc_bits = (sc->sc_bits << 1)
1067 | ((newphase == sc->sc_rphase) ? 0x0 : 0x1);
1068 #endif /* HIRESTIME */
1071 if(sc->sc_rcount >= 22 || sc->sc_flags & TW_RCV_ERROR) {
1072 if(sc->sc_rcount != 22) {
1073 sc->sc_flags |= TW_RCV_ERROR;
1074 pkt[0] = sc->sc_flags;
1075 pkt[1] = pkt[2] = 0;
1077 pkt[0] = sc->sc_flags;
1078 pkt[1] = X10_HOUSE_INV[(sc->sc_bits & 0x1e0) >> 5];
1079 pkt[2] = X10_KEY_INV[sc->sc_bits & 0x1f];
1081 sc->sc_state &= ~TWS_RCVING;
1083 callout_stop(&sc->abortrcv_ch);
1084 if(sc->sc_flags & TW_RCV_ERROR) {
1085 log(LOG_ERR, "TWRCV: invalid packet: (%d, %x) %c %s\n",
1086 sc->sc_rcount, sc->sc_bits, 'A' + pkt[1], X10_KEY_LABEL[pkt[2]]);
1089 /* log(LOG_ERR, "TWRCV: valid packet: (%d, %x) %c %s\n",
1090 sc->sc_rcount, sc->sc_bits, 'A' + pkt[1], X10_KEY_LABEL[pkt[2]]); */
1093 wakeup((caddr_t)sc);
1097 static void twdebugtimes(struct tw_sc *sc)
1100 for (i = 0; (i < sc->sc_no_rcv) && (i < SC_RCV_TIME_LEN); i++)
1101 log(LOG_ERR, "TWRCV: interrupt %2d: %d\t%d%%\n", i, sc->sc_rcv_time[i],
1102 (sc->sc_rcv_time[i] - sc->sc_rcv_time[(i?i-1:0)])*100/HALFCYCLE);
1107 * Initialize an array of 22 times, starting from the current
1108 * microtime and continuing for the next 21 half cycles.
1109 * We use the times as a reference to make sure transmission
1110 * or reception is on schedule.
1113 static void twsetuptimes(int *a)
1120 for(i = 0; i < 22; i++) {
1123 if(t >= 1000000) t -= 1000000;
1128 * Check the current time against a slot in a previously set up
1129 * timing array, and make sure that it looks like we are still
1133 static int twchecktime(int target, int tol)
1140 d = (target - t) >= 0 ? (target - t) : (t - target);
1141 if(d > 500000) d = 1000000-d;
1142 if(d <= tol && d >= -tol) {
1148 #endif /* HIRESTIME */