def osc_callback(self,message,*args):
     try:
         if message[2] == 'Play':
             self.play()
         elif message[2] == 'Pause':
             self.pause()
     except Exception as e: osc.sendMsg('/some_api', [str(e)], port=3002)
Esempio n. 2
0
 def send_modify_result(self, _id, status=None):
     L.debug("Send modify result %d" % _id)
     pickle_msg = pickle.dumps({
         'response': 'modify',
         'id': _id,
         'status': status})
     osc.sendMsg('/android_park', [pickle_msg, ], port=3334)
Esempio n. 3
0
 def rpcout(self, message, *args):
     """
     Send a message to osc channel
     """
     osc.sendMsg('/rpc', [
         message,
     ], port=3001)
Esempio n. 4
0
    def start_service(self):
        """Start the service"""
        self.save_settings()
        print("Starting service")
        self.service_running = False
        osc.sendMsg("/status", [], port=3000)
        osc.sendMsg("/progress", [], port=3000)
        sleep(0.1)
        osc.readQueue(self.oscid)
        if not self.service_status:
            # Wait a little longer and try again
            sleep(0.5)
            osc.readQueue(self.oscid)

        if not self.service_status:
            print("Start_service: Service is not running, starting")
            if self.service is None:

                if platform == "android":
                    from android import AndroidService
                    self.service = AndroidService("Optimal file sync service", "running")
                    self.service.start("service started")
                else:
                    # Start process on linux.
                    print("Running on !android initializing service using Popen.")
                    self.service = subprocess.Popen(args = ["python", "./service/main.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        else:
            print("Start_service: Service is already running, not starting.")
Esempio n. 5
0
 def build(self):
     # the root is created in pictures.kv
     self.root
     self.osc_id = osc.listen(ipAddr='0.0.0.0', port=activity_port)
     if platform == 'android':
         from android import AndroidService
         service = AndroidService('Mentor Service', 'running')
         service.start('service started')
         self.service = service
     # get any files into images directory
     curdir = dirname(__file__)
     list = glob(join(curdir, 'images', '*'))
     Logger.debug("{}".format(list))
     shuffle(list)
     Logger.debug("{}".format(list))
     for filename in list:
         try:
             # load the image
             picture = Picture(source=filename, id=filename, rotation=randint(-30, 30))
             # add to the main field
             self.root.add_widget(picture)
         except Exception as e:
             Logger.exception('Pictures: Unable to load <%s>' % filename)
     osc.init()
     self.last_name = ""
     osc.sendMsg('/say', ["La ap di Michele e' pronta", ], port=service_port)
     return self.root
Esempio n. 6
0
def on_success(req,result):
	#self.ids.update_time.text = 'updated: processing...'
	global markov_graph
	global markov_title
	markov_title, markov_graph = process_result(result)
	osc.sendMsg('/some_api', ['UPDATE_DB','success',asctime(localtime()), ], port=activityport)
	print 'success'
Esempio n. 7
0
    def push_alerts(self, alerts):
        message = {"alerts": {}}
        for i, a in alerts.items():
            message["alerts"][i] = {
                "expected_request_id":
                a[0],
                "expected_request_name":
                expected.ExpectedRequestManager.i(
                ).get_expected_result_request_module_name(a[0]),
                "timestamp":
                datetime.datetime.fromtimestamp(int(
                    a[1]["timestamp"])).strftime('%Y-%m-%d %H:%M:%S'),
                "response":
                a[1]["response"],
                "unique_analyses":
                a[1]["unique_analyses"],
                "expected_request_configuration":
                expected.ExpectedRequestManager.i().
                get_expected_result_request_module_configuration(a[0]),
            }

        osc.sendMsg(API_OFFSET + "pending-alerts", [
            json.dumps(message),
        ],
                    port=ACTIVITY_PORT)
Esempio n. 8
0
 def stop_service(self):
     if self.service:
         if _platform == 'android':
             self.service.stop()
         self.service = None
     else:
         osc.sendMsg('/kill',[], port=SERVICE_PORT)
Esempio n. 9
0
 def on_touch_move(self, touch):
     if self.collide_point(*touch.pos):
         print(touch.pos)
         rel_pos = self.to_widget(*touch.pos, relative=True)
         x_scaled, y_scaled = rel_pos[0]/self.width , rel_pos[1] / self.height
         osc.sendMsg(self.x_msg, [x_scaled, ], ipAddr=oscIpAddress, port=oscPort)
         osc.sendMsg(self.y_msg, [y_scaled, ], ipAddr=oscIpAddress, port=oscPort)
    def _test_2_test_service_control(self):
        # Run main
        _proc = subprocess.Popen(args = ["python", os.path.normpath(Test_Script_Dir + "/../main.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)


        # Connect to it and sent message

        osc.init()
        self.oscid = osc.listen(ipAddr='0.0.0.0', port=3002)
        osc.bind(self.oscid, self._status_result, '/status')

        self.test_2_result = None
        sleep(1)
        osc.sendMsg(oscAddress ='/status', ipAddr="0.0.0.0", dataArray=[""], port=3000)

        while self.test_2_result is None:
            osc.readQueue(self.oscid)
            sleep(.1)
        if self.test_2_result is True:
            self.assertTrue(True)
        else:
            self.assertTrue(False, "Test failed, service returned:" + str(self.test_2_result))

        osc.sendMsg(oscAddress ='/stop', ipAddr="0.0.0.0", dataArray=[], port=3000)
        osc.dontListen(self.oscid)
Esempio n. 11
0
 def send_ping_result(self, _id):
     L.debug("Send ping result %d" % _id)
     pickle_msg = pickle.dumps({
         'response': 'ping',
         'id': _id,
         'config': self.config})
     osc.sendMsg('/android_park', [pickle_msg, ], port=3334)
Esempio n. 12
0
 def on_slid(self):
     self.device_value = str(self.ids.curtain_slider.value)
     print self.ids.curtain_slider.value
     final_msg = str(self.device_location + '_' + self.device_type + '_' +
                     self.device_name + '_' + self.device_value + '_' +
                     self.device_ttime)
     print final_msg
     osc.sendMsg('/command', [final_msg], port=3000)
Esempio n. 13
0
    def send_modify(self, modify):
        pickle_msg = pickle.dumps(
            {'request': 'modify',
             'id': self.save_id(modify),
             'config': self.get_config(),
             'operations': modify.operations})

        osc.sendMsg('/android_park', [pickle_msg, ], port=3333)
Esempio n. 14
0
 def rm(self, root, tag):
     self.listapedidos.remove(tag.id)
     osc.sendMsg('/servidor_men', ['pedido_servido', tag.id],
                 port=serviceport)
     tag.delete()
     tag.servido = True
     if tag.id in self.listapedidos:
         self.listapedidos.remove(tag.id)
     self.view.remove_widget(root)
Esempio n. 15
0
 def on_stop(self):
     # The Kivy event loop is about to stop, set a stop signal;
     # otherwise the app window will close, but the Python process will
     # keep running until all secondary threads exit.
     if platform == 'android':
         self.p.service.stop()
     osc.sendMsg('/servidor_men', [
         'finalizar',
     ], port=serviceport)
Esempio n. 16
0
 def servido(self, root):
     tag = root.tag
     s = tag.servido
     s = False if s == True else True
     tag.servido = s
     tag.save()
     osc.sendMsg('/servidor_men', ['linea_servida', tag.id, tag.servido],
                 port=serviceport)
     root.color = '#beec90' if s == True else '#b9b9b9'
Esempio n. 17
0
 def send_query_result(self, _id, result, pending, status=None):
     L.debug("Send query result %d" % _id)
     pickle_msg = pickle.dumps({
         'response': 'query',
         'id': _id,
         'result': result,
         'pending': pending,
         'status': status})
     osc.sendMsg('/android_park', [pickle_msg, ], port=3334)
Esempio n. 18
0
 def osc_send(self, *largs):
     if len(largs) == 2:
         msg_type = largs[1]
         msg = largs[0]
     else:  # Sending default OSC
         msg_type = self.sequences.current_osc_message[1]
         msg = [self.sequences.current_osc_message[0]]
     Logger.debug("main.BaseApp.osc_send: sending message'[{}]{}' on port {}".format(msg_type, msg, service_port))
     osc.sendMsg(msg_type, msg, port=service_port)
Esempio n. 19
0
 def send_msg_to_service(self, instance):
     '''
     Send message to the service
     '''
     osc.sendMsg('/message', [
         'Activity: Hey there',
     ],
                 port=service_port,
                 typehint=None)
Esempio n. 20
0
 def osc_send(self, osc_addr, data={}, raw=False):
     if not raw:
         data['host'] = self.net.client_host
         data = json.dumps(data)
     osc.sendMsg(osc_addr, [data],
                 ipAddr=self.net.server_host,
                 port=self.net.server_port)
     if DEBUG_OSC and osc_addr != '/ping':
         Logger.info('sendind: {}'.format([osc_addr, data]))
Esempio n. 21
0
def sync_pedidos():
    sound = SoundLoader.load('a1.wav')
    if sound:
        print("Sound found at %s" % sound.source)
        print("Sound is %.3f seconds" % sound.length)
        sound.play()
    osc.sendMsg('/sync_pedidos', [
        'sync',
    ], port=activityport)
Esempio n. 22
0
 def stop_simulation(self, *args):
     print("ABORT THE SIMULATION!")
     self.root.ids.label.text += 'Simulation STOP\n'
     osc.sendMsg('/start', [False, ], port=3000)
     self.start_simu = True
     self.cycle = 0
     crossing_obj = App.get_running_app().root.ids.gridy.children
     for child in crossing_obj:
         child.spot = [0, 0, 0, 0, 0]
Esempio n. 23
0
def check_state(message, *args):
    if mPlayer.isPlaying():
        osc.sendMsg('/is_playing', [
            'is playing',
        ], port=activityport)
    elif not mPlayer.isPlaying():
        osc.sendMsg('/is_stopped', [
            'is stopped',
        ], port=activityport)
Esempio n. 24
0
 def save(self):
     global client_id
     global server_ip
     client_id = str(self.ids.client_id_text.text)
     server_ip = str(self.ids.server_ip_text.text)
     print server_ip
     print client_id
     osc.sendMsg('/clientID', [client_id], port=3000)
     osc.sendMsg('/serverIP', [server_ip], port=3000)
Esempio n. 25
0
def first_auth():
    global authorized
    authorized = False

    osc.sendMsg('/first auth', [], port=3002)

    while not authorized:
        time.sleep(0.5)
        osc.readQueue(oscid)
Esempio n. 26
0
def send_gpx_rec_status():
    """Sends the service status is_recording. That way, even if KivyTrek is stopped, upon
    restart of the application we are aware that the service is recording the gps position.
    Then, KivyTrek's interface can display that information accordingly.
    """
    if gpx_record is not None:
        rec_status = gpx_record.is_recording()
    else:
        rec_status = False
    osc.sendMsg('/gpx_status', dataArray=[rec_status], port=kivytrek_port)
Esempio n. 27
0
 def close_connection(self, name):
     osc.sendMsg('/api/main', ['disconnect', name], port=serviceport)
     if name not in self.running:
         return
     Animation(background_color=(1, 1, 1,
                                 1)).start(self.boxes[name].ids.servername)
     self.root.transition.direction = 'right'
     self.root.current = 'ScreenMain'
     self.root.remove_widget(self.running[name])
     del self.running[name]
Esempio n. 28
0
    def pressed(self):

        if self.status == 'ON':
            self.device_value = 'OFF'
        else:
            self.device_value = 'ON'
        final_msg = str(self.device_location + '_' + self.device_type + '_' +
                        self.device_name + '_' + self.device_value)
        print final_msg
        osc.sendMsg('/command', [final_msg], port=3000)
Esempio n. 29
0
File: main.py Progetto: javto/AT3
    def status(self, setup=False, stop=False):
        """
        Runs status updates from the anontunnels
        """
        if setup:
            self.running_updates = True
            self.download_benchmark = []
            self.download_first_byte = None
            self.printed_results = False
        if stop:
            self.running_updates = False
            if self.timer is not None:
                self.timer.stop()
        if self.running_updates:
            self.timer = Timer(1, self.status).start()
            status = self.anon_tunnel.status()
            cpu = ', '.join([str(abs(core)) for core in self.cpu_usage])
            print 'REALTIME {"cpu": %f, "speed": %f, "progress": %f, "circuits": %d}' % (sum(self.cpu_usage), status['download_speed'], status['download_progress'], status['circuits'])
            array_status = [status['circuits'],
                            status['relays'],
                            status['enter'],
                            status['relay'],
                            status['exit'],
                            status['download_speed'],
                            status['download_progress'],
                            cpu]
            self.download_benchmark.append((clock(), status['download_speed']))
            if status['download_speed'] > 0.0 and self.download_first_byte is None:
                self.download_first_byte = clock()
            if status['download_progress'] >= 100.0 and not self.printed_results:
                self.printed_results = True
                self.download_end = clock()
                self.output = {'timings':
                                  {'tribler_start': self.tribler_start,
                                   'tribler_end': self.tribler_end,
                                   'download_start': self.download_start,
                                   'download_first_byte': self.download_first_byte,
                                   'download_end': self.download_end},
                               'cpu': self.cpu_benchmark,
                               'speed': self.download_benchmark}
                results_file = open('/sdcard/experiments/%d_hops_%d_circuits.pickle' % (self.NRHOPS, self.NRCIRCUITS), 'w')
                results_file.write(base64.urlsafe_b64encode(pickle.dumps(self.output)))
                results_file.close()

                print '--- IMPORTANT TIMESTAMPS ---'
                print 'Start Tribler/Dispersy startup at    %.2f' % self.tribler_start
                print 'Finished Tribler/Dispersy startup at %.2f' % self.tribler_end
                print 'Start download                       %.2f' % self.download_start
                print 'First byte downloaded                %.2f' % self.download_first_byte
                print 'Finished download                    %.2f' % self.download_end
                print '--- CPU ---'
                print self.cpu_benchmark
                print '--- KB/S ---'
                print self.download_benchmark
            osc.sendMsg('/status', array_status, ipAddr='127.0.0.1', port=9000)
Esempio n. 30
0
def twofactor_handler():
    global twofactor_code
    twofactor_code = None
    osc.sendMsg('/auth twofactor needed', [], port=3002)

    while not twofactor_code:
        time.sleep(0.5)
        osc.readQueue(oscid)

    send_log_line(u'Повторяю запрос с кодом', 0)
    return twofactor_code, True
Esempio n. 31
0
    def kivy_server(message, *args):
        """
        Handle SoundLoader messages. Message is a list of:
            [<api_name>, ',s')] + [<function>, <args>, <kwargs>]

        Note: args and kwargs are string literals, but this is not yet
        implemented.
        """
        print("kivy_server : got a message {0}".format(message))
        osc.sendMsg('kivy_client', ['p1', 'p2', 'p3'],
                    port=OSCServer.client_port)
Esempio n. 32
0
    def kivy_server(message, *args):
        """
        Handle SoundLoader messages. Message is a list of:
            [<api_name>, ',s')] + [<function>, <args>, <kwargs>]

        Note: args and kwargs are string literals, but this is not yet
        implemented.
        """
        print("kivy_server : got a message {0}".format(message))
        osc.sendMsg('kivy_client', ['p1', 'p2', 'p3'],
                    port=OSCServer.client_port)
Esempio n. 33
0
    def do_notify(self, mode='normal'):
        """ collect text edit text and send to the background service """

        title = self.ids.notification_title.text
        message = self.ids.notification_text.text

        if PY2:
            title = title.decode('utf8')
            message = message.decode('utf8')

        osc.sendMsg('/update', dataArray=(title,message,), port=serviceport)
Esempio n. 34
0
 def osc_send(self, osc_addr, data, host=None, raw=False):
     if not raw:
         data = json.dumps(data)
     if host is not None:
         if DEBUG_OSC and not osc_addr in ['/pong', '/draw']:
             Logger.info('sendind: {}'.format([osc_addr, data, host]))
         if self.net.valid_host(host):
             osc.sendMsg(osc_addr, [ data ], ipAddr=host, port=self.net.client_port)
     else:  # Broadcast
         for host in self.clients.keys():
             self.osc_send(osc_addr, data, host, raw=True)
Esempio n. 35
0
def captcha_handler(captcha):
    global captcha_code
    captcha_code = None
    osc.sendMsg('/auth captcha needed', [captcha.get_url(), ], port=3002)

    while not captcha_code:
        time.sleep(0.5)
        osc.readQueue(oscid)

    send_log_line(u'Повторяю запрос с капчей', 0)
    captcha.try_again(captcha_code)
 def pause(self):
     try:
         osc.sendMsg('/some_api', ['Pause'], port=3002)
         if self.sound == None:
             pass
         else:
             self.pauseTime = self.sound.get_pos()
             self.sound.stop()
         self.state = 'pause'
         self.nBuilder.set_title('Pause')
         self.nBuilder.build()
     except Exception as e: osc.sendMsg('/some_api', [str(e)], port=3002)
Esempio n. 37
0
def on_location(**kwargs):
    lat = kwargs.get('lat')
    lon = kwargs.get('lon')
    alt = kwargs.get('altitude')
    speed = kwargs.get('speed')
    bearing = kwargs.get('bearing')

    osc.sendMsg('/gps_pos', [lat, lon, alt, speed, bearing],
                port=kivytrek_port)

    if gpx_record is not None:
        gpx_record.add_point(lat, lon, alt)
Esempio n. 38
0
 def start_simulation(self, *args):
     if self.start_simu == True:
         print("PERMISSION GRANTED: Simulation start!")
         self.root.ids.label.text += 'Simulation START\n'
         osc.sendMsg('/start', [True, int(self.max_cycle), int(self.agents_num),
                                int(self.grid[0]), int(self.grid[1])], port=3000)
         self.start_simu = False
     else:
         print("Simulation is on holiday")
         self.root.ids.label.text += 'Simulation PAUSE\n'
         osc.sendMsg('/start', ['pause', ], port=3000)
         self.start_simu = True
Esempio n. 39
0
    def stopService(self):
        if self.isRunning:
            if self.service:
                osc.sendMsg('/stop', [''], port=IPCServicePort)
                try:
                    self.service.stop()
                    self.currentstatus = "GPS stopped"
                except Exception as e:
                    logging.exception('failed to stop service')
                    self.currentstatus = "failed to stop service: " + e.message

        self.isRunning = False
Esempio n. 40
0
def _main():
    osc.init()
    start_time = int(time.time())
    oscid = osc.listen(ipAddr='0.0.0.0', port=MAIN_PROG_RCV)
    osc.bind(oscid, play, '/play')
    osc.bind(oscid, pause, '/pause')
    osc.bind(oscid, stop, '/stop')
    osc.bind(oscid, volume, '/volume')
    osc.bind(oscid, kill, '/kill')
    while True:
        osc.readQueue(oscid)
        osc.sendMsg('/ping', [start_time], port=MAIN_PROG_PORT)
        sleep(.1)
Esempio n. 41
0
def gen_sentence_from_markov(graph):
	try:
		for i in range(10): # try 10 times (REALLY BAD WAY TO STOP UNICODEENCODEERROR)
			try:
				sentence_bits = bml.genSentence(graph)
				sentence = str(bml.processSentence(sentence_bits))
				return sentence
			except UnicodeEncodeError:
				pass
	except AttributeError:
		osc.sendMsg('/some_api',['GENERATE','fail','you can\'t generate one until you UPDATE_DB','FAILURE'],port=activityport)
		return None
	osc.sendMsg('/some_api',['GENERATE','fail','stuck escaping unicode (python2.7 sucks at unicode)','FAILURE'],port=activityport)
	return None
Esempio n. 42
0
    def stop_service(self):
        """Stop the service"""
        print("Asking service to stop.")
        self.service_running = False

        osc.sendMsg("/status", [], port=3000)
        sleep(0.2)
        osc.readQueue(self.oscid)

        osc.sendMsg("/stop", [], port=3000)
        sleep(0.2)
        osc.readQueue(self.oscid)
        if self.service is not None and platform == "android":
            self.service.stop()
            self.service = None
Esempio n. 43
0
 def start_requesting_answers_count(self):
     if not self.answers_request_event:
         self.answers_request_event = Clock.schedule_interval(
             lambda *x:
                 osc.sendMsg('/request answers count', [], port=3000),
             5
         )
    def _test_3_test_service_job(self):
        # Run main
        _proc = subprocess.Popen(args = ["python", os.path.normpath(Test_Script_Dir + "/../main.py")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        # Connect to it and sent message

        osc.init()
        self.oscid = osc.listen(ipAddr='0.0.0.0', port=3002)
        osc.bind(self.oscid, self._status_result, "/status")

        sleep(1)

        osc.sendMsg(oscAddress ='/run_job', ipAddr="0.0.0.0", dataArray=["Default", ], port=3000)

        sleep(10)

        osc.sendMsg(oscAddress ='/stop', ipAddr="0.0.0.0", dataArray=[], port=3000)
Esempio n. 45
0
def main_api_callback(message, *args):
    #    print message[2:]
    if len(message) > 3:
        name = message[3]
        if message[2] == "connect":
            init_server(name, *message[4:])
        elif message[2] == "disconnect":
            disconnect_server(name)
        elif message[2] == "unread":
            unread = unread_server(name)
            osc.sendMsg("/api/main", ["unread", name, unread],
                        port=activityport)
            opened[name] = True
        elif message[2] == "send":
            send_server(name, message[4])
        elif message[2] == "channel":
            channel_server(name, message[4])
Esempio n. 46
0
def bt_rx_thread():
    Logger.info('RC_SVC: ############################## bt_rx_thread started ##############################')
    while service_should_run.is_set():
        try:
            msg = bt_connection.read_line()
            if msg:
                osc.sendMsg(RX_API, [msg, ], port=CLIENT_API_PORT)
        except PortNotOpenException:
            sleep(1.0)
            pass                
        except Exception as e:
            Logger.info('RC_SVC: Exception in rx_message_thread')
            traceback.print_exc()
            osc.sendMsg(CMD_API, ["ERROR", ], port=CLIENT_API_PORT)
            sleep(1.0)
    jnius.detach() #detach the current thread from pyjnius, else hard crash occurs 
    Logger.info('RC_SVC: ############################## bt_rx_thread exited ##############################')
    def __init__(self):
        sleep(1)
        osc.init()
        oscid = osc.listen(ipAddr='127.0.0.1', port=3001)
        try:
            osc.sendMsg('/some_api', ['Init'], port=3002)
            self.mplayer = M_Player(self)
            osc.bind(oscid, self.mplayer.osc_callback, '/some_api')
            self.queue = ''

            while True:
                osc.readQueue(oscid)
                if self.queue != '':
                    self.mplayer.osc_callback(['','',self.queue])
                    self.queue = ''
                    sleep(.3)
        except Exception as e:
            osc.sendMsg('/some_api', ['Service crash '+str(e)], port=3002)
 def play(self):
     osc.sendMsg('/some_api', ['Play'], port=3002)
     try:
         if self.sound == None:
             if self.pauseTime == None:
                 self.sound = SoundLoader.load(self.path)
                 if self.sound:
                     self.sound.play()
         else:
             self.sound.play()
             if self.state == 'pause':
                 sleep(0.2)
                 self.sound.seek(int(self.pauseTime))
         self.state = 'play'
         self.nBuilder.set_title('Play')
         self.nBuilder.build()
     except Exception as e:
         osc.sendMsg('/some_api', [str(e)], port=3002)
Esempio n. 49
0
def process_result(result):
	osc.sendMsg('/some_api', ['UPDATE_DB','progress','downloaded data...', ], port=activityport)
	titledata, descdata = processUrlData(result)
	descdataset = bml.genSetOfWords(descdata)
	titledataset = bml.genSetOfWords(titledata)
	osc.sendMsg('/some_api', ['UPDATE_DB','progress','created datasets...', ], port=activityport)
	markov_graph = bml.genMarkov(descdata,descdataset)
	osc.sendMsg('/some_api', ['UPDATE_DB','progress','created description set...', ], port=activityport)
	markov_title = bml.genMarkov(titledata,titledataset)
	osc.sendMsg('/some_api', ['UPDATE_DB','progress','created headline set...', ], port=activityport)
	#self.ids.random_number.text = str(result[500:800])
	return markov_title, markov_graph
Esempio n. 50
0
 def main_api_callback(self, message, *args):
     #        print message[2:]
     if len(message) > 3:
         name = message[3]
         if name not in self.running:
             return
         if message[2] == 'nick':
             nick = message[4]
             self.running[name].ids.nick.text = nick
         elif message[2] == 'channel':
             channel, channels = message[4], message[5:]
             self.running[name].ids.channel.text = channel or 'No channel'
             self.running[name].ids.channel.values = [
                 x or 'No channel' for x in channels
             ]
         elif message[2] == 'check':
             osc.sendMsg('/api/main', ['unread', name], port=serviceport)
         elif message[2] == 'unread':
             self.log_msg(name, message[4])
Esempio n. 51
0
    def init(self, _cfg_file=None):
        self.ids.destination_host.ids.input_selection.bind(text=self._update_host)
        self.ids.destination_path.on_status = self.do_on_smbselector_status
        self.load_settings(_cfg_file)
        self.service = None
        osc.init()
        self.oscid = osc.listen(port=3002)
        osc.bind(self.oscid, self.progress_callback, "/progress_callback")
        osc.bind(self.oscid, self.status_callback, "/status_callback")

        # Check if service is running
        self.service_running = False
        osc.sendMsg("/status", [], port=3000)
        osc.sendMsg("/progress", [], port=3000)
        sleep(0.3)
        osc.readQueue(self.oscid)


        Clock.schedule_interval(self.process_messages, 1)
Esempio n. 52
0
def on_auth_request(message, *args):
    global authorized
    login, password = literal_eval(message[2])
    send_log_line(u'Логин и пароль доставлены', 0)

    authorized, error = bot.authorization(
        login=login, password=password,
        twofactor_handler=twofactor_handler, captcha_handler=captcha_handler
    )
    if error:
        osc.sendMsg('/auth failed', [], port=3002)
        if error == 'bad password':
            send_log_line(u'[b]Неправильный логин или пароль[/b]', 2)
        else:
            send_error(error)

        exit()

    osc.sendMsg('/auth successful', [], port=3002)
    def __init__(self,parent):
        try:
            self.nBuilder = Notification_Builder()
            self.nBuilder.set_title('Stop')
            self.nBuilder.set_message('msg')
            self.nBuilder.set_ticker('Button example')
            ## 0. Displayed button name
            ## 1. icon integer available at https://developer.android.com/reference/android/R.drawable.html
            ## 2. callback
            ## action= android PendingIntent action, button name will be used if not provided
            self.nBuilder.Button('Play', 17301540 , self.intent_callback, action='Play')
            self.nBuilder.Button('Pause', 17301539 , self.intent_callback, action='Pause')
            self.nBuilder.build()

            self.parent = parent
            self.sound = None
            self.pauseTime = None
            self.state = 'stop'
            self.path = '/data/data/org.test.npexample/files/rain.ogg'
        except Exception as e: osc.sendMsg('/some_api', ['Mplayer exception '+str(e)], port=3002)
Esempio n. 54
0
 def selectDevice(self, dropdown, deviceId, title):
     if dropdown:
         dropdown.dismiss()
     self.selectedDeviceName = title
     self.device = deviceId
     if self.asset:
         IOT.unsubscribe(self.asset)
     self.asset = None
     if self.device:
         assets = IOT.getAssets(self.device)
         locationAsset = [
             asset for asset in assets
             if str(asset['name']).startswith('prediction_distance_json')
         ]
         if locationAsset and len(locationAsset) > 0:
             self.asset = str(locationAsset[0]['id'])
             IOT.subscribe(self.asset, self.destinationChanged)
     if self.isRunning and platform == 'android':
         osc.sendMsg('/device', [str(self.device)], port=IPCServicePort)
     self.saveConfig()
Esempio n. 55
0
 def init_connection(self, name):
     if name not in self.servers:
         return
     if name not in self.running:
         Animation(background_color=(0.1, 1, 0.1, 1)).start(
             self.boxes[name].ids.servername)
         screen = ScreenConversation(name=name)
         data = self.servers.get(name)
         self.running[name] = screen
         self.root.add_widget(screen)
         screen.ids.nick.text = data['nick']
         osc.sendMsg(
             '/api/main',
             [
                 'connect', name, data['host'], data['port'], data['nick'],
                 data['password'], data['auth_nickserv'], data['scripts']
             ] + data['autojoin'],
             port=serviceport)
     self.root.transition.direction = 'left'
     self.root.current = name
Esempio n. 56
0
def cmd_api_callback(message, *args):
    message = message[2]
    if message == 'EXIT':
        Logger.info('RC_SVC: ############################## GOT EXIT CMD #####################################')
        service_should_run.clear()
    elif message == 'OPEN':
        try:
            Logger.info('RC_SVC: ############################## GOT OPEN CMD #####################################')
            bt_connection.open('RaceCapturePro')
        except Exception as e:
            Logger.info("RC_SVC:Failed to open Bluetooth connection: " + str(e))
    elif message == 'CLOSE':
        Logger.info('RC_SVC: ############################## GOT CLOSE CMD #####################################')
        bt_connection.close()
    elif message == 'GET_PORTS':
        Logger.info('RC_SVC: ############################## GOT GET_PORTS CMD #####################################')
        ports = bt_connection.get_available_ports()
        osc.sendMsg(CMD_API, [ports ,], port=CLIENT_API_PORT)
    elif message == 'PING':
        global last_keep_alive_time
        last_keep_alive_time = time();
Esempio n. 57
0
File: main.py Progetto: synctext/AT3
 def status(self, setup=False, stop=False):
     """
     Runs status updates from the anontunnels
     """
     if setup:
         self.running_updates = True
     if stop:
         self.running_updates = False
     if self.running_updates:
         self.timer = Timer(1, self.status).start()
         status = self.anon_tunnel.status()
         cpu = ', '.join([str(abs(core)) for core in psutil.cpu_percent(percpu=True)])
         array_status = [status['circuits'],
                         status['relays'],
                         status['enter'],
                         status['relay'],
                         status['exit'],
                         status['download_speed'],
                         status['download_progress'],
                         cpu]
         osc.sendMsg('/status', array_status, ipAddr='127.0.0.1', port=9000)
Esempio n. 58
0
    def send_message(self, message, *args):
        # print(
        #     ('app' if not service else 'service')+
        #    ' sending message: {}'.format(message))
        #  print " "
        # print " "
        #  print message

        # if 'message_type' in message:
        #     # print " "
        #     # print "DATA CHECKS OUT"
        #     # print " "
        #     app = App.get_running_app()
        #     millis = int(round(time.time() * 1000))
        #     print "1. send data", millis
        #     app.appix_base.run_bluetooth_commands(ast.literal_eval(message))
        #     millis = int(round(time.time() * 1000))
        #     print "2. done data", millis
        # millis = int(round(time.time() * 1000))
        # print "1. send message", millis
        osc.sendMsg('/AppixCom', message, port=self.send_port)
Esempio n. 59
0
def currency():
    url = "http://www.doviz.com/api/v1/currencies/all/latest"
    req = request(url=url, method="GET")
    update = "noupdate"
    if req.status_code == 200:
        js = json.loads(req.text)
        for x in js:
            if abs(x["change_rate"]) > 0.02 and (
                x["name"] == "amerikan-dolari" or x["name"] == "euro" or x["name"] == "sterlin"
            ):
                update = "update"
                try:
                    from utils2 import AndroidNotification

                    title = "Doviz App"
                    message = "{} {} yukseldi".format(x["name"], x["change_rate"])
                    notify = AndroidNotification()
                    notify._notify(title=title, message=message, ticker="Doviz App Yeni")
                except:
                    update = "error"
                break
    port = 3005
    js = [str(update)]
    osc.sendMsg("/currency", js, port=port)
Esempio n. 60
0
    def build(self):
        self.title = "Traffic simulator"

        # Android
        self.service = None
        self.start_service()

        # osc messages init
        osc.init()
        oscid = osc.listen(port=3002)
        # Send start/stop simulation
        osc.bind(oscid, self.start_simulation, '/send_start')
        # Receive hello world
        osc.bind(oscid, self.output_hello, '/receive_hello')
        # Retrieve simulation status
        osc.bind(oscid, self.simulation_status_receive, '/simu-status')
        # Retrieve server stopped
        osc.bind(oscid, self.server_stopped, '/server-stop')
        # Read received messages
        Clock.schedule_interval(lambda *x: osc.readQueue(oscid), 0)
        # Receive grid status
        osc.bind(oscid, self.grid_update, '/states')

        # Send message asking for simulation status
        osc.sendMsg('/simu-status_ask', [], port=3000)

        # Grid changes
        # self._size_handler_trigger = Clock.schedule_once(self._size_handler)  # Clock.create_trigger
        # self.bind(grid=self._size_handler_trigger)

        # normal variables
        self.grid_spots = []

        if not self.server_running:
            print("Simulation server not running")
            self.root.ids.label.text = "Simulation server not running :(\n"