#!/usr/bin/env python

from xbee import ZigBee
import serial
import datetime
import logging
import sys
import os
import pickle

class XBeeGateway:

    def initialize(self):
        print "Setup"
        self.callbacks = []

    def register_callback(self, callback):
        self.callbacks.push()

    def setup(self):
        print "Init XBeeGateway"
        ser_port = '/dev/ttyUSB0'
        baud_rate = 9600
        try:
            ser = serial.Serial(ser_port, baud_rate)
            xbee = ZigBee(ser, escaped=True)
        except serial.serialutil.SerialException as e:
            print "Serial Error: ", e
            logging.warning("Serial error")
            logging.warning(str(e))
            sys.exit(1)

    def begin(self):
        while True:
            xbee_frame = xbee.wait_read_frame()
            data = {
                    "timestamp": datetime.datetime.now(),
                    "xbee_frame": xbee_frame
                    }
            d = pickle.dumps(data)

            s = "[" + str(datetime.datetime.now()) + "] " + "Published xbee frame"
            logging.info(s)

            for callback in callbacks:
                callback(d)


if __name__ == "__main__":
    xbg = XBeeGateway()
    xbg.setup()
    xbg.begin()

@@ -119,16 +119,28 @@
 t pickle
+%0Aimport time
 %0A%0Aclass 
@@ -165,18 +165,16 @@
 def 
+__
 init
-ialize
+__
 (sel
@@ -298,13 +298,23 @@
 cks.
-push(
+append(callback
 )%0A%0A 
@@ -734,16 +734,17 @@
 xit(1)%0A%0A
+%0A
     def 
@@ -841,108 +841,283 @@
    d
-ata = %7B%0A                    %22timestamp%22: datetime.datetime.now(),%0A                    %22xbee_frame%22: 
+ = self.process_packet(xbee_frame)%0A            for callback in self.callbacks:%0A                callback(d)%0A%0A    def begin_fake(self):%0A        xbee_frame = pickle.load( open( %22save.p%22, %22rb%22 ) )%0A        while True:%0A            time.sleep(1)%0A            d = self.process_packet(
 xbee
@@ -1122,16 +1122,17 @@
 ee_frame
+)
 %0A       
@@ -1140,136 +1140,222 @@
     
-        %7D%0A            d = pickle.dumps(data)%0A%0A            s = %22%5B%22 + str(datetime.datetime.now()) + %22%5D %22 + %22Published
+for callback in self.callbacks:%0A                callback(d)%0A%0A    def process_packet(self, xbee_frame):%0A        data = %7B%0A                %22timestamp%22: datetime.datetime.now(),%0A                %22xbee_frame%22:
  xbee
- 
+_
 frame
-%22
 %0A   
@@ -1367,148 +1367,254 @@
     
-logging.info(s)%0A%0A            for callback in callbacks:%0A                callback(d)%0A%0A%0Aif __name__ == %22__main__%22:%0A    xbg = XBeeGateway()%0A   
+   %7D%0A        return pickle.dumps(data)%0A%0Aif __name__ == %22__main__%22:%0A    def print_data(d):%0A        print %22Got data%22%0A        data = pickle.loads(d)%0A        print data%5B'timestamp'%5D%0A%0A    xbg = XBeeGateway()%0A    xbg.register_callback(print_data)%0A    #
  xbg
@@ -1635,11 +1635,16 @@
 bg.begin
+_fake
 ()%0A

Fix gateway errors