Exemple #1
0
 def run(self):
     if self.args.debug:
         logging.basicConfig(level=logging.DEBUG)
     else:
         logging.basicConfig(level=logging.WARN)
     p = Poller(self.args)
     p.run()
Exemple #2
0
 def Run(self):
     logger = logging.getLogger()
     logger.info("PullClient starting...")
     self.poller = Poller(self.pollerStop)
     self.poller.start()
     logger.info("PullClient started.")
     self.stopEvent.Wait()
Exemple #3
0
class Handler(object):

    # no parameters are permitted; all configuration should be placed in the
    # configuration file and handled in the Initialize() method
    def __init__(self):
        self.stopEvent = cx_Threads.Event()
        self.pollerStop = threading.Event()
        self.config = PullClientConfig.instance()
        logging.config.fileConfig(self.config.config_file)

    # called when the service is starting
    def Initialize(self, configFileName):
        pass

    # called when the service is starting immediately after Initialize()
    # use this to perform the work of the service; don't forget to set or check
    # for the stop event or the service GUI will not respond to requests to
    # stop the service
    def Run(self):
        logger = logging.getLogger()
        logger.info("PullClient starting...")
        self.poller = Poller(self.pollerStop)
        self.poller.start()
        logger.info("PullClient started.")
        self.stopEvent.Wait()

    # called when the service is being stopped by the service manager GUI
    def Stop(self):
        logger = logging.getLogger()
        logger.info("PullClient stopping...")
        self.pollerStop.set()
        self.poller.join()
        logger.info("PullClient stopped.")
        self.stopEvent.Set()
Exemple #4
0
 def setUp(self):
     self.test_poll = Poller()
     self.test_poll._candidates = [
         Candidate("candidate1"),
         Candidate("candidate2")
     ]
     self.test_poll._miscast = deepcopy(self.test_poll._candidates)
Exemple #5
0
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()
Exemple #6
0
 def __init__(self):
     self.p = Poller()
     self.fd = None
     self.base_timeout = 10
     self.timeout = 10
     self.disable()
     self.disable_timeout()
     self.sensores = None
     self.placa = None
Exemple #7
0
 def __init__(self, ip_port):
     listener = socket.socket()
     listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
     listener.bind(ip_port)
     listener.listen(NEW_CLIENTS)
     self.listener = listener
     poller = Poller()
     poller.add(listener)
     self.poller = poller
 def run(self):
     webParse = HTTPServer(self.args.debug)
     success = webParse.parseConfig("tests/web.conf")
     print webParse.hosts
     print webParse.media
     print webParse.parameters
     if success:
         p = Poller(self.args.port, webParse)
         p.run()
     else:
         print "Server Error: could not read config file"
Exemple #9
0
class TestPoller(unittest.TestCase):
    def setUp(self):
        self.test_poll = Poller()
        self.test_poll._candidates = [
            Candidate("candidate1"),
            Candidate("candidate2")
        ]
        self.test_poll._miscast = deepcopy(self.test_poll._candidates)

    def test_add_to_poll(self):
        """ Ensure when we add a candidate to a poll that they exist, and
            that we've only added them once. Furthermore check
        """
        new_candidate = "numero3"
        preLen = len(self.test_poll._candidates)
        self.test_poll.add_candidate(new_candidate)
        postLen = len(self.test_poll._candidates)
        self.assertEqual(
            preLen + 1, postLen,
            "Check - we've added more than just %s" % (new_candidate))
        self.assertTrue(
            Candidate(new_candidate) in self.test_poll._candidates,
            "Candidate %s cannot be added" % (new_candidate))
        self.assertTrue(
            Candidate(new_candidate) in self.test_poll._miscast,
            "Candidate %s was not added to our log of miscast votes" %
            (new_candidate))

    def test_unique_candidates(self):
        duplicate = "duplicate candidate"
        self.test_poll.add_candidate(duplicate)
        with self.assertRaises(Exception):
            self.test_poll.add_candidate(duplicate)

    def test_add_vote(self):
        current_votes = len(self.test_poll._candidates[0]._votes)
        self.test_poll.add_vote("candidate1", "user1")
        new_votes = len(self.test_poll._candidates[0]._votes)
        self.assertEqual(new_votes, current_votes + 1,
                         "Vote not saved correctly")

        # Check if we exceed the voting limit it becomes a miscast vote
        for i in range(0, self.test_poll.VOTE_LIMIT):
            self.test_poll.add_vote("candidate1", "user1")
        self.assertEquals(
            len(self.test_poll._miscast[0]._votes), 1,
            "Vote limit was exceeded and not captured as a miscast vote")

    def tearDown(self):
        self.test_poll = None
    def butcmdacquire(self):
        """
        Acquire check button command to manage the acquisition thread to read the DSP data.
        If the button is not selected the thread is lunched.
        If the button is selected the thread is stopped.

        """
        if self.ivaracquire.get():
            if not self.isconnected():
                self.ivaracquire.set(0)
                return
            self.scope.resetpoints()
            self.strtme = time()
            self.poller = Poller(self.ivaracquire, self.dvarsecsmp,
                                 self.updatefields)
        else:
            self.poller.wake()
Exemple #11
0
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()
def do_poll():
    """ Create a poll of candidates, and a menu screen to allow a user to view
        the poll or add a vote
    """

    # Some intial setup to get a MVP, will do this dynamically later
    candidates = [
        "Candidate 1", "Candidate 2", "Candidate 3", "Candidate 4",
        "Candidate 5"
    ]

    poll = Poller()

    # Generate our list of candidates
    for candidate in candidates:
        poll.add_candidate(candidate)

    menu = OrderedDict([])
    menu['P/p'] = "Print current poll status"
    menu['V/v'] = "Vote"
    menu['A/a'] = "Auto vote with x votes"
    menu['Q/q'] = "Quit"
    while True:
        print "\nMain Menu"
        print "-----------------------------"
        options = menu.keys()
        for entry in options:
            print entry, menu[entry]

        selection = raw_input("Selection:").lower()
        if selection == 'p':
            start = timer()
            print(poll)
            stop = timer()
            print "\nPoll displayed in %.2f seconds" % (stop - start)
        elif selection == 'v':
            manual_vote(poll)
        elif selection == 'a':
            auto_vote(poll)
        elif selection == 'q':
            quit()
        else:
            print "\nUnknown Option Selected - please try again"
Exemple #13
0
    def setUp(self):
        context = zmq.Context()
        worker_socket = context.socket(zmq.REP)
        worker_socket.bind("ipc:///tmp/worker")
        frontend_socket = context.socket(zmq.REP)
        frontend_socket.bind("ipc:///tmp/frontend")

        sockets = {
            "worker": {
                "socket": worker_socket,
                "receive": worker_socket.recv_json,
                "send": worker_socket.send_json
            },
            "frontend": {
                "socket": frontend_socket,
                "receive": frontend_socket.recv_json,
                "send": worker_socket.send_json
            },
        }
        time = TimeStub()

        self.poller = Poller(sockets, time)
Exemple #14
0
    def setUp(self):
        context = zmq.Context()
        worker_socket = context.socket(zmq.REP)
        worker_socket.bind("ipc:///tmp/worker")
        frontend_socket = context.socket(zmq.REP)
        frontend_socket.bind("ipc:///tmp/frontend")

        sockets = {
            "worker": {"socket": worker_socket, "receive": worker_socket.recv_json, "send": worker_socket.send_json},
            "frontend": {"socket": frontend_socket, "receive": frontend_socket.recv_json, "send": worker_socket.send_json},
        }
        time = TimeStub()

        self.poller = Poller(sockets, time)
Exemple #15
0
 def run(self, debug=False):
     
     #
     # load up the poller
     #
     poller = Poller()
     
     
     #
     # using sched here since I think its thread safer then a lame while loop
     # with a sleep.
     #
     s = sched.scheduler(time.time, time.sleep)
     poller.runChecks(s, True)
     
     try:
         s.run()
     except (KeyboardInterrupt, SystemExit):
         poller.shutdown()
    p.add_argument("--dd-api-key", dest="datadog_api_key", action=EnvDefault, envvar="DATADOG_API_KEY", type=str,
                   required=True, help="Datadog API key")
    p.add_argument("--dd-app-key", dest="datadog_app_key", action=EnvDefault, envvar="DATADOG_APP_KEY", type=str,
                   required=True, help="Datadog APP key")
    p.add_argument("--dd-env", dest="datadog_env", action=EnvDefault, envvar="DATADOG_ENV", type=str,
                   required=True, help="Datadog ENV variable")
    p.add_argument("--log-config", dest="log_config", action=EnvDefault, envvar="LOG_CONFIG", type=str,
                   default="/app/logging_config.json",
                   help="Path to logging configuration file")
    p.add_argument("--enforce-version-match", dest="enforce_version_match", action=EnvDefault,
                   envvar="ENFORCE_VERSION_MATCH", type=bool, default=False,
                   required=False, help="If set, version matching will be required of applications to participate")
    p.add_argument("--rules-prefix", dest="rules_prefix", action=EnvDefault,
                   envvar="RULES_PREFIX", type=str, default="mas_rule",
                   required=False, help="The prefix for rule names")
    return p.parse_args()


def add_args_to_settings(cli_args):
    for name, value in vars(cli_args).iteritems():
        setattr(settings, name, value)

if __name__ == "__main__":
    args = parse_cli_args()
    add_args_to_settings(args)
    setup_logging(args)
    logging.info(args)
    poller = Poller(args)
    poller.start()
    sys.exit(0)
 def run(self):
     if(self.args.debug):
         print self.args
     p = Poller(self.args.port, self.args.debug)
     p.run()
Exemple #18
0
 def run(self):
     p = Poller(self.args.port)  #so now my
     p.run()
Exemple #19
0
class Bot:
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()

    def run(self):
        self.poller.async_run(self.on_update)
        self.updater.start_polling()
        self.updater.idle()
        self.poller.stop()
        self.persist()
        db.close()

    def persist(self):
        for _, client in self.clients.items():
            client.persist()

    def restore(self):
        for _, client in self.clients.items():
            self.add_poll_server(client)

    def reg_actions(self):
        dispatcher = self.updater.dispatcher
        dispatcher.addTelegramCommandHandler('start', self.start)
        dispatcher.addTelegramCommandHandler('whoami', self.whoami)
        dispatcher.addTelegramCommandHandler('pick', self.pick)
        dispatcher.addTelegramCommandHandler('unpick', self.unpick)
        dispatcher.addTelegramCommandHandler('details', self.details)
        dispatcher.addErrorHandler(self.error)
        dispatcher.addUnknownTelegramCommandHandler(self.unknown)
        dispatcher.addTelegramMessageHandler(self.on_message)

    def start(self, bot, update):
        chat_id = update.message.chat_id
        auth_url = self.vk.get_auth_url()
        # Send first info messages
        bot.sendMessage(chat_id=chat_id,
                text=message.WELCOME(auth_url),
                reply_markup=ReplyKeyboardHide())
        bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN)
        # Create new client
        client = Client(next_action=action.ACCESS_TOKEN,
                        chat_id=chat_id)
        self.clients[chat_id] = client
        client.persist()

    def whoami(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            return

        client = self.clients[chat_id]
        bot.sendMessage(chat_id=chat_id,
            text=message.WHOAMI(client.vk_user.get_name()),
            reply_markup=Bot.keyboard(client.keyboard_markup()))

    def pick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        recepient = update.message.text[6:]
        client.expect_message_to(recepient)
        bot.sendMessage(chat_id=chat_id,
                text=message.TYPE_MESSAGE(recepient),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))

    def unpick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.next_action = action.NOTHING
        client.persist()
        bot.sendMessage(chat_id=chat_id,
                text=message.UNPICK(client.next_recepient.get_name()),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))
        client.next_recepient = None

    def details(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        user = client.next_recepient
        if user == None:
            bot.sendMessage(chat_id=chat_id,
                    text=message.FIRST_PICK_USER,
                    reply_markup=Bot.keyboard(client.keyboard_markup()))
            return

        if user.photo != None:
            bot.sendPhoto(chat_id=chat_id, photo=user.photo)

        bot.sendMessage(chat_id=chat_id,
                text=message.USER_NAME(user.get_name()),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=Bot.keyboard(client.keyboard_markup()))

        participants = user.participants()
        if participants != None:
            bot.sendMessage(chat_id=chat_id,
                    text=message.PARTICIPANTS(participants),
                    parse_mode=ParseMode.MARKDOWN,
                    reply_markup=Bot.keyboard(client.keyboard_markup()))



    def error(self, bot, update, error):
        logger.warn('Update "%s" caused error "%s"' % (update, error))

    def on_message(self, bot, update):
        chat_id = update.message.chat_id

        if not chat_id in self.clients:
            return self.start(bot, update)

        client = self.clients[chat_id]
        client.seen_now()

        if client.next_action == action.ACCESS_TOKEN:
            return self.on_token_message(bot, update, client)
        elif client.next_action == action.MESSAGE:
            return self.on_typed_message(bot, update, client)

        self.echo(update.message.chat_id)

    def on_token_message(self, bot, update, client):
        parseresult = urlparse(update.message.text)
        if parseresult.scheme=='https':
            parseparams = parse_qs(parseresult.fragment)
            access_token = parseparams.get('access_token')[0]
            client.load_vk_user(access_token)
        else:
            client.load_vk_user(update.message.text)
        name = client.vk_user.get_name()
        client.next_action = action.NOTHING
        self.add_poll_server(client)
        bot.sendMessage(chat_id=update.message.chat_id,
                text=message.TOKEN_SAVED(name),
                reply_markup=Bot.keyboard(client.keyboard_markup()))

    def on_typed_message(self, bot, update, client):
        client.send_message(update.message.text)

    @run_async
    def add_poll_server(self, client):
        if client.vk_token != None:
            self.poller.add(client)

    def echo(self, chat_id):
        self.updater.bot.sendMessage(chat_id=chat_id, text=message.ECHO)

    def unknown(self, bot, update):
        bot.sendMessage(chat_id=update.message.chat_id,
                text=message.UNKNOWN)

    @staticmethod
    def keyboard(keyboard_markup):
        return ReplyKeyboardMarkup(
            keyboard_markup,
            selective=True,
            resize_keyboard=True)

    def on_update(self, updates, client):
        for update in updates:
            self.process_update(update, client)

    def process_update(self, update, client):
        if len(update) == 0:
            return

        if update[0] == 4:
            # When new message received
            self.receive_vk_message(update, client)

    def receive_vk_message(self, update, client):
        flags = update[2]
        from_id = update[3]
        text = update[6]
        attachments = update[7]

        if flags & 2 == 2:
            # Skip when message is outgoing
            return

        from_name = ''

        if from_id & 2000000000 == 2000000000:
            # Message came from chat
            chat_id = from_id - 2000000000
            chat = Vk_chat.fetch(client.vk_token, chat_id)
            from_name = chat.name_from(attachments['from'])
            client.add_interaction_with(chat)
        else:
            user = Vk_user.fetch_user(client.vk_token, from_id)
            from_name = user.get_name()
            client.add_interaction_with(user)

        self.updater.bot.sendMessage(chat_id=client.chat_id,
                text=message.NEW_MESSAGE(from_name, text),
                reply_markup=Bot.keyboard(client.keyboard_markup()),
                parse_mode=ParseMode.MARKDOWN)
        client.persist()
Exemple #20
0
import argparse
from poller import Poller

if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog="CamHart Python Web Server", description="Web server for CS 360", add_help=True)
    parser.add_argument("-p", "--port", type=int, default=8080, help="port number to run the server on")
    parser.add_argument("-d", "--debug", action="store_true", help="Debug output", default=False)
    args = parser.parse_args()
    server = Poller(port=args.port, debug=args.debug)
    server.run()
 def run(self):
     p = Poller(self.args.port)
     p.unimplementedMethods = ['HEAD','PUT','POST','DELETE','LINK','UNLINK']
     p.hosts = dict()
     p.media_types = dict()
     p.timeout = 0
     with open('web.conf', 'r') as f:
         for line in f:
             if not line in ['\n','\r\n']:
                 words = line.split()
                 if words[0] == 'host':
                     p.hosts[words[1]] = words[2]
                 if words[0] == 'media':
                     p.media_types[words[1]] = words[2]
                 if words[0] == 'parameter':
                     if words[1] == 'timeout':
                         p.timeout = int(words[2])
     p.run()
Exemple #22
0
class CoAPP(Callback):
    '''
        Classe responsável por utilizar os métodos da classe coap e implementar o protocolo
        de aplicação (registro da placa no servidor e troca de dados dos sensores)
    '''
    def __init__(self):
        self.p = Poller()
        self.fd = None
        self.base_timeout = 10
        self.timeout = 10
        self.disable()
        self.disable_timeout()
        self.sensores = None
        self.placa = None

    def handle(self):
        pass

    def handle_timeout(self):
        '''
            Método para transmitir os dados de sensores a cada timeout
        '''
        msg = sensorapp_pb2.Mensagem()
        msg.placa = self.placa
        print(msg.placa)
        sensores = []
        for i in range(len(self.sensores)):
            sensor = sensorapp_pb2.Sensor()
            sensor.nome = self.sensores[i]
            sensor.valor = random.randint(-10, 10)
            sensor.timestamp = int(time.time())
            sensores.append(sensor)

        msg.dados.amostras.extend(sensores)
        payload = msg.SerializeToString()
        print("Payload >>>", payload)
        r = coap("::1").do_post(coap.CON, payload, 'ptc')
        print(r.getPayload())
        if (r.getPayload() == -1 or r.getPayload() == -2):
            print("error", r.getPayload())
            self.disable_timeout()
            self.disable()
            return False

    def configura(self, placa, periodo, *sensores):
        '''
            Método que faz o registro da placa no servidor
            Recebe como parâmetros:
            placa: string representando o nome da unidade de aquisição de dados
            periodo: inteiro com o intervalo de tempo de retransmissão desejado pelo usuário
            *sensores: listra de string com os nomes dos sensores que irão ser utilizados

            Retorna True se a requisição for bem sucedida. Retorna False caso haja erro na configuração
        '''
        self.sensores = sensores
        self.placa = placa
        msg = sensorapp_pb2.Mensagem()
        msg.placa = placa
        msg.config.periodo = 10
        msg.config.sensores.extend(sensores)
        data = msg.SerializeToString()
        payload = data
        r = coap("::1").do_post(coap.CON, payload, 'ptc')
        print(r.getPayload())
        if (r.getPayload() == -1 or r.getPayload() == -2):
            print("error", r.getPayload())
            self.disable_timeout()
            self.disable()
            return False
        msg.ParseFromString(r.getPayload())
        self.base_timeout = int(msg.config.periodo / 1000)
        return True

    def start(self):
        '''
            Método que inicia a troca de mensagens com os dados de sensores. Faz o primeiro envio
            e após deixa a retransmissão a cargo da classe Poller
        '''
        msg = sensorapp_pb2.Mensagem()
        msg.placa = self.placa
        print(msg.placa)
        sensores = []
        for i in range(len(self.sensores)):
            sensor = sensorapp_pb2.Sensor()
            sensor.nome = self.sensores[i]
            sensor.valor = random.randint(-10, 10)
            sensor.timestamp = int(time.time())
            sensores.append(sensor)

        msg.dados.amostras.extend(sensores)
        payload = msg.SerializeToString()
        print("Payload >>>", payload)
        r = coap("::1").do_post(coap.CON, payload, 'ptc')
        if (r.getPayload() == -1 or r.getPayload() == -2):
            print("error", r.getPayload())
            self.disable_timeout()
            self.disable()
            return False
        self.enable_timeout()
        self.enable()
        self.p.adiciona(self)
        self.p.despache()
        return False
Exemple #23
0
    def __init__(self):
        self._influx = None
        self._poller = Poller()

        self._database_name = DEFAULT_DATABASE
        self._num_polling_threads = DEFAULT_NUM_POLLING_THREADS
Exemple #24
0
def main():
    logging.basicConfig(filename='log.poller',
                        level=logging.DEBUG,
                        filemode='w',
                        format='%(asctime)s %(levelname)s %(message)s')

    logging.info('Loading poller...')
    poller = Poller('trucks')

    logging.info('Setting up probe storage db...')
    probe_storage = ProbeStorage()
    # probe_storage.clear_db()

    poller.start()

    try:
        """
        poller.add(PingProbe('149.210.184.36',
                             recurrence_time=1,
                             run_on_nodes=['trucks']))
        poller.add(TraceProbe('8.8.8.8', recurrence_time=3))
        poller.add(PingProbe('10.0.0.1', run_on_nodes=['miles']))
        """
        poller.add(HttpProbe('http://www.mortimer.nl/'))

        while True:
            # Here we can send probes to the poller
            # e.g. poller.add(IcmpProbe('127.0.0.1'))
            db_probes = probe_storage.get_probes()
            for probe in db_probes:
                if 'trucks' in probe['run_on_nodes']:
                    if probe['type'] == 'PingProbe':
                        poller.add(PingProbe(probe['dest_addr'],
                                             recurrence_time=probe['recurrence_time'],
                                             recurrence_count=probe['recurrence_count'],
                                             run_on_nodes=probe['run_on_nodes'],
                                             probe_id=probe['_id']))
                    if probe['type'] == 'TraceProbe':
                        poller.add(TraceProbe(probe['dest_addr'],
                                              recurrence_time=probe['recurrence_time'],
                                              recurrence_count=probe['recurrence_count'],
                                              run_on_nodes=probe['run_on_nodes']),
                                              probe_id=probe['_id'])
            time.sleep(5)
    except KeyboardInterrupt:
        poller.stop()
        print("\nThanks for joining!\n")
Exemple #25
0
 def run(self):
     p = Poller(self.args.port, self.conf)
     p.run()
Exemple #26
0
class TestPoller(unittest.TestCase):
    def setUp(self):
        context = zmq.Context()
        worker_socket = context.socket(zmq.REP)
        worker_socket.bind("ipc:///tmp/worker")
        frontend_socket = context.socket(zmq.REP)
        frontend_socket.bind("ipc:///tmp/frontend")

        sockets = {
            "worker": {
                "socket": worker_socket,
                "receive": worker_socket.recv_json,
                "send": worker_socket.send_json
            },
            "frontend": {
                "socket": frontend_socket,
                "receive": frontend_socket.recv_json,
                "send": worker_socket.send_json
            },
        }
        time = TimeStub()

        self.poller = Poller(sockets, time)

    def test_when_nobody_sends_message_poller_returns_empty_dictionary(self):
        messages, time = self.poller.poll(timeout=1)

        self.assertEquals({}, messages)
        self.assertEquals(1, time)

    def test_when_frontend_sends_message_poller_returns_that_message(self):
        message = {"model": "en-GB"}
        self.send_message("ipc:///tmp/frontend", message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("frontend", message, messages)

    def test_when_worker_sends_message_poller_returns_that_message(self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("worker", message, messages)

    def test_when_worker_and_frontend_send_message_poller_returns_both_messages(
            self):
        worker_message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", worker_message)

        frontend_message = {"model": "en-GB"}
        self.send_message("ipc:///tmp/frontend", frontend_message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("worker", worker_message, messages)
        self.assertReceivedMessage("frontend", frontend_message, messages)

    def test_when_worker_sends_two_messages_poller_should_return_both_messages_sequentially(
            self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})
        self.assertReceivedMessage("worker", message, messages)
        self.assertEquals(1, time)

        message = {"address": "tcp://127.0.0.1:2", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})
        self.assertReceivedMessage("worker", message, messages)
        self.assertEquals(2, time)

    def test_when_worker_sends_message_it_should_be_able_to_recieve_reply(
            self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        socket = self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})

        message = socket.recv_json()
        self.assertEquals({"status": "success"}, message)

    def assertReceivedMessage(self, name, message, messages):
        self.assertIn(name, messages)
        self.assertEquals(message, messages[name])

    def send_message(self, address, message):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(address)
        socket.send_json(message)

        return socket
Exemple #27
0
class TestPoller(unittest.TestCase):

    def setUp(self):
        context = zmq.Context()
        worker_socket = context.socket(zmq.REP)
        worker_socket.bind("ipc:///tmp/worker")
        frontend_socket = context.socket(zmq.REP)
        frontend_socket.bind("ipc:///tmp/frontend")

        sockets = {
            "worker": {"socket": worker_socket, "receive": worker_socket.recv_json, "send": worker_socket.send_json},
            "frontend": {"socket": frontend_socket, "receive": frontend_socket.recv_json, "send": worker_socket.send_json},
        }
        time = TimeStub()

        self.poller = Poller(sockets, time)

    def test_when_nobody_sends_message_poller_returns_empty_dictionary(self):
        messages, time = self.poller.poll(timeout=1)

        self.assertEquals({}, messages)
        self.assertEquals(1, time)

    def test_when_frontend_sends_message_poller_returns_that_message(self):
        message = {"model": "en-GB"}
        self.send_message("ipc:///tmp/frontend", message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("frontend", message, messages)

    def test_when_worker_sends_message_poller_returns_that_message(self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("worker", message, messages)

    def test_when_worker_and_frontend_send_message_poller_returns_both_messages(self):
        worker_message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", worker_message)

        frontend_message = {"model": "en-GB"}
        self.send_message("ipc:///tmp/frontend", frontend_message)

        messages, time = self.poller.poll(timeout=1)
        self.assertReceivedMessage("worker", worker_message, messages)
        self.assertReceivedMessage("frontend", frontend_message, messages)

    def test_when_worker_sends_two_messages_poller_should_return_both_messages_sequentially(self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})
        self.assertReceivedMessage("worker", message, messages)
        self.assertEquals(1, time)

        message = {"address": "tcp://127.0.0.1:2", "model": "en-GB"}
        self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})
        self.assertReceivedMessage("worker", message, messages)
        self.assertEquals(2, time)

    def test_when_worker_sends_message_it_should_be_able_to_recieve_reply(self):
        message = {"address": "tcp://127.0.0.1:1", "model": "en-GB"}
        socket = self.send_message("ipc:///tmp/worker", message)

        messages, time = self.poller.poll(timeout=1)
        self.poller.send("worker", {"status": "success"})

        message = socket.recv_json()
        self.assertEquals({"status": "success"}, message)

    def assertReceivedMessage(self, name, message, messages):
        self.assertIn(name, messages)
        self.assertEquals(message, messages[name])

    def send_message(self, address, message):
        context = zmq.Context()
        socket = context.socket(zmq.REQ)
        socket.connect(address)
        socket.send_json(message)

        import gevent
        gevent.sleep(0.05)

        return socket
Exemple #28
0
 def run(self):
     if(self.args.debugMode):
         Printer.debugging = True
     p = Poller(self.args.port)
     p.run()
from poller import Poller
from app import App
from client import CoapClient

UDP_IP = "localhost"
UDP_PORT = 5683
PATH = "ptc"

if __name__ == '__main__':
    poller = Poller()
    app = App(placa="placaA", sensores=["sensorA", "sensorB"])
    coap = CoapClient(UDP_IP, UDP_PORT, PATH)

    app._lower = coap
    coap._upper = app

    poller.adiciona(app)
    poller.adiciona(coap)

    poller.despache()
Exemple #30
0
#! /usr/bin/env python

from config import Config  # this is a subdir
from listener import Listener
from poller import Poller
import sys

if __name__ == "__main__":
    """Run the monitor. The listener class waits for requests. The
    poller class polls the PIDs that were input and forwards output
    to the output class."""
    parpid = sys.argv[1]
    cfg = Config()
    cfg.add_item('parentpid', parpid)
    lst = Listener(cfg)
    lst.start()
    print "listener started"
    # Where is the output class?

    pol = Poller(cfg)
    pol.start()
    print "Poller started"
class DPSinterface:
    """
    DSPinterface is a Tk graphical interface to drive a DPS power supplier.

    """
    def __init__(self, root):
        """
        Create a DSP interface instance.

        :param root: is the Tk() interface where the DPS will be drawedstring with the prot name i.e. /dev/ttyUSB0 or COM5 for Windows
        :returns: a new instance of DPS graphical interface

        """

        self.root = root
        root.title("DPS power supplier interface")
        root.protocol("WM_DELETE_WINDOW", self.wnwcmdclose)

        self.dps = None
        self.poller = None
        self.waver = None
        self.strtme = time()
        self.dpsfwave = None
        self.maxoutv = 5
        self.maxoutc = 5

        menubar = Menu(root)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", command=self.wnwcmdclose)
        menubar.add_cascade(label="File", menu=filemenu)

        scopemenu = Menu(menubar, tearoff=0)
        scopemenu.add_command(label="Load sampled points...",
                              command=self.mnucmdloadsmppts)
        scopemenu.add_command(label="Save sampled points as...",
                              command=self.mnucmdsavesmppts)
        menubar.add_cascade(label="Scope", menu=scopemenu)

        wavemenu = Menu(menubar, tearoff=0)
        wavemenu.add_command(label="New wave", command=self.mnucmdnewwve)
        wavemenu.add_command(label="Load wave...", command=self.mnucmdloadwve)
        wavemenu.add_command(label="Edit wave...", command=self.mnucmdedtwve)
        wavemenu.add_command(label="Save wave as...",
                             command=self.mnucmdsavewve)
        menubar.add_cascade(label="Wave", menu=wavemenu)

        memmenu = Menu(menubar, tearoff=0)
        memmenu.add_command(label="Edit memories...",
                            command=self.mnucmdedtmem)
        menubar.add_cascade(label="Memory", menu=memmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="Help...", command=self.mnucmdhelp)
        helpmenu.add_command(label="About...", command=self.mnucmdabout)
        menubar.add_cascade(label="Help", menu=helpmenu)

        root.config(menu=menubar)

        row = 0
        col = 0
        rowspan = 1
        colspan = 1
        insertlabelrow(root, row, col, ("Serial: ", None, "Addr,Baud: "), E)
        col += colspan
        self.svardpsport = StringVar()
        self.svardpsport.set('/dev/ttyUSB0')
        self.entryserport = Entry(root,
                                  textvariable=self.svardpsport,
                                  width=ENTRYWIDTH,
                                  justify='right')
        self.entryserport.grid(row=row, column=col, sticky=W)
        col += colspan
        col += colspan
        self.svardpsaddbrt = StringVar()
        self.svardpsaddbrt.set('1, 9600')
        self.entrydpsadd = Entry(root,
                                 textvariable=self.svardpsaddbrt,
                                 width=ENTRYWIDTH,
                                 justify='right')
        self.entrydpsadd.grid(row=row, column=col, sticky=W)
        col += colspan
        colspan = 2
        self.ivarconctd = IntVar()
        self.ivarconctd.set(0)
        Checkbutton(root,
                    variable=self.ivarconctd,
                    text='Connect',
                    command=self.butcmdconnect).grid(row=row,
                                                     column=col,
                                                     columnspan=colspan,
                                                     sticky=E + W)

        row += rowspan
        col = 0
        colspan = 1
        Separator(root, orient='horizontal').grid(row=row,
                                                  columnspan=8,
                                                  sticky=E + W,
                                                  pady=8)

        row += rowspan
        rowspan = 1
        colspan = 2
        col = 0
        self.ivarbrghtnes = IntVar()
        s = Scale(root,
                  label='Brightness',
                  variable=self.ivarbrghtnes,
                  from_=0,
                  to=5,
                  resolution=1,
                  orient="horizontal")
        s.bind("<ButtonRelease-1>", self.sclbndbrghtnss)
        s.grid(row=row, column=col, columnspan=colspan, sticky=E + W)
        col += colspan
        colspan = 1
        Label(root, text="Model: ").grid(row=row, column=col, sticky=E)
        col += colspan
        self.ivarmodel = IntVar()
        Entry(root,
              textvariable=self.ivarmodel,
              state="readonly",
              width=ENTRYWIDTH,
              justify='right').grid(row=row, column=col, sticky=W)
        col += colspan
        colspan = 2
        self.ivarsetmem = IntVar()
        s = Scale(root,
                  label='Mem Recall',
                  variable=self.ivarsetmem,
                  from_=1,
                  to=9,
                  resolution=1,
                  orient="horizontal")
        s.bind("<ButtonRelease-1>", self.sclbndmemory)
        s.grid(row=row, column=col, columnspan=colspan, sticky=E + W)

        row += rowspan
        colspan = 1
        col = 0
        insertlabelrow(
            root, row, col,
            (("Vinp [V]: ", VCOL), None, "Out Mode: ", None, "Protection: "),
            E)
        self.dvarvinp = DoubleVar()
        self.svarwrmde = StringVar()
        self.setworkmode(0)
        self.svarprot = StringVar()
        self.setprotection(0)
        insertentryrow(
            root, row, col,
            (None, self.dvarvinp, None, self.svarwrmde, None, self.svarprot),
            'right', W, 'readonly')

        colspan = 1
        row += rowspan
        col = 0
        insertlabelrow(root, row, col,
                       (("Vmax [V]: ", VCOL), None, ("Cmax [A]: ", CCOL), None,
                        ("Pmax [W]: ", PCOL)), E)
        self.dvarvmaxm0 = DoubleVar()
        self.dvarcmaxm0 = DoubleVar()
        self.dvarpmaxm0 = DoubleVar()
        entries = insertentryrow(root, row, col,
                                 (None, self.dvarvmaxm0, None, self.dvarcmaxm0,
                                  None, self.dvarpmaxm0), 'right', W)
        for e, f in zip(entries,
                        (self.entbndvmax, self.entbndcmax, self.entbndpmax)):
            e.bind('<FocusOut>', f)
            e.bind('<Return>', f)

        row += rowspan
        col = 0
        insertlabelrow(root, row, col,
                       (("Vout [V]: ", VCOL), None, ("Cout [A]: ", CCOL), None,
                        ("Pout [W]: ", PCOL)), E)
        self.dvarvout = DoubleVar()
        self.dvarcout = DoubleVar()
        self.dvarpout = DoubleVar()
        insertentryrow(
            root, row, col,
            (None, self.dvarvout, None, self.dvarcout, None, self.dvarpout),
            'right', W, 'readonly')

        row += rowspan
        col = 0
        self.scope = Scope(root, [], row, col)

        row += 9
        col = 4
        Label(root, text="Rte[s/Sa]: ").grid(row=row, column=col, sticky=E)
        col += colspan
        self.dvarsecsmp = DoubleVar()
        self.dvarsecsmp.set(self.scope.sampletime())
        e = Entry(root,
                  textvariable=self.dvarsecsmp,
                  width=ENTRYWIDTH,
                  justify='right').grid(row=row, column=col, sticky=W)

        row += rowspan
        col = 0
        colspan = 2
        self.ivaracquire = IntVar()
        self.ivaracquire.set(0)
        Checkbutton(root,
                    variable=self.ivaracquire,
                    text='Run Acquisition',
                    command=self.butcmdacquire).grid(row=row,
                                                     column=col,
                                                     columnspan=2,
                                                     sticky=E + W)
        col += colspan
        self.ivarkeylock = IntVar()
        self.ivarkeylock.set(0)
        Checkbutton(root,
                    variable=self.ivarkeylock,
                    text="Key Lock",
                    command=self.butcmdkeylock).grid(row=row,
                                                     column=col,
                                                     sticky=E + W,
                                                     columnspan=colspan)
        col += colspan
        self.ivaroutenab = IntVar()
        self.ivaroutenab.set(0)
        Checkbutton(root,
                    variable=self.ivaroutenab,
                    text="Output Enable",
                    command=self.butcmdoutenable).grid(row=row,
                                                       column=col,
                                                       sticky=E + W,
                                                       columnspan=colspan)

        row += rowspan
        col = 0
        rowspan = 1
        colspan = 3
        self.dvarvscale = DoubleVar()
        self.voltscale = Scale(root,
                               label='Vset [V]',
                               foreground=VCOL,
                               variable=self.dvarvscale,
                               from_=0,
                               to=self.maxoutv,
                               resolution=1,
                               orient="horizontal")  #, label='Vset[V]'
        self.voltscale.bind("<ButtonRelease-1>", self.sclbndvolt)
        self.voltscale.grid(row=row,
                            column=col,
                            columnspan=colspan,
                            sticky=E + W)
        col += colspan
        self.dvarcscale = DoubleVar()
        self.curntscale = Scale(root,
                                label='Cset[A]',
                                foreground=CCOL,
                                variable=self.dvarcscale,
                                from_=0,
                                to=self.maxoutc,
                                resolution=1,
                                orient="horizontal")  #,label='Cset[A]'
        self.curntscale.bind("<ButtonRelease-1>", self.sclbndcrnt)
        self.curntscale.grid(row=row,
                             column=col,
                             columnspan=colspan,
                             sticky=E + W)

        row += rowspan
        col = 0
        self.dvarvscalef = DoubleVar()
        sc = Scale(root,
                   foreground=VCOL,
                   variable=self.dvarvscalef,
                   from_=0,
                   to=0.99,
                   resolution=0.01,
                   orient="horizontal")
        sc.bind("<ButtonRelease-1>", self.sclbndvolt)
        sc.grid(row=row, column=col, columnspan=colspan, sticky=E + W)
        col += colspan
        self.dvarcscalef = DoubleVar()
        sc = Scale(root,
                   foreground=CCOL,
                   variable=self.dvarcscalef,
                   from_=0,
                   to=0.99,
                   resolution=0.01,
                   orient="horizontal")
        sc.bind("<ButtonRelease-1>", self.sclbndcrnt)
        sc.grid(row=row, column=col, columnspan=colspan, sticky=E + W)

        row += rowspan
        col = 0
        colspan = 1
        Separator(root, orient='horizontal').grid(row=row,
                                                  columnspan=6,
                                                  sticky=E + W,
                                                  pady=8)

        row += rowspan
        colspan = 1
        col = 0
        Label(root, text="Waveform: ").grid(row=row, column=col, sticky=E)
        col += colspan
        colspan = 2
        self.svarwave = StringVar()
        Entry(root,
              textvariable=self.svarwave,
              width=ENTRYWIDTH,
              justify='right',
              state='readonly').grid(row=row,
                                     column=col,
                                     columnspan=colspan,
                                     sticky=E + W)
        col += colspan
        colspan = 1
        self.ivarplaywv = IntVar()
        self.ivarplaywv.set(0)
        Checkbutton(root,
                    variable=self.ivarplaywv,
                    text='Play',
                    command=self.butcmdplaywave).grid(row=row,
                                                      column=col,
                                                      sticky=E + W)
        col += colspan
        self.ivarpausewv = IntVar()
        self.ivarpausewv.set(0)
        Checkbutton(root,
                    variable=self.ivarpausewv,
                    text='Pause',
                    command=self.butcmdpausewave).grid(row=row,
                                                       column=col,
                                                       sticky=E + W)
        col += colspan
        self.ivarloopwv = IntVar()
        self.ivarloopwv.set(0)
        Checkbutton(root, variable=self.ivarloopwv,
                    text='Loop').grid(row=row, column=col, sticky=E + W)

        self.scope.update()
        self.scope.redraw()

    def sclbndvolt(self, event):
        """
        Voltage scale bind command to set the voltage on the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            self.dps.set(['vset'], [self.getvscale()])

    def sclbndcrnt(self, event):
        """
        Current scale bind command to set the current on the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            self.dps.set(['cset'], [self.getcscale()])

    def sclbndmemory(self, event):
        """
        Memory-set bind command to set the memory on the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            m = self.ivarsetmem.get()
            self.dps.set(['mset'], [m])
            self.updatefields(True)

    def sclbndbrghtnss(self, event):
        """
        Brightness bind command to set the brightness on the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            b = self.ivarbrghtnes.get()
            self.dps.set(['brght'], [b])

    def mnucmdnewwve(self):
        """
        New wave menu command to initialize a new wave.

        """
        self.dpsfwave = Dpsfile()
        self.svarwave.set('unnamed')

    def mnucmdloadwve(self):
        """
        Load wave menu command to load a wave file.

        """
        fname = tkFileDialog.askopenfilename(initialdir=".",
                                             title="Select wave file to load",
                                             filetypes=(("dps files", "*.dps"),
                                                        ("all files", "*.*")))
        if fname:
            self.svarwave.set(os.path.basename(fname))
            self.dpsfwave = Dpsfile()
            self.dpsfwave.load(fname)

    def mnucmdedtwve(self):
        """
        Edit wave menu command to open the edit wave window.

        """
        if self.dpsfwave is not None:
            Wveinterface(self.root, self.dpsfwave.getpoints())
        else:
            tkMessageBox.showinfo('No wave loaded',
                                  'Load or create a new wave file to modify')

    def mnucmdsavewve(self):
        """
        Save wave menu command to save the current wave in memory.

        """
        if self.dpsfwave is not None:
            fname = tkFileDialog.asksaveasfilename(
                initialdir=".",
                title="Select wave file to save",
                filetypes=(("dps files", "*.dps"), ("all files", "*.*")))
            if fname:
                self.dpsfwave.save(fname)
                self.svarwave.set(os.path.basename(fname))
        else:
            tkMessageBox.showinfo('No wave in memory',
                                  'Load or create a wave file to modify')

    def mnucmdloadsmppts(self):
        """
        Load sampled points menu command to load in the graphical view sampled before.

        """
        fname = tkFileDialog.askopenfilename(initialdir=".",
                                             title="Select data file to load",
                                             filetypes=(("dps files", "*.dps"),
                                                        ("all files", "*.*")))
        if fname:
            self.scope.load(fname)

    def mnucmdsavesmppts(self):
        """
        Save sampled points menu command to save the last points sampled showed in the graphical view.

        """
        fname = tkFileDialog.asksaveasfilename(
            initialdir=".",
            title="Select data file to save",
            filetypes=(("dps files", "*.dps"), ("all files", "*.*")))
        if fname:
            self.scope.save(fname)

    def mnucmdedtmem(self):
        """
        Memory menu command to edit the values of preset memories on DSP.

        """
        if self.isconnected():
            Meminterface(self.root, self.dps, self.updatefields)

    def mnucmdabout(self):
        """
        About menu command to show the window with program information.

        """
        Txtinterface(
            self.root, 'About', """DPS interface is designed by Simone Pernice

That project was born as a textual driver to interface any DPS device.
After the driver I made also a graphical interface to manage DPS devices.

This project was born because I was not able to find any Linux
application to manage DPS devices via USB.

For question email to me: [email protected]
Version {} relesed on {}
First release on 3rd February 2019 Turin Italy
DPS interface is under licence {}

If you like this program please make a donation with PayPal to [email protected]"""
            .format(__version__, __date__, __license__))

    def mnucmdhelp(self):
        """
        Help menu command to show basic help on usage.

        """
        Txtinterface(
            self.root, 'Help',
            """This is an interface to remote controll a power supplier of DPS series.
The white fields can be edited, the gray are read only.
To connect to DPS power supplier first link it to the PC through an USB cable.
The data required to connect is on the first row of the graphical interface.
Write the serial address on the first field (COMxx for Windows or 
/dev/ttyUSBx for Linux).
Address and baudrate do not require update because they are the default 
for DPS power supplier. Turn on DPS with up key pressed to change those values.
Press 'Connect' check button and if the device is present it is linked. 
Press again the same check button to disconnect the DPS.
Once the link to DPS is in place all the data on the interface are updated and 
on the DPS the keylock is set. 
The second block of graphical interface contains all data about DPS.
The brightness set which can be changed through the scale regulation.
The model number. The memory from which recall the preset parameters.
The input voltage, the output mode cv (constant voltage) or cc (constant current).
The protection mode: none (no protection triggered), ovp (over voltage protection), 
ocp (over current protection), opp (over power protection).
The maximum voltage, current and power to provide before triggering the 
self protection.
The next row contains output voltage, current and power in textual form.
A time diagram of the DPS output voltage, current and power is avaiable. 
It is possible to play with the mouse on that screen:
- wheel press to fit in the screen all the enabled drawings
- wheel to zoom in time
- shift+wheel to zoom on Y for the highlighted curves
- ctrl+wheel to change the enabled curves
- left button drag to move the highlighted curve
The same mouse functions are available in the fields below the diagram:
- voltage per division, current per division and watt per division
- zero position for voltage, current and power
- check button to view voltage, current and power
- time: second per divisions and zero position for time
The sample time is used for the acquisition. DPS is quite slot, the minimum read
time is around 1 second. The suggested rate is to have a sample for displayed pixel.
The next buttons are:
- Run acquisition: starts a thread that read the DPS status, update the interface 
fields as well as the time diagram. 
The acquisition points can be saved and loaded to be showed lated with menu 
commands on DPS scope load/save. They can be also edited through the
wave edit window and played.
- Key lock: set or reset the DPS key lock. It should be on in order to have faster
communication. If key lock is on less fields of DPS are read since user can 
change them only through the PC interface.
- Output enable to enable the DPS output
Eventually there are the voltage and current scale. Thery are split in two:
- the first  is for coarse (1 unit/step) adjustment the unit of voltage/current 
- the second is for fine (0.01 unit/step) adjustament of voltage/current
On the last block of interface there is a waveform field showing the wave loaded.
Wave is a set of required output voltage and current at give timings. It is possible
play and pause it through the respective commands of the interface. If loop is
set when the wave play is completed it restarts.
The acquisition may slow the wave player, use low acquisition sample time 
to avoid delays.""")

    def butcmdconnect(self):
        """
        Connect check button command to connect to the DSP.

        It reads: serial port address, DPS address and serial speed from other interface fields.
        If it is capable to link to the DPS: 
        - the maximum voltage and current are read and scale maximums set accordingly
        - the DPS current data are read and set accordingly in the interface
        - the localDPS interface is locked so that the user cannot change them but has to go through the graphical interface
         if the DPS is locked the polling is faster because less data needs to be read from DPS 
        - the input fields are disabled
        """
        if self.ivarconctd.get():
            try:
                flds = self.svardpsaddbrt.get().split(',')
                if len(flds) > 0:
                    ch = int(flds[0])
                else:
                    ch = 1
                if len(flds) > 1:
                    br = int(flds[1])
                else:
                    br = 9600
                self.dps = DPSdriver(self.svardpsport.get(), ch, br)
            except Exception as e:
                tkMessageBox.showerror('Error', 'Cannot connect: ' + str(e))
                self.ivarconctd.set(0)
                self.dps = None
                return

            m = self.dps.get(['model'])
            m = m[0]
            self.ivarmodel.set(m)

            to = m / 100
            self.voltscale.config(to=to)
            self.maxoutv = to

            to = m % 100
            self.curntscale.config(to=to)
            self.maxoutv = to

            self.scope.resetpoints()

            self.ivarkeylock.set(1)
            self.butcmdkeylock()
            self.updatefields(True)

            self.entryserport.config(state='readonly')
            self.entrydpsadd.config(state='readonly')
        else:
            # Stop polling
            self.ivaracquire.set(0)
            if self.poller:
                self.poller.wake()
                time.sleep(1.)  # Wait to be sure the thread exits

            # Stop waveform generation
            self.ivarplaywv.set(0)
            if self.waver:
                self.waver.wake()
                time.sleep(1.)  # Wait to be sure the thread exits

            self.dps = None

            self.entryserport.config(state=NORMAL)
            self.entrydpsadd.config(state=NORMAL)

    def butcmdacquire(self):
        """
        Acquire check button command to manage the acquisition thread to read the DSP data.
        If the button is not selected the thread is lunched.
        If the button is selected the thread is stopped.

        """
        if self.ivaracquire.get():
            if not self.isconnected():
                self.ivaracquire.set(0)
                return
            self.scope.resetpoints()
            self.strtme = time()
            self.poller = Poller(self.ivaracquire, self.dvarsecsmp,
                                 self.updatefields)
        else:
            self.poller.wake()

    def butcmdkeylock(self):
        """
        Key lock button command to enable or disable the key lock on DPS remote interface.

        """
        if self.isconnected():
            self.dps.set(['lock'], [self.ivarkeylock.get()])
        else:
            self.ivarkeylock.set(0)

    def butcmdoutenable(self):
        """
        DPS output button command to enable or disable the DPS output power.

        """
        if self.isconnected():
            self.dps.set(['onoff'], [self.ivaroutenab.get()])
        else:
            self.ivaroutenab.set(0)

    def butcmdplaywave(self):
        """
        Wave generator  check button command to manage the wave generation thread to make a waveform on the DSP.
        If the button is not selected the thread is lunched.
        If the button is selected the thread is stopped.

        """
        if self.ivarplaywv.get():
            if not self.isconnected():
                self.ivarplaywv.set(0)
                return
            if not self.dpsfwave:
                tkMessageBox.showinfo('No wave in memory',
                                      'Load or create a wave file to modify')
                self.ivarplaywv.set(0)
                return
            if not self.ivaroutenab.get():
                self.ivaroutenab.set(1)
                self.butcmdoutenable()
            self.waver = Waver(self.setvcdps, self.ivarplaywv,
                               self.ivarpausewv, self.ivarloopwv,
                               self.dpsfwave.getpoints())
        else:
            self.waver.wake()

    def butcmdpausewave(self):
        """
        Wave generator  pause check button command to temporary pause the wave generations.

        """
        self.waver.wake()

    def wnwcmdclose(self):
        """
        DPS main window close. Before exiting the supplier is disconnected the external supplier.

        """
        if self.ivarconctd.get():
            self.ivarconctd.set(0)
            self.butcmdconnect()

        self.root.destroy()

    def entbndvmax(self, event):
        """
        Maximum voltage entry bind to set the protection maximum ouput voltage of the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            if self.dvarvmaxm0.get() > self.maxoutv * PROTEXCEED:
                self.dvarvmaxm0.set(self.maxoutv * PROTEXCEED)
            elif self.dvarvmaxm0.get() < 0.:
                self.dvarvmaxm0.set(0.)
            self.dps.set(['m0ovp'], [self.dvarvmaxm0.get()])

    def entbndcmax(self, event):
        """
        Maximum current entry bind to set the protection maximum output curret of the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            if self.dvarcmaxm0.get() > self.maxoutc * PROTEXCEED:
                self.dvarcmaxm0.set(self.maxoutc * PROTEXCEED)
            elif self.dvarcmaxm0.get() < 0.:
                self.dvarcmaxm0.set(0.)
            self.dps.set(['m0ocp'], [self.dvarcmaxm0.get()])

    def entbndpmax(self, event):
        """
        Maximum power entry bind to set the protection maximum output power of the DSP.

        :param event: the event describing what changed

        """
        if self.isconnected():
            if self.dvarpmaxm0.get(
            ) > self.maxoutv * self.maxoutc * PROTEXCEED * PROTEXCEED:
                self.dvarpmaxm0.set(self.maxoutv * self.maxoutc * PROTEXCEED *
                                    PROTEXCEED)
            elif self.dvarpmaxm0.get() < 0.:
                self.dvarcmaxm0.set(0.)
            self.dps.set(['m0opp'], [self.dvarpmaxm0.get()])

    def setvcdps(self, v, c):
        """
        Set the DPS output voltage and current moving their scales accordingly.

        :param v: the required voltage, if negative it is not changed
        :param c: the required current, if negative it is not changed

        """
        if v >= 0:
            if c >= 0:
                self.setvscale(v)
                self.setcscale(c)
                self.dps.set(['vset', 'cset'], [v, c])
            else:
                self.setvscale(v)
                self.dps.set(['vset'], [v])
        elif c >= 0:
            self.setcscale(c)
            self.dps.set(['cset'], [c])

    def isconnected(self):
        """
        Check if the DPS is connected, if not display a message.

        :returns: True if connected, False if not

        """
        if self.dps is None:
            tkMessageBox.showinfo('Not connected',
                                  'Enstablish a connection before')
            return False
        return True

    def setvscale(self, v):
        """
        Set the voltage scale, nothing is changed on the DPS.

        :param v: the voltage to set

        """
        if v > self.maxoutv: v = self.maxoutv
        elif v < 0: v = 0
        self.dvarvscale.set(int(v))
        self.dvarvscalef.set(round(v - int(v), 2))

    def getvscale(self):
        """
        Get the voltage scale set value.

        :returns: the voltage set

        """
        return self.dvarvscale.get() + self.dvarvscalef.get()

    def setcscale(self, c):
        """
        Set the current scale, nothing is changed on the DPS.

        :param c: the current to set

        """
        if c > self.maxoutc: c = self.maxoutc
        elif c < 0: c = 0
        self.dvarcscale.set(int(c))
        self.dvarcscalef.set(round(c - int(c), 2))

    def getcscale(self):
        """
        Get the current scale set value.

        :returns: the current set

        """
        return self.dvarcscale.get() + self.dvarcscalef.get()

    def updatefields(self, forcereadall=False):
        """
        Reads data stored in DPS and updates the interface fields accordingly. 
        
        In order to be as fast as possible, if keylock is enabled, reads only the fields that can change without uses access.
        If keylock is disabled all the fields are read because user may have changed something from the interface.

        :param forcereadall: if True read and update all the DPS fields regardless of the keylock status
        :returns: the point read. A point is made by (time, voltage, current, power)

        """
        if not forcereadall and self.ivarkeylock.get(
        ):  # If user keep locked fewer data are read, otherwise all
            data = self.dps.get(
                ['vout', 'cout', 'pout', 'vinp', 'lock', 'prot', 'cvcc'])
            self.dvarvout.set(data[0])
            self.dvarcout.set(data[1])
            self.dvarpout.set(data[2])
            self.dvarvinp.set(data[3])
            self.ivarkeylock.set(data[4])
            self.setprotection(data[5])
            self.setworkmode(data[6])
            vcp = data[0:3]

        else:  # All data is read
            data = self.dps.get([
                'vset', 'cset', 'vout', 'cout', 'pout', 'vinp', 'lock', 'prot',
                'cvcc', 'onoff', 'brght', 'mset', 'm0ovp', 'm0ocp', 'm0opp'
            ])
            self.setvscale(data[0])
            self.setcscale(data[1])
            self.dvarvout.set(data[2])
            self.dvarcout.set(data[3])
            self.dvarpout.set(data[4])
            self.dvarvinp.set(data[5])
            self.ivarkeylock.set(data[6])
            self.setprotection(data[7])
            self.setworkmode(data[8])
            self.ivaroutenab.set(data[9])
            self.ivarbrghtnes.set(data[10])
            self.ivarsetmem.set(data[11])
            self.dvarvmaxm0.set(data[12])
            self.dvarcmaxm0.set(data[13])
            self.dvarpmaxm0.set(data[14])
            vcp = data[2:5]

        vcp.insert(TPOS, time() - self.strtme)
        self.scope.addpoint(vcp)
        return vcp

    def setprotection(self, p):
        """
        Set the protection field with an user readable string explaining the DPS protection status.

        :param p: the protection statu returned by the DPS

        """
        self.svarprot.set({0: 'none', 1: 'ovp', 2: 'ocp', 3: 'opp'}[p])

    def setworkmode(self, wm):
        """
        Set the workmode field with an user readable string explaining the DPS work mode.

        :param wm: the working mode returned by the DPS

        """
        self.svarwrmde.set({0: 'cv', 1: 'cc'}[wm])
Exemple #32
0
def parse_info(info: dict):
    return info


def collect_redis_info(mgr):
    info = mgr.info()
    return parse_info(info)


def sensor():
    value = collect_redis_info(target_mgr)
    value["time"] = get_current_timestamp()
    store_mgr.append(json.dumps(value))


poller = Poller.instance()
poller.add(sensor, POLLING_INTERVAL)


def make_histories(values):
    l = len(values)
    p0 = values[0]
    c = p0['total_commands_processed']
    tc = []
    labels = []
    rss = []
    for i in range(1, l):
        p = values[i]['total_commands_processed']
        label = datetime.datetime.fromtimestamp(
            values[i]['time']).strftime("%Y-%m-%d %H:%M:%S")
        rs = values[i]['used_memory_rss'] / 1024 / 1024 / 1024
Exemple #33
0
                   action=EnvDefault,
                   envvar="SLACK_WEBHOOK_URL",
                   type=str,
                   default=None,
                   required=False,
                   help="Slack webhook URL for sending scaling alerts")
    p.add_argument("--slack-channel",
                   dest="slack_channel",
                   action=EnvDefault,
                   envvar="SLACK_CHANNEL",
                   type=str,
                   default='#deploy',
                   required=False,
                   help="Slack channel to scaling alerts")
    return p.parse_args()


def add_args_to_settings(cli_args):
    for name, value in vars(cli_args).iteritems():
        setattr(settings, name, value)


if __name__ == "__main__":
    args = parse_cli_args()
    add_args_to_settings(args)
    setup_logging(args)
    logging.info(args)
    poller = Poller(args)
    poller.start()
    sys.exit(0)
Exemple #34
0
 def _startPoller(self):
     poller = Poller(self.sock_path,self.q,self.sleep)
     poller.start()
     poller.join()
Exemple #35
0
class DataLogger:
    def __init__(self):
        self._influx = None
        self._poller = Poller()

        self._database_name = DEFAULT_DATABASE
        self._num_polling_threads = DEFAULT_NUM_POLLING_THREADS

    def load_config(self, filename):
        config_str = open(filename).read()
        logging.info(config_str)
        config = json.loads(config_str)

        self._database_name = config["database"]
        self._num_polling_threads = config.get("polling_threads", DEFAULT_NUM_POLLING_THREADS)
        self._poller.set_items_config(config["items"])

    def get_config(self):
        config = {
            "database": self._database_name,
            "polling_threads": self._num_polling_threads,
            "items": self._poller.get_items_config()
        }
        return config

    def add_item(self, name, key, interval, arg=None):
        self._poller.add_item(name, key, arg, interval)
        logging.info("item added: {0}".format(name))

    def delete_item(self, name):
        self._poller.delete_item(name)
        logging.info("item deleted: {0}".format(name))

    def get_items(self):
        return self._poller.get_items()

    def get_item(self, name):
        return self._poller.get_item(name)

    def create_test_items(self):
        self._poller.add_item("loadavg1 1s", "system.loadavg1", None, 1)
        self._poller.add_item("loadavg1 5s", "system.loadavg1", None, 5)
        self._poller.add_item("loadavg1 60s", "system.loadavg1", None, 60)

        self._poller.add_item("ping google.com.au", "net.ping", "google.com.au", 1)
        self._poller.add_item("ping google.com", "net.ping", "google.com", 1)
        self._poller.add_item("ping www.microsoft.com", "net.ping", "www.microsoft.com", 1)
        self._poller.add_item("ping www.tesla.co", "net.ping", "www.tesla.co", 1)

        self._poller.add_item("switch1 power", "wemo.power", "switch1", 1)
        self._poller.add_item("switch1 state", "wemo.state", "switch1", 1)

        self._poller.add_item("sensehat temperature", "sensehat.temperature", None, 10)
        self._poller.add_item("sensehat humidity", "sensehat.humidity", None, 10)
        self._poller.add_item("sensehat pressure", "sensehat.pressure", None, 10)

    def run(self):
        self._influx = InfluxDBClient("localhost", 8086)
        self._influx.create_database(self._database_name)
        self._influx.switch_database(self._database_name)

        self._poller.run(self._num_polling_threads, self._process_results)

    def _build_points(self, items):
        """build a list of influx data points from the given list of PollItems"""
        fields = {}
        for item in items:
            fields[item.name] = item.last_value

        point = {
            "measurement": "rpdemo",
            "fields": fields
        }

        return [point]

    def _process_results(self, items):
        # build influx points from the results and write them to influx DB
        points = self._build_points(items)

        logging.debug("{0}".format(points))

        self._influx.write_points(points)
Exemple #36
0
	def run(self):
		p = Poller(self.args.port)
		p.run()
Exemple #37
0
class Bot:
    def __init__(self, token, vk_client_id):
        self.poller = Poller()
        self.updater = Updater(token=token)
        self.vk = Vk(vk_client_id)
        self.clients = Client.all_from_db()

        self.reg_actions()
        self.restore()

    def run(self):
        self.poller.async_run(self.on_update)
        self.updater.start_polling()
        self.updater.idle()
        self.poller.stop()
        self.persist()
        db.close()

    def persist(self):
        for _, client in self.clients.items():
            client.persist()

    def restore(self):
        for _, client in self.clients.items():
            self.add_poll_server(client)

    def reg_actions(self):
        dispatcher = self.updater.dispatcher
        dispatcher.addTelegramCommandHandler('start', self.start)
        dispatcher.addTelegramCommandHandler('whoami', self.whoami)
        dispatcher.addTelegramCommandHandler('pick', self.pick)
        dispatcher.addTelegramCommandHandler('unpick', self.unpick)
        dispatcher.addTelegramCommandHandler('details', self.details)
        dispatcher.addErrorHandler(self.error)
        dispatcher.addUnknownTelegramCommandHandler(self.unknown)
        dispatcher.addTelegramMessageHandler(self.on_message)

    def start(self, bot, update):
        chat_id = update.message.chat_id
        auth_url = self.vk.get_auth_url()
        # Send first info messages
        bot.sendMessage(chat_id=chat_id,
                        text=message.WELCOME(auth_url),
                        reply_markup=ReplyKeyboardHide())
        bot.sendMessage(chat_id=chat_id, text=message.COPY_TOKEN)
        # Create new client
        client = Client(next_action=action.ACCESS_TOKEN, chat_id=chat_id)
        self.clients[chat_id] = client
        client.persist()

    def whoami(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            return

        client = self.clients[chat_id]
        bot.sendMessage(chat_id=chat_id,
                        text=message.WHOAMI(client.vk_user.get_name()),
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def pick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        recepient = update.message.text[6:]
        client.expect_message_to(recepient)
        bot.sendMessage(chat_id=chat_id,
                        text=message.TYPE_MESSAGE(recepient),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def unpick(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.next_action = action.NOTHING
        client.persist()
        bot.sendMessage(chat_id=chat_id,
                        text=message.UNPICK(client.next_recepient.get_name()),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))
        client.next_recepient = None

    def details(self, bot, update):
        chat_id = update.message.chat_id
        if not chat_id in self.clients:
            self.start(bot, update)
            return

        client = self.clients[chat_id]
        client.seen_now()
        user = client.next_recepient
        if user == None:
            bot.sendMessage(chat_id=chat_id,
                            text=message.FIRST_PICK_USER,
                            reply_markup=Bot.keyboard(
                                client.keyboard_markup()))
            return

        if user.photo != None:
            bot.sendPhoto(chat_id=chat_id, photo=user.photo)

        bot.sendMessage(chat_id=chat_id,
                        text=message.USER_NAME(user.get_name()),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

        participants = user.participants()
        if participants != None:
            bot.sendMessage(chat_id=chat_id,
                            text=message.PARTICIPANTS(participants),
                            parse_mode=ParseMode.MARKDOWN,
                            reply_markup=Bot.keyboard(
                                client.keyboard_markup()))

    def error(self, bot, update, error):
        logger.warn('Update "%s" caused error "%s"' % (update, error))

    def on_message(self, bot, update):
        chat_id = update.message.chat_id

        if not chat_id in self.clients:
            return self.start(bot, update)

        client = self.clients[chat_id]
        client.seen_now()

        if client.next_action == action.ACCESS_TOKEN:
            return self.on_token_message(bot, update, client)
        elif client.next_action == action.MESSAGE:
            return self.on_typed_message(bot, update, client)

        self.echo(update.message.chat_id)

    def on_token_message(self, bot, update, client):
        parseresult = urlparse(update.message.text)
        if parseresult.scheme == 'https':
            parseparams = parse_qs(parseresult.fragment)
            access_token = parseparams.get('access_token')[0]
            client.load_vk_user(access_token)
        else:
            client.load_vk_user(update.message.text)
        name = client.vk_user.get_name()
        client.next_action = action.NOTHING
        self.add_poll_server(client)
        bot.sendMessage(chat_id=update.message.chat_id,
                        text=message.TOKEN_SAVED(name),
                        reply_markup=Bot.keyboard(client.keyboard_markup()))

    def on_typed_message(self, bot, update, client):
        client.send_message(update.message.text)

    @run_async
    def add_poll_server(self, client):
        if client.vk_token != None:
            self.poller.add(client)

    def echo(self, chat_id):
        self.updater.bot.sendMessage(chat_id=chat_id, text=message.ECHO)

    def unknown(self, bot, update):
        bot.sendMessage(chat_id=update.message.chat_id, text=message.UNKNOWN)

    @staticmethod
    def keyboard(keyboard_markup):
        return ReplyKeyboardMarkup(keyboard_markup,
                                   selective=True,
                                   resize_keyboard=True)

    def on_update(self, updates, client):
        for update in updates:
            self.process_update(update, client)

    def process_update(self, update, client):
        if len(update) == 0:
            return

        if update[0] == 4:
            # When new message received
            self.receive_vk_message(update, client)

    def receive_vk_message(self, update, client):
        flags = update[2]
        from_id = update[3]
        text = update[6]
        attachments = update[7]

        if flags & 2 == 2:
            # Skip when message is outgoing
            return

        from_name = ''

        if from_id & 2000000000 == 2000000000:
            # Message came from chat
            chat_id = from_id - 2000000000
            chat = Vk_chat.fetch(client.vk_token, chat_id)
            from_name = chat.name_from(attachments['from'])
            client.add_interaction_with(chat)
        else:
            user = Vk_user.fetch_user(client.vk_token, from_id)
            from_name = user.get_name()
            client.add_interaction_with(user)

        self.updater.bot.sendMessage(chat_id=client.chat_id,
                                     text=message.NEW_MESSAGE(from_name, text),
                                     reply_markup=Bot.keyboard(
                                         client.keyboard_markup()),
                                     parse_mode=ParseMode.MARKDOWN)
        client.persist()
Exemple #38
0
fn = "C:\\Users\\CJ\\Music\\iTunes\\iTunes Media\\Music\\Vanilla Ice\\To the Extreme\\01 Ice Ice Baby.m4a"

songs = {
         "+17859798181" : "C:\\Users\\CJ\\Music\\iTunes\\iTunes Media\\Music\\Vanilla Ice\\To the Extreme\\01 Ice Ice Baby.m4a",
         "+17853934228" : "C:\\Users\\CJ\\Music\\iTunes\\iTunes Media\\Music\\Waka Flocka Flame\\No Hands (feat. Roscoe Dash & Wale) - Si\\01 No Hands (feat. Roscoe Dash & Wal.m4a",
        }

if __name__ == '__main__':
   # While not killed
   # Poll texts
   # Once one has been found
   #  pause music
   #  queue up theme song
   s = MusicServer()
   p = Poller()
#   s.interrupt(fn)
   try:
      while True:
         for i in p.poll():
            if songs.has_key(i):
               song = songs[i]
            else:
               song = fn
            s.interrupt(song)
         print "wait"
         time.sleep(30)
         continue
   except Exception, e:
      print str(e)
Exemple #39
0
 def run(self):
     p = Poller(self.args.port, self.args.debug)
     p.run()
 def run(self):
     p = Poller(self.args.port)
     p.run()
Exemple #41
0
#! /usr/bin/env python


from config import Config # this is a subdir
from listener import Listener
from poller import Poller
import sys

if __name__ == "__main__":
    """Run the monitor. The listener class waits for requests. The
    poller class polls the PIDs that were input and forwards output
    to the output class."""
    parpid = sys.argv[1]
    cfg = Config()
    cfg.add_item('parentpid',parpid)
    lst = Listener(cfg)
    lst.start()
    print "listener started"
    # Where is the output class?
    
    pol = Poller(cfg)   
    pol.start()
    print "Poller started"
Exemple #42
0
def handler(name, hostname, username, password, timeout, port):
    _poller = Poller(name, hostname, username, password, timeout, port)
    if _poller.open():
        thread = Thread(target= _poller.read)
    else: