def __init__(self, callback, args): self._proxy_id, self._proxy_secret = read_or_make_config() logging.info('I am proxy \'%s\'', self._proxy_id) self._args = args self._exiting = False self._events = Queue.Queue() self._events_thread = threading.Thread(target=self._post_events_loop) self._events_thread.daemon = True self._events_thread.start() self._callback = callback if args.local: self._websocket_connection = None self._websocket_thread = threading.Thread(target=self._local_websocket) self._websocket_thread.start() else: self._pusher = Pusher(public_creds.pusher_key, auth_callback=self._pusher_auth_callback, log_level=logging.ERROR) self._pusher.connection.bind( 'pusher:connection_established', self._connect_handler) self._pusher.connect()
def main(): pusher = Pusher(creds.pusher_key) ser = serial.Serial(find_arduino(), 9600) def sendToArduino(message): print message ser.write(message) def callback(data): data = json.loads(data) print data message = "%d%d\n" % (1 if data["mode"] else 0, data["num"]) sendToArduino(message) def connect_handler(data): channel = pusher.subscribe('test') channel.bind('event', callback) pusher.connection.bind('pusher:connection_established', connect_handler) pusher.connect() pusher.connection.join()
def connect_to_pusher(self): print 'setting up pusher' self.pusher_client = Pusher(PUSHER_CLIENT_KEY, secure=True) self.pusher_client.connection.bind( 'pusher:connection_established', self.subscribe_on_pusher) self.pusher_client.connect()
class Scene(object): """ Dots on a.....strip... """ def __init__(self): self.dots = [] self.pusher_thread = threading.Thread(target=self.connect_to_pusher) self.pusher_thread.start() self.position = 0 self.cleanup() def connect_to_pusher(self): print 'setting up pusher' self.pusher_client = Pusher(PUSHER_CLIENT_KEY, secure=True) self.pusher_client.connection.bind( 'pusher:connection_established', self.subscribe_on_pusher) self.pusher_client.connect() def subscribe_on_pusher(self, data): print 'pusher connected' self.pusher_channel = self.pusher_client.subscribe('pa_channel') self.pusher_channel.bind('pa_event', self.new_pa) print 'pusher subscribed' def add_dot(self,color): self.dots.append({ 'time': time.time(), 'color': color, 'pos': self.position }) self.position = (self.position + 1) % 60 def cleanup(self): threading.Timer(0.25, self.cleanup).start() if len(self.dots) <= 0: return if self.last_dot.get('expired', False): self.dots = self.dots[1:] @property def last_dot(self): last = self.dots[0] last['expired'] = (time.time() - last['time']) > 15 return last def new_pa(self, data_str): try: data = json.loads(data_str) if data.get('is_retrospective', False): self.add_dot(RETRO_COLOR) else: self.add_dot(PRO_COLOR) except Exception as err: print err @property def pixels(self): pixel_dots = [] for dot in self.dots: age = float(time.time() - dot['time']) amp = self.amplitude(age) old_c = dot['color'] new_c = tuple([int(amp*c) for c in old_c]) pixel_dots.append({'pos':dot['pos'], 'color':new_c}) return pixel_dots def amplitude(self, time): amp = 0.5*math.e**(-((time-PULSE_DELAY)/PULSE_LENGTH)**2.0) amp += 0.5*math.e**(-(time/DECAY_TIME)**3.0) return amp def render_to(self, renderer, moment): for pix in self.pixels: renderer.set_pixel(pix['pos'], pix['color']) return
global pusher # ugh pin = 3 GPIO.setmode(GPIO.BOARD) GPIO.setup(pin, GPIO.OUT, initial=True) try: def buzz(data): GPIO.output(pin, False) print 'Door open' time.sleep(1) GPIO.output(pin, True) print 'Door shut!' time.sleep(5) def bind_to_channel(data): channel = pusher.subscribe('doorbell') channel.bind('buzz', buzz) pusher = Pusher(os.environ['PUSHER_KEY']) pusher.connection.bind('pusher:connection_established', bind_to_channel) pusher.connect() while True: time.sleep(1) except: print sys.exc_info()[0] GPIO.cleanup()
class PushRPC(object): """Wrapper for pusher integration.""" # pylint: disable=too-many-instance-attributes def __init__(self, callback, args): self._proxy_id, self._proxy_secret = read_or_make_config() logging.info('I am proxy \'%s\'', self._proxy_id) self._args = args self._exiting = False self._events = Queue.Queue() self._events_thread = threading.Thread(target=self._post_events_loop) self._events_thread.daemon = True self._events_thread.start() self._callback = callback if args.local: self._websocket_connection = None self._websocket_thread = threading.Thread(target=self._local_websocket) self._websocket_thread.start() else: self._pusher = Pusher(public_creds.pusher_key, auth_callback=self._pusher_auth_callback, log_level=logging.ERROR) self._pusher.connection.bind( 'pusher:connection_established', self._connect_handler) self._pusher.connect() def _local_websocket(self): """Connect to local websocket server.""" self._websocket_connection = websocket.create_connection( "ws://localhost:%d/" % simple_pusher.WEBSOCKET_PORT) request = json.dumps({'channel': 'private-%s' % self._proxy_id}) self._websocket_connection.send(request) while True: result = self._websocket_connection.recv() self._callback_handler(result) def _pusher_auth_callback(self, socket_id, channel_name): params = {'socket_id': socket_id, 'channel_name': channel_name} response = self._make_request(APPENGINE_ADDRESS, AUTH_PATH, params=params) response = response.json() return response['auth'] def _make_request(self, server, path, method='GET', **kwargs): """Make a request to the server with this proxy's auth.""" response = requests.request( method, server + path, auth=(self._proxy_id, self._proxy_secret), headers={'content-type': 'application/json', 'awesomation-proxy': 'true'}, **kwargs) response.raise_for_status() return response def _connect_handler(self, _): channel_name = 'private-%s' % self._proxy_id channel = self._pusher.subscribe(channel_name) channel.bind('events', self._callback_handler) def _callback_handler(self, data): """Callback for when messages are recieved from pusher.""" try: events = json.loads(data) except ValueError: logging.error('Error parsing message', exc_info=sys.exc_info()) return # pylint: disable=broad-except try: self._callback(events) except Exception: logging.error('Error running push callback', exc_info=sys.exc_info()) def send_event(self, event): self._events.put(event) def _get_batch_of_events(self, max_size=20): """Retrieve as many events from queue as possible without blocking.""" events = [] while len(events) < max_size: try: # First time round we should wait (when list is empty) block = len(events) == 0 event = self._events.get(block) # To break out of this thread, we inject a None event in stop() if event is None: return None events.append(event) except Queue.Empty: break assert events return events def _post_events_loop(self): """Send batched of events to server in a loop.""" logging.info('Starting events thread.') while not self._exiting: events = self._get_batch_of_events() if events is None: break # pylint: disable=broad-except try: self._post_events_once(events) except Exception: logging.error('Exception sending events to server', exc_info=sys.exc_info()) logging.info('Exiting events thread.') def _post_events_once(self, events): """Send list of events to server.""" logging.info('Posting %d events to server', len(events)) try: server_address = LOCAL_ADDRESS if self._args.local else APPENGINE_ADDRESS self._make_request(server_address, EVENT_PATH, method='POST', data=json.dumps(events)) except: logging.error('Posting events failed', exc_info=sys.exc_info()) def stop(self): """Stop various threads and connections.""" self._exiting = True self._events.put(None) self._events_thread.join() if self._args.local: self._websocket_connection.close() self._websocket_thread.join() else: self._pusher.disconnect()
class Scene(object): """ Dots on a.....strip... """ def __init__(self): self.dots = [] self.pusher_thread = threading.Thread(target=self.connect_to_pusher) self.pusher_thread.start() self.cleanup() def connect_to_pusher(self): print 'setting up pusher' self.pusher_client = Pusher(PUSHER_CLIENT_KEY, secure=True) self.pusher_client.connection.bind( 'pusher:connection_established', self.subscribe_on_pusher) self.pusher_client.connect() def subscribe_on_pusher(self, data): print 'pusher connected' self.pusher_channel = self.pusher_client.subscribe('pa_channel') self.pusher_channel.bind('pa_event', self.new_pa) print 'pusher subscribed' def add_dot(self,color): self.dots.append({ 'time': time.time(), 'color': color, }) def new_pa(self, data_str): try: data = json.loads(data_str) if data.get('is_retrospective', False): self.add_dot(RETRO_COLOR) else: self.add_dot(PRO_COLOR) except Exception as err: print err def pixel_pair(self, dot): age = time.time() - dot['time'] b_pos = int(30*min(age/(2.0*PULSE_DELAY),1.0)) t_pos = int(60-30*min(age/(2.0*PULSE_DELAY),1.0)) color = self.pixel_color(dot['color'], dot['time']) return [ dict(dot, color=color, pos=b_pos), dict(dot, color=color, pos=t_pos) ] def pixel_color(self, base_color,time): amp = 0.3+0.7*math.e**(-((time-PULSE_DELAY)/PULSE_LENGTH)**2.0) return tuple([int(amp*c) for c in base_color]) @property def pixels(self): pixel_dots = [] for dot in self.dots: pixel_dots += self.pixel_pair(dot) return pixel_dots def render_to(self, renderer, moment): for pix in self.pixels: renderer.set_pixel(pix['pos'], pix['color']) return def cleanup(self): threading.Timer(0.25, self.cleanup).start() if len(self.dots) <= 0: return if self.last_dot.get('expired', False): self.dots = self.dots[1:] @property def last_dot(self): last = self.dots[0] last['expired'] = (time.time() - last['time']) > 3*PULSE_DELAY return last