Example #1
0
class ValidFakeDatabase:

    # initializes dummy data to return
  def __init__(self):
    self.dateA = datetime.datetime(2013, 8, 4, 12, 30, 45)
	self.dateB = datetime.datetime(1999, 7, 6, 12, 30, 45)
    self.paperA = Paper("12345", "The Health Benefits of the All-Bacon Diet", ["4445", "666", "123"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], "Bacon is actually one of the healthiest foods of all time.  This is an abstract!  For the full article, download the PDF.", "1234", self.dateA, datetime.datetime.now(), "1111", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Alan Turing", "Shia Leboeuf", "Andrew Davidson"])
    self.paperB = Paper("90210", "The Dangers of Coding While Hungry", ["12068", "7797", "4326"], ["Genetics", "Bioinformatics", "Search Engines", "Artificial Intelligence"], " Abstracts never seem to be simple or contain useful information.", "444", self.dateA, datetime.datetime.now(), "6677", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Your Favorite Publisher",["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])
    self.paperC = Paper("666", "The Struggles of Eating a Giordano's Pizza Alone", ["567", "2213", "989"], ["6237", "3177", "432"], "Abstracts are the SparkNotes of the academic world.", "12534434", self.dateB, datetime.datetime.now(), "2345", ["ref1", "ref2", "ref3"], "14000", ["citation link 1", "citation link 2", "citation link 2"], "Prentice Hall", ["Andrew Davidson","William Shakespeare","Edsger Dijkstra"])

    self.authorA = Author("55555", "Shia Leboeuf", "4444", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorB = Author("43216", "Andrew Davidson", "1", ["0", "1"],["The Health Benefits of the All-Bacon Diet", "The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorC = Author("6542", "William Shakespeare", "11542", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorD = Author("64632", "Edsger Dijkstra", "147", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])
    self.authorE = Author("63421", "Alan Turing", "40000", ["2", "1"],["The Struggles of Eating a Giordano's Pizza Alone","The Dangers of Coding While Hungry"],[["Andrew Davidson","William Shakespeare","Edsger Dijkstra"],["Alan Turing", "Shia Leboeuf", "Andrew Davidson"]],[self.dateB,self.dateA])

    self.tagA = Tag("Genetics", "40000", ["0", "1"])
    self.tagB = Tag("Bioinformatics", "12345", ["0", "1"])
    self.tagC = Tag("Search Engines", "5555", ["2", "3"])
    self.tagD = Tag("Artificial Intelligence", "42", ["2", "3"])
    
    self.publisherA = Publisher("1233", "Your Favorite Publisher",0)
    self.publisherB = Publisher("3468", "Prentice Hall",0)
    self.publisherC = Publisher("8372", "Rose-Hulman",0)

    self.userA = User("0","Otis Redding", ["1", "3"],["Andrew Davidson","Jonathan Jenkins"], [self.paperA, self.paperB, self.paperC], [self.authorA, self.authorB, self.authorC], [self.tagA, self.tagC, self.tagB, self.tagD], "45", "005792830123")
Example #2
0
class Rest:

	def __init__(self):
		rospy.init_node('communication_manager',anonymous=False,disable_signals=True)	
		pubsubport = rospy.get_param('~pubsubport')
		self.publisher=Publisher(pubsubport)	
		thread = threading.Thread(target=self.publisher.run, args=())
        	thread.daemon = True                            # Daemonize thread
        	thread.start()
	
	def publish(self,msg):
			actions = msg.data
			print ("Sending to the subscribers the set of actions %s" %str(actions))
			self.publisher.send("actions %s" %str(actions))

	def run(self):

		for topic in rospy.get_param('~forwardedtopics').split(","):
			print ("Communication manager will forward messages regarding the topic %s" %str(topic))
			subtopic="~" + topic
			rospy.Subscriber(subtopic, String, self.publish) 
	
		port = rospy.get_param('~port')
                topicType = rospy.get_param('~topicName')
		
		while not rospy.is_shutdown():			
			httpd = HTTPServer(('0.0.0.0', port),Request_Handler)
			print ("Waiting for a new mission on the port %s messages will be forwarded on the topic %s" %(port,topicType))

			httpd.serve_forever()
Example #3
0
	def __init__(self):
		rospy.init_node('communication_manager',anonymous=False,disable_signals=True)	
		pubsubport = rospy.get_param('~pubsubport')
		self.publisher=Publisher(pubsubport)	
		thread = threading.Thread(target=self.publisher.run, args=())
        	thread.daemon = True                            # Daemonize thread
        	thread.start()
 def testGetSubscriberList(self):
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     list1 = pub.getSubscriberList()
     list2 = [dum1, dum2]
     self.assertCountEqual(list1, list2)
Example #5
0
def register(address, port, init_topic):
	publisher = Publisher(address, port, init_topic)
	publisher.register_handler()
	logfile_name = './Output/' + publisher.myID + '-publisher.log'
	with open(logfile_name, 'w') as log:
		log.write('ID: %s \n' % publisher.myID)
		log.write('Init Topic: %s\n' % publisher.init_topic)
		log.write('Connection Info: tcp://' + address + ':' + port + '\n')
	return publisher
Example #6
0
def publish(msg, room, token):
    publisher = Publisher(room=room, token=token)
    publisher.start()
    publisher.publish(msg)
    _, data = publisher.recv()
    if not data == b'publish successful':
        raise Exception(data)
    publisher.stop()
Example #7
0
    def process_withdrawal_status(self, message):
        self.info("Publish .. creating publish instance, queue," \
  "exchange: (%s, %s) " % ('WITHDRAWAL_STATUS', 'WITHDRAWAL_STATUS'))
        message['exchange'] = 'WITHDRAWAL_STATUS'
        publisher = Publisher('WITHDRAWAL_STATUS', 'WITHDRAWAL_STATUS')

        self.logger.info("Publish calling publish status : %r" % message)
        publisher.publish(message, 'WITHDRAWAL_STATUS')

        self.info(
            "POST: Withdraw status Queued successfully with message: %r " %
            message)
Example #8
0
    def process_message_status(self, message):
        self.info("Publish .. creating publish instance, queue," \
  "exchange: (%s, %s) " % ('DLR_QUEUE', 'DLR_QUEUE'))
        message['exchange'] = 'DLR_QUEUE'
        message['reference'] = message.get('ref_no')

        publisher = Publisher('DLR_QUEUE', 'DLR_QUEUE')

        self.logger.info("Publish calling publish status : %r" % message)
        publisher.publish(message, 'DLR_QUEUE')

        self.info("POST: DLR Queued successfully with message: %r " % message)
Example #9
0
    def get(self):
        message = self.get_message_dict()
        self.logger.info("Publish .. creating publish instance, queue," \
            "exchange: (%s, %s) " % (self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME))

        message['exchange'] = self.SMS_EXCHANGE_NAME
        publisher = Publisher(self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        publisher.publish(message, self.SMS_ROUTING_KEY)

        self.info("GET: Task Queued successfully with message: %r " % message)
        return self.response()
Example #10
0
    def get(self):
        message = self.get_message_dict()
        self.logger.info("Publish .. creating publish instance, queue," \
            "exchange: (%s, %s) " % (self.QUEUE_NAME, self.EXCHANGE_NAME))
        publisher = Publisher(self.QUEUE_NAME, self.EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        q_message = self.get_queue_message(message)
        publisher.publish(q_message, self.ROUTING_KEY)

        self.info("GET: Task Queued successfully with message: %r " % message)
        return self.response(message.get('TransID'), 201,
                             'Transaction queued succcess'), 200
class iot_device(object):
    def __init__(self, name):
        self.name = name
        self.broker = []
        self.Publish = None

    def MessageReceived(self, paho_mqtt, userdata, msg):
        # A new message is received

        body = msg.payload.decode("utf-8")
        print(body)
        json_body = json.loads(body)
        #nelle righe successive ci sarebbe il controllo delle uscite
        #che vanno al condizionamento e al riscaldamento
        print("Activate water pump:" + str(json_body['water']))
        print("Light on:" + str(json_body['light']))
        print("heather: " + str(int(json_body['Heat'])))

    def sendData(self):
        per_dict = {
            'temperature': 0,
            'unit': 'C',
            'light perc': None,
            "umidity": None
        }

        per_dict['temperature'] = (random.randint(10, 40))

        per_dict['light perc'] = (random.randint(0,
                                                 100))  #% di luce nella serra

        per_dict['umidity'] = (random.randint(0,
                                              100))  #% di umidità nel terreno
        load = json.dumps(per_dict)

        self.Publish.myPublish("/tiot/17/serra/sens", load)

    def alive(self):
        threading.Timer(60.0, self.alive).start()
        load = json.dumps({
            "ID":
            self.name,
            "endPoint":
            "/tiot/17/serra/sens",
            "avaibleResources": ["Temperature", "umidity", "light level"]
        })
        requests.put('http://localhost:8080/device/', data=load)

    def set(self):
        self.Publish = Publisher("pub", self.broker)
        self.Publish.start()
class SerialData(object):
    """ This class handles the communication with Arduino Boards.
    """
    def __init__(self, port='/dev/ttyACM1'):
        signal.signal(signal.SIGINT, self.signal_handler)
        self.__publisher = Publisher()
        self.__last_received = '{"temperature":"-100","humidity":"-100"}'
        self.__kill_received = False
        try:
            self.ser =  serial.Serial(
                port=port,
                baudrate=9600,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=0.1,
                xonxoff=0,
                rtscts=0,
                interCharTimeout=None
            )
        except serial.serialutil.SerialException:
            # no serial connection
            self.ser = None
        else:
            self.__thread = Thread(target=self.__receiving, args=(self.ser,)).start()

    def __receiving(self, ser):
        readline = ''
        while not self.__kill_received:
            if self.__kill_received:
                logging.debug('got kill')
            readline = ser.readline()
            if readline != '':
                self.__last_received = readline
                self.__publisher.publish(self.__last_received)

    def next(self):
        if not self.ser:
            return 100  # return anything so we can test when Arduino isn't connected
        for j in range(40):
            raw_line = self.__last_received
            try:
                # logging.debug(raw_line.strip())
                return raw_line.strip()
            except ValueError, e:
                # print 'bogus data',raw_line
                logging.debug("Value Error: {0}".format(raw_line.strip()))
                print str(e)
                time.sleep(.005)
        return 0.
    def getEBookInfo(self):
        title = input("Enter the book title:")
        location = input("Enter the location code:")
        try:
            yearPub = int(input("Enter int value for the year of publication:"))
        except ValueError as e:
            print("*** Input type error, publication year set to 0 ***")
            yearPub = 0
        authors = []
        authorName = input("Enter one author for the book(you can add more late):")
        author = Author(authorName)
        authors.append(author)
        publisherName = input("Enter the publisher:")
        publisher = Publisher(publisherName)
        try:
            pages = int(input("Enter int value for the number of pages:"))
        except ValueError as e:
            print("*** Input type error, total pages set to 0 ***")
            pages = 0
        try:
            size = float(input("Enter decimal value for the size in MB of the e-book:"))
        except ValueError as e:
            print("*** Input type error, size set to 0.0 ***")
            size = 0.0
        print()

        addBook = ElectronicBook(title, location, yearPub, authors, publisher, pages, size)
        return addBook
Example #14
0
    def daily_news(self):
        # get all articles
        paper_bundle = Paper_Boy().get_the_paper()

        # add the statistics
        Analyzer(paper_bundle).fill_stats()

        # write tweets
        tweets = Writer(paper_bundle).write_all_tweets()

        # publish tweets
        publisher = Publisher()
        for tweet in tweets:
            publisher.post_tweet(tweet)

        return tweets
Example #15
0
 def __init__(self, path):
   self.publisher = Publisher()
  
   parser = ArgumentParser()
   parser.add_argument("-verbose",      help="show details of generated files", action="store_true")
   parser.add_argument("-pagetitles",   help="Page titles based on file names, not on first headder in document. eg. '1.02.md' would have title '02'", action="store_true")
   parser.add_argument("-outputfolder", help="output folder for generated files")
   parser.add_argument("-bootstrap",    help="use bootstrap theme", action="store_true")
   parser.add_argument("-external",     help="use external semantic ui and highlight.js resources", action="store_true")
   parser.add_argument("-wall",         help="generate a topic and lab wall pages", action="store_true")
   args = parser.parse_args()
  
   settings.viewsPath      = path + '/views'
   settings.verbose        = args.verbose  
   settings.pagetitles     = args.pagetitles
   settings.bootstrap      = args.bootstrap
   settings.external       = args.external
   settings.wall           = args.wall
   
   if args.outputfolder:
     settings.outputfolder   = args.outputfolder
   settings.templateLoader = jinja2.FileSystemLoader( searchpath=settings.viewsPath )  
   settings.templateEnv    = jinja2.Environment( loader=settings.templateLoader, trim_blocks=True, lstrip_blocks=True, line_statement_prefix='#' )
  
   print ('Moodle-Books Version ' + settings.version + ' (-h for commands)')
Example #16
0
    def post(self):
        message = self.get_message_dict()
        self.info("Received inbox post request ==> %r" % (message, ))
        if not message or not message.get('short_code'):
            return {
                'response_code': 400,
                'response_desc': 'Missing MSISDN on POST'
            }, 400
        message['exchange'] = self.SMS_EXCHANGE_NAME
        publisher = Publisher(self.SMS_QUEUE_NAME, self.SMS_EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r" % message)
        publisher.publish(message, self.SMS_ROUTING_KEY)

        self.info("POST: Task Queued successfully with message: %r " % message)
        return self.response()
 def __init__(self):
     signal.signal(signal.SIGINT, self.signal_handler)
     self.__lastswitchstate = 1;
     self.__temperature = -100;
     self.__humidity = 0;
     self.__thread = Thread(target=self.__receiving).start()
     self.__kill_received = False
     self.__publisher = Publisher()
def unitTest12(ip, address):
    topics = {
        1: 'animals',
        2: 'countries',
        3: 'foods',
        4: 'countries',
        5: 'phones',
        6: 'universities',
        7: 'phones',
        8: 'laptops',
        9: 'foods',
        10: 'laptops',
        11: 'laptops',
        12: 'animals'
    }
    topic = topics[random.randint(1, 12)]
    publisher = Publisher(ip, address, '5556', '6002', topic)
    publisher.register()
Example #19
0
    def post(self):
        message = self.get_message_dict()
        if not message or not message.get('TransID'):
            return {
                'response_code': 400,
                'response_desc': 'Missing transaction ID'
            }, 400
        message['exchange'] = self.EXCHANGE_NAME
        publisher = Publisher(self.QUEUE_NAME, self.EXCHANGE_NAME)

        self.logger.info("Publish calling publish : %r => Q = %s, EX=%s" %
                         (message, self.QUEUE_NAME, self.EXCHANGE_NAME))

        q_message = self.get_queue_message(message)
        publisher.publish(q_message, self.ROUTING_KEY)

        self.info("POST: Task Queued successfully with message: %r " % message)
        return self.response(message.get('TransID'), 201, 'Succcess')
Example #20
0
def main():
    """Main entry point to the program."""

    # Get the location of the AMQP broker (RabbitMQ server) from
    # an environment variable
    amqp_url = os.environ['AMQP_URL']
    LOGGER.info('URL: %s' % (amqp_url, ))

    # Connect to localhost:5672 as guest with the password guest and virtual host "/" (%2F)
    Publisher(amqp_url, on_connection_complete=publish_events)
Example #21
0
 def __init__(self,
              context=None,
              fuser=None,
              socket_nr=5555,
              debug_time=-1):
     DataBoss.__init__(self, fuser, debug_time)
     self.context = context
     if self.context is None:
         self.context = zmq.Context()
     self.publisher = Publisher(context=self.context, socket_nr=socket_nr)
 def testRemoveSubscriber1(self):
     # tests to see if subscriber in list is removed
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     pub.removeSubscriber(dum2)
     self.assertEqual(len(pub.getSubscriberList()), 1)
def unitTest12(ip, address, zk_address):
    topics = {
        1: 'animals',
        2: 'countries',
        3: 'foods',
        4: 'countries',
        5: 'phones',
        6: 'universities',
        7: 'phones',
        8: 'laptops',
        9: 'foods',
        10: 'laptops',
        11: 'laptops',
        12: 'animals'
    }
    topic = topics[random.randint(1, 12)]
    publisher = Publisher(zk_address, topic)
    input_file = './Input/' + topic + '.txt'
    print(input_file)
    publisher.main(topic, input_file)
Example #24
0
 def __init__(self, group=None, target=None, name=None, args=(), kwargs={}, daemon=None, sensorConversionThread=None):
   '''
   Initializes the control planner
   @param Refer to the Python Thread class for documentation on all thread specific parameters
   @param sensorConversionThread - the sensor conversion thread
   '''
   Thread.__init__(self, group=group, target=target, name=name, daemon=daemon)
   Publisher.__init__(self)
   self.args = args
   self.kwargs = kwargs
   self.sensorConversionThread = sensorConversionThread
   self.shutDown = False
   self.wallFollowPID = PID(Constants.WALL_FOLLOW_PID_P, Constants.WALL_FOLLOW_PID_I, Constants.WALL_FOLLOW_PID_D, Constants.WALL_FOLLOW_PID_WINDUP)
   self.wallFollowPID.setGoal(Constants.WALL_FOLLOW_PID_DIST_GOAL)
   self.vehicleLeftDistance = 0.0
   self.vehicleRightDistance = 0.0
   self.vehicleSteeringAngle = 0.0
   self.steeringAngleGoal = 0.0
   # TODO: Velocity goals?
   self.velocityGoal = 0.5
   self.currentTime = time.time()
 def testRemoveSubscriber2(self):
     # tests to make sure nothing is removed since not in list
     pub = Publisher()
     dum1 = Dummy()
     dum2 = Dummy()
     notAdded = BigDummy()
     pub.addSubscriber(dum1)
     pub.addSubscriber(dum2)
     pub.removeSubscriber(notAdded)
     self.assertEqual(len(pub.getSubscriberList()), 2)
Example #26
0
 def start_collection(self):
     iot = IoT()
     self.publisher = Publisher(self.drone_id, self.server_ip,
                                self.server_port, self.username,
                                self.password)
     sensor = iot.get_sensor(self.sensor_type)
     while True:
         self.send_data(sensor.get_data())
         self.count -= 1
         if self.count == 0:
             break
         time.sleep(self.interval)
Example #27
0
class iot_device(object):
        def __init__(self,name):
           self.name=name
           self.broker=[]
           self.Publish=None
        def MessageReceived(self, paho_mqtt , userdata, msg):
                    # A new message is received
                    
                    body=msg.payload.decode("utf-8")
                        
                    json_body = json.loads(body)
                    #nelle righe successive ci sarebbe il controllo delle uscite
                    #che vanno al condizionamento e al riscaldamento
                    print("FAN :" + str(int(json_body['Fan'])))
                    print("Heater :" + str(int(json_body['Heat'])))

        def sendData(self):
                per_dict = {'temperature' : 0, 'unit' : 'C', 'presence' : False}

                per_dict['temperature'] = str(random.randint(1,60))

                        
                per_dict['presence'] = str(random.choice([True, False]))

                load = json.dumps(per_dict)
                
                self.Publish.myPublish("/tiot/17/house/sens",load)
               
                
        def alive(self):         
            threading.Timer(60.0, self.alive).start()
            load=json.dumps({
                      "ID": self.name,
                  "endPoint": "/tiot/17/house/sens",
                  "avaibleResources": ["Temperature", "sound"]
                })
            requests.put('http://localhost:8080/device/', data=load)  
        def set(self):
             self.Publish=Publisher("pub",self.broker)
             self.Publish.start()
 def __init__(self,
              group=None,
              target=None,
              name=None,
              args=(),
              kwargs={},
              daemon=None,
              courseMap=None,
              sensorConversionThread=None):
     '''
 Initializes the control planner
 @param Refer to the Python Thread class for documentation on all thread specific parameters
 @param courseMap - the course map
 @param sensorConversionThread - the sensor conversion thread
 '''
     Thread.__init__(self,
                     group=group,
                     target=target,
                     name=name,
                     daemon=daemon)
     Publisher.__init__(self)
     self.args = args
     self.kwargs = kwargs
     self.courseMap = courseMap
     self.particleFilter = ParticleFilter(Constants.PARTICLE_NUMBER,
                                          Constants.MAP_START_BOX,
                                          Constants.MAP_HEADING_RANGE,
                                          self.courseMap,
                                          sensorConversionThread)
     self.shutDown = False
     self.estVehicleX = 0.0
     self.estVehicleY = 0.0
     self.estVehicleHeading = 0.0
     self.covarVehicle = None
     self.waypoint = 0
     self.waypointCheck = 0
     self.steeringAngleGoal = 0.0
     self.velocityGoal = 0.0
class RPData(object):
    """This class handles hardware communication with sensors and actuators directly attached to
    the RPi
    """
    def __init__(self):
        signal.signal(signal.SIGINT, self.signal_handler)
        self.__lastswitchstate = 1;
        self.__temperature = -100;
        self.__humidity = 0;
        self.__thread = Thread(target=self.__receiving).start()
        self.__kill_received = False
        self.__publisher = Publisher()

    def __receiving(self):
        """This function is called by the thread to update the device"""
        while not self.__kill_received:
            if self.__kill_received:
                logging.debug("Thread got killed")
            humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)
            logging.debug("Got temperature reading: "+str(temperature)+" and also got Humidity reading: "+str(humidity))
            if self.__temperature != temperature or self.__humidity != humidity:
                if self.__humidity != 0 and self.__temperature != -100:
                    self.__publisher.publish({"temperature":temperature,"humidity":humidity, "switch":self.__lastswitchstate})
                self.__humidity = humidity
                self.__temperature = temperature
            sleep(2)

    def next(self):
        return str('{"temperature":"%5.2f","humidity":"%5.2f", "switch":"%d"}' % (self.__temperature, self.__humidity, self.__lastswitchstate))

    def updateSwitch(self, state):
        subprocess.call(["sudo", "/usr/local/bin/send433", "11111", "11", str(state)])
        self.__lastswitchstate = state

    def signal_handler(self, signal, frame):
        self.__kill_received = True
        os._exit(1)
Example #30
0
def main():
    args = sys.argv[1:]

    # if len(args) != 3:
    #     print('python init.py [publisher|subscriber|server] <host> <port>')

    #     return

    host = 'localhost'
    port = 8000

    if args[0] == 'publisher':
        client = Publisher(host, port)

        try:
            client.menu_loop()
        except KeyboardInterrupt:
            print('\nBye')

        return

    if args[0] == 'subscriber':
        client = Subscriber(host, port)

        try:
            client.menu_loop()
        except KeyboardInterrupt:
            print('\nBye')

        return

    if args[0] == 'server':
        server = Server('server/newsletter.db')

        print('Serving...')

        try:
            server.serve(host, port)
        except KeyboardInterrupt:
            print('\nBye')

        return

    print('Bad argument')
 def __init__(self, port='/dev/ttyACM1'):
     signal.signal(signal.SIGINT, self.signal_handler)
     self.__publisher = Publisher()
     self.__last_received = '{"temperature":"-100","humidity":"-100"}'
     self.__kill_received = False
     try:
         self.ser =  serial.Serial(
             port=port,
             baudrate=9600,
             bytesize=serial.EIGHTBITS,
             parity=serial.PARITY_NONE,
             stopbits=serial.STOPBITS_ONE,
             timeout=0.1,
             xonxoff=0,
             rtscts=0,
             interCharTimeout=None
         )
     except serial.serialutil.SerialException:
         # no serial connection
         self.ser = None
     else:
         self.__thread = Thread(target=self.__receiving, args=(self.ser,)).start()
Example #32
0
    def HandleAddPublisher(self, command):
        """This function handles the case where the client wishes to add a publisher to the sensor mesh"""

        print "Handling Add Publisher..."

        # The client screwed up the packet do nothing, return failure.
        if not command.Payload or command.Payload == "":
            print "Client tried to add a publisher, but did not provide an identifier."
            return Command().CreateFromParams(Command.FAILURE, command.TransactionID, 0, Command.INVALID_COMMAND)

        # RQ 15b
        # If the publisher already exists in the network.
        if Pubs.has_key(command.Payload):
            print "Client " + str(self.client_address) + " tried to add publisher that already exists."
            return Command().CreateFromParams(Command.FAILURE, command.TransactionID, 0, Command.PUB_ALREADY_EXISTS)

        # Actually add the publisher to the dictionary.
        Pubs[command.Payload] = Publisher(command.Payload, self.request, self.client_address, self.GetNextPort(), command.SensorType)
        print "Added publisher: ID=" + command.Payload + " from " + str(self.client_address)

        # RQ 15c
        # Return success.
        return Command().CreateFromParams(Command.SUCCESS, command.TransactionID, 0, Pubs[command.Payload].BroadcastPort)
    def getPrintedBookInfo(self):
        title = input("Enter the book title:")
        location = input("Enter the location code:")
        try:
            yearPub = int(input("Enter int value for the year of publication:"))
        except ValueError as e:
            print("*** Input type error, publication year set to 0 ***")
            yearPub = 0
        authors = []
        authorName = input("Enter one author for the book(you can add more late):")
        author = Author(authorName)
        authors.append(author)
        publisherName = input("Enter the publisher:")
        publisher = Publisher(publisherName)
        try:
            pages = int(input("Enter int value for the number of pages:"))
        except ValueError as e:
            print("*** Input type error, total pages set to 0 ***")
            pages = 0
        type = input("Enter the type(hard cover or paperback):")
        print()

        addBook = PrintedBook(title, location, yearPub, authors, publisher, pages, type)
        return addBook
}
dict3 = {
    'topic_channel': [],
    'topic_key': topic_key3,
    'publisher': None,
    'subscriber_lst': []
}

topic_dict = {'topic1': dict1, 'topic2': dict2, 'topic3': dict3}
authentication_manager = AuthenticationManager({}, source_dict)

# ------------------------------Creating three publishers ------------------------------------------------

pub1_client_conn = Connection()
pub1_server_conn = Connection()
pub1 = Publisher(pub1_server_conn, pub1_client_conn, "topic1", 'publisher1',
                 "source1", "trusted_keys/trusted1", 'trusted_keys')

pub2_client_conn = Connection()
pub2_server_conn = Connection()
pub2 = Publisher(pub2_server_conn, pub2_client_conn, "topic2", 'publisher2',
                 "source2", "trusted_keys/trusted2", 'trusted_keys')

pub3_client_conn = Connection()
pub3_server_conn = Connection()
pub3 = Publisher(pub3_server_conn, pub3_client_conn, "topic3", 'publisher3',
                 "source3", "trusted_keys/trusted3", 'trusted_keys')

pub1_AS_thread = AuthenticationServerThread(pub1_server_conn, pub1_client_conn,
                                            authentication_manager)
pub1_AS_thread.start()
pub1.start()
 def getPublisher(self, publisherID):
   name = self.redisDB.get("Publisher:"+publisherID+":Name")
   if name == None:
     return None
   viewCount = self.redisDB.get("Publisher:"+publisherID+":ViewCount")
   return Publisher(publisherID, name, viewCount)
Example #36
0
 def __init__(self, **kwargs):
     Publisher.__init__(self, **kwargs)
     self._xslt = XsltTransformer(caller=self)
     if not self.script:
         self.script = self._xslt.script