def connect(self, attempts=<NUM_LIT:20>, delay=<NUM_LIT:0.5>):
<EOL>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)<EOL>with closing(sock):<EOL><INDENT>sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, <NUM_LIT:1>)<EOL>discover_packet = build_packet(REQ_GATEWAY,<EOL>ALL_BULBS, ALL_BULBS, '<STR_LIT>',<EOL>protocol=DISCOVERY_PROTOCOL)<EOL>for _, ok in _retry(self.gateway_found_event, attempts, delay):<EOL><INDENT>sock.sendto(discover_packet, BROADCAST_ADDRESS)<EOL><DEDENT><DEDENT>if not ok:<EOL><INDENT>raise ConnectException('<STR_LIT>')<EOL><DEDENT>self.callbacks.put(EVENT_DISCOVERED)<EOL>for _, ok in _retry(self.sender.is_connected, <NUM_LIT:1>, <NUM_LIT:3>):<EOL><INDENT>self.sender.put(self.gateway)<EOL><DEDENT>if not ok:<EOL><INDENT>raise ConnectException('<STR_LIT>')<EOL><DEDENT>self.callbacks.put(EVENT_CONNECTED)<EOL>for _, ok in _retry(self.bulbs_found_event, attempts, delay):<EOL><INDENT>self.send(REQ_GET_LIGHT_STATE, ALL_BULBS, '<STR_LIT>')<EOL><DEDENT>if not ok:<EOL><INDENT>raise ConnectException('<STR_LIT>' % (<EOL>len(self.bulbs), self.num_bulbs))<EOL><DEDENT>self.callbacks.put(EVENT_BULBS_FOUND)<EOL>
Connects to a gateway, blocking until a connection is made and bulbs
are found.

Step 1: send a gateway discovery packet to the broadcast address, wait
until we've received some info about the gateway.

Step 2: connect to a discovered gateway, wait until the connection has
been completed.

Step 3: ask for info about bulbs, wait until we've found the number of
bulbs we expect.

Raises a ConnectException if any of the steps fail.