Esempio n. 1
0
 def main(self):
     # default value
     self.brute = False
     self.user = "******"
     self.wordlist = "db/wordlist.txt"
     self.url = None
     self.user = None
     self.scan = None
     #
     if len(sys.argv) < 2:
         usage(True)
     try:
         opts, args = getopt.getopt(
             sys.argv[1:], 'u:U:s:p:c:a:t:w:Rrhvb:', [
                 'url=', 'brute', 'user='******'scan=', 'proxy=', 'cookie=',
                 'agent=', 'wordlist=', 'timeout=', 'redirect', 'ragent',
                 'help', 'verbose'
             ])
     except getopt.GetoptError as e:
         usage(True)
     for opt, arg in opts:
         if opt in ('-u', '--url'): self.url = urlCheck(arg)
         if opt in ('-b', '--brute'): self.brute = True
         if opt in ('-U', '--user'): self.user = arg
         if opt in ('-s', '--scan'): self.scan = arg
         if opt in ('-p', '--proxy'): self.kwargs['proxy'] = arg
         if opt in ('-c', '--cookie'): self.kwargs['cookie'] = arg
         if opt in ('-a', '--agent'): self.kwargs['agent'] = arg
         if opt in ('-t', '--timeout'): self.kwargs['timeout'] = arg
         if opt in ('-R', '--redirect'): self.kwargs['redirect'] = True
         if opt in ('-r', '--ragent'): self.kwargs['ragent'] = True
         if opt in ('-v', '--verbose'): self.kwargs['verbose'] = True
         if opt in ('-h', '--help'): usage(True)
     # start
     try:
         if self.scan != None:
             banner()
             Scan().run(self.scan)
         elif self.brute is True:
             ptime(self.url)
             XMLRPCBrute(self.url, None, self.user, self.wordlist,
                         self.kwargs).run()
         elif self.url:
             ptime(self.url)
             fingerprint(self.url, None, self.kwargs).run()
             generic(self.url, None, self.kwargs)
             wpthemes(self.url, None, self.kwargs).run()
             wpplugins(self.url, None, self.kwargs).run()
             wpusers(self.url, None, self.kwargs).run()
     except UnboundLocalError as e:
         pass
Esempio n. 2
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '',
                                           ['help', 'log-path=', 'room='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--log-path'):
            s.log_path = arg
        elif opt in ('--room'):
            if arg not in [
                    'RRF', 'RRF_V1', 'TECHNIQUE', 'INTERNATIONAL', 'BAVARDAGE',
                    'LOCAL', 'EXPERIMENTAL', 'FON'
            ]:
                print(
                    'Unknown room name (choose between \'RRF\', \'TECHNIQUE\', \'INTERNATIONAL\', \'BAVARDAGE\', \'LOCAL\', \'EXPERIMENTAL\' and \'FON\')'
                )
                sys.exit()
            s.room = arg

    # Create directory and copy asset if necessary
    if not os.path.exists(s.log_path):
        os.makedirs(s.log_path)
    if not os.path.exists(s.log_path + '/' + 'assets'):
        os.popen('cp -a ../front/assets ' + s.log_path)

    tmp = datetime.datetime.now()
    s.day = tmp.strftime('%Y-%m-%d')

    s.log_path_day = s.log_path + '/' + s.room + '-' + s.day

    if not os.path.exists(s.log_path_day):
        os.makedirs(s.log_path_day)
        os.popen('cp /opt/RRFTracker/front/index.html ' + s.log_path_day +
                 '/index.html')
        os.popen('ln -sfn ' + s.log_path_day + ' ' + s.log_path + '/' +
                 s.room + '-today')

    # Startup
    filename = s.log_path + '/' + s.room + '-today/rrf.json'  # If restart on day...
    if os.path.isfile(filename):
        l.restart()

    l.log_user()  # Get user online
    l.whereis_load()  # Load whereis dict
    l.whois_load()  # Load whois dict

    # Urllib3 settings
    http = urllib3.PoolManager(timeout=1.0)
    http = urllib3.PoolManager(timeout=urllib3.Timeout(connect=.5, read=.5))

    # Main loop
    while (True):
        chrono_start = time.time()

        # If midnight...
        tmp = datetime.datetime.now()
        s.day = tmp.strftime('%Y-%m-%d')
        s.now = tmp.strftime('%H:%M:%S')
        s.hour = int(tmp.strftime('%H'))
        s.minute = int(s.now[3:-3])
        s.seconde = int(s.now[-2:])

        if (s.minute % 5 == 0 and s.seconde == 0):
            l.log_user()
            l.whereis_load()

        if (s.now[:5] == '00:00'):
            l.whois_load()

            s.log_path_day = s.log_path + '/' + s.room + '-' + s.day

            if not os.path.exists(s.log_path_day):
                os.makedirs(s.log_path_day)
                os.popen('cp /opt/RRFTracker/front/index.html ' +
                         s.log_path_day + '/index.html')
                os.popen('ln -sfn ' + s.log_path_day + ' ' + s.log_path + '/' +
                         s.room + '-today')

            s.qso = 0
            s.day_duration = 0
            for q in range(0, 24):  # Clear histogram
                s.qso_hour[q] = 0
            s.all.clear()  # Clear all history
            s.porteuse.clear()  # Clear porteuse history
            s.tot.clear()  # Clear tot history
            s.init = True  # Reset init

        # Request HTTP data
        try:
            r = http.request('GET',
                             s.room_list[s.room]['url'],
                             timeout=.5,
                             retries=10)
            data = json.loads(r.data.decode('utf-8'))
            transmitter = data['transmitter']
        except:
            data = ''
            if s.now < '03:00:00' or s.now > '03:05:00':
                print('Failed', s.day, s.now)

        # If valid json data
        if data != '':

            # If transmitter...
            if transmitter != '':

                if s.transmit is False:
                    s.transmit = True

                s.call_current = l.sanitize_call(transmitter)

                if (s.call_previous != s.call_current):
                    s.tot_start = time.time()
                    s.tot_current = s.tot_start
                    s.call_previous = s.call_current

                    if s.call_date[0] == '' or s.call_date[0] > s.now:
                        blanc = 0
                    else:
                        blanc = l.convert_time_to_second(
                            s.now) - l.convert_time_to_second(s.call_date[0])

                    for i in range(9, 0, -1):
                        s.call[i] = s.call[i - 1]
                        s.call_date[i] = s.call_date[i - 1]
                        s.call_blanc[i] = s.call_blanc[i - 1]
                        s.call_time[i] = s.call_time[i - 1]

                    s.call[0] = s.call_current
                    s.call_blanc[0] = l.convert_second_to_time(blanc)

                else:
                    if s.tot_start == '':
                        s.tot_start = time.time()
                        s.tot_current = s.tot_start

                        if s.call_date[0] == '' or s.call_date[0] > s.now:
                            blanc = 0
                        else:
                            blanc = l.convert_time_to_second(
                                s.now) - l.convert_time_to_second(
                                    s.call_date[0])

                        for i in range(9, 0, -1):
                            s.call[i] = s.call[i - 1]
                            s.call_date[i] = s.call_date[i - 1]
                            s.call_blanc[i] = s.call_blanc[i - 1]
                            s.call_time[i] = s.call_time[i - 1]

                        s.call[0] = s.call_current
                        s.call_blanc[0] = l.convert_second_to_time(blanc)

                    else:
                        s.tot_current = time.time()

                s.duration = int(s.tot_current) - int(s.tot_start)

                # Save stat only if real transmit
                if (s.stat_save is False and s.duration > s.intempestif):
                    #s.node = l.save_stat_node(s.node, s.call[0], 0)
                    s.qso += 1
                    tmp = datetime.datetime.now() - datetime.timedelta(
                        seconds=3)
                    s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])
                    s.all = l.save_stat_all(
                        s.all, s.call[0], tmp.strftime('%H:%M:%S'),
                        l.convert_second_to_time(s.duration), True)

                    s.stat_save = True

                # Format call time
                tmp = datetime.datetime.now()
                s.now = tmp.strftime('%H:%M:%S')
                s.hour = int(tmp.strftime('%H'))

                s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])

                s.call_date[0] = s.now
                s.call_time[0] = s.duration

                if s.duration > s.intempestif:
                    s.all = l.save_stat_all(
                        s.all, s.call[0], tmp.strftime('%H:%M:%S'),
                        l.convert_second_to_time(s.duration), False)

            # If no Transmitter...
            else:
                if s.transmit is True:
                    tmp = datetime.datetime.now()
                    if s.room == 'RRF':
                        if l.convert_second_to_time(s.duration) > s.tot_limit:
                            s.tot = l.save_stat_tot(s.tot, s.call[0],
                                                    tmp.strftime('%H:%M:%S'))

                    if s.stat_save is True:
                        if s.duration > 600:  # I need to fix this bug...
                            s.duration = 0
                        s.day_duration += s.duration
                    if s.stat_save is False:
                        s.porteuse = l.save_stat_porteuse(
                            s.porteuse, s.call[0], tmp.strftime('%H:%M:%S'))

                    s.transmit = False
                    s.stat_save = False
                    s.tot_current = ''
                    s.tot_start = ''

            # Node analyze
            s.node_list = []
            for d in data['nodes']:
                if d not in [
                        'RRF', 'RRF2', 'RRF3', 'TECHNIQUE', 'BAVARDAGE',
                        'INTERNATIONAL', 'LOCAL', 'EXPERIMENTAL'
                ]:
                    s.node_list.append(l.sanitize_call(d))

            if s.node_list_old == []:
                s.node_list_old = s.node_list
            else:
                if s.node_list_old != s.node_list:
                    if (list(set(s.node_list_old) - set(s.node_list))):
                        s.node_list_out = list(
                            set(s.node_list_old) - set(s.node_list))
                        for n in s.node_list_out:
                            if n in s.node_list_in:
                                s.node_list_in.remove(n)
                        s.node_list_out = sorted(s.node_list_out)

                    if (list(set(s.node_list) - set(s.node_list_old))):
                        s.node_list_in = list(
                            set(s.node_list) - set(s.node_list_old))
                        for n in s.node_list_in:
                            if n in s.node_list_out:
                                s.node_list_out.remove(n)
                        s.node_list_in = sorted(s.node_list_in)

                    s.node_list_old = s.node_list

            s.node_count = len(s.node_list)

            if s.node_count > s.node_count_max:
                s.node_count_max = s.node_count

            if s.node_count < s.node_count_min:
                s.node_count_min = s.node_count

            # Compute duration
            if s.transmit is True and s.tot_current > s.tot_start:
                s.duration = int(s.tot_current) - int(s.tot_start)
            if s.transmit is False:
                s.duration = 0

            # Save log
            l.log_write()

        # Last, manage tempo if necessary
        chrono_stop = time.time()
        chrono_time = chrono_stop - chrono_start
        if chrono_time < s.main_loop:
            sleep = s.main_loop - chrono_time
        else:
            sleep = 0
        #print "Temps d'execution : %.2f %.2f secondes" % (chrono_time, sleep)
        time.sleep(sleep)
        sys.stdout.flush()
Esempio n. 3
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '',
                                           ['help', 'log-path=', 'room='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--log-path'):
            s.log_path = arg
        elif opt in ('--room'):
            if arg not in [
                    'RRF', 'RRF_V1', 'TECHNIQUE', 'INTERNATIONAL', 'BAVARDAGE',
                    'LOCAL', 'EXPERIMENTAL', 'FON'
            ]:
                print(
                    'Unknown room name (choose between \'RRF\', \'TECHNIQUE\', \'INTERNATIONAL\', \'BAVARDAGE\', \'LOCAL\', \'EXPERIMENTAL\' and \'FON\')'
                )
                sys.exit()
            s.room = arg

    # Create directory and copy asset if necessary

    if not os.path.exists(s.log_path):
        os.makedirs(s.log_path)
    if not os.path.exists(s.log_path + '/' + 'assets'):
        os.popen('cp -a ../front/assets ' + s.log_path)

    tmp = datetime.datetime.now()
    s.day = tmp.strftime('%Y-%m-%d')

    s.log_path_day = s.log_path + '/' + s.room + '-' + s.day

    if not os.path.exists(s.log_path_day):
        os.makedirs(s.log_path_day)
        os.popen('cp /opt/RRFTracker/front/index.html ' + s.log_path_day +
                 '/' + 'index.html')
        os.popen('ln -sfn ' + s.log_path_day + ' ' + s.log_path + '/' +
                 s.room + '-today')

    # If restart on day...

    filename = s.log_path + '/' + s.room + '-today/rrf.json'
    if os.path.isfile(filename):
        l.restart()

    # Get user online
    s.user_count = l.log_user()

    # Load whereis dict
    l.whereis_load()

    # Load whois dict
    l.whois_load()

    # Boucle principale
    while (True):
        chrono_start = time.time()

        # If midnight...
        tmp = datetime.datetime.now()
        s.day = tmp.strftime('%Y-%m-%d')
        s.now = tmp.strftime('%H:%M:%S')
        s.hour = int(tmp.strftime('%H'))
        s.minute = int(s.now[3:-3])
        s.seconde = int(s.now[-2:])

        if (s.minute % 5 == 0):
            s.user_count = l.log_user()
            l.whereis_load()

        if (s.minute % 30 == 0):
            l.whois_load()

        if (s.now[:5] == '00:00'):
            s.log_path_day = s.log_path + '/' + s.room + '-' + s.day

            if not os.path.exists(s.log_path_day):
                os.makedirs(s.log_path_day)
                os.popen('cp /opt/RRFTracker/front/index.html ' +
                         s.log_path_day + '/index.html')
                os.popen('ln -sfn ' + s.log_path_day + ' ' + s.log_path + '/' +
                         s.room + '-today')

            s.qso = 0
            s.day_duration = 0
            for q in range(0, 24):  # Clean histogram
                s.qso_hour[q] = 0
            s.all.clear()  # Clear all history
            s.porteuse.clear()  # Clear porteuse history
            s.tot.clear()  # Clear tot history
            s.init = True  # Reset init

        # Request HTTP datas
        try:
            r = requests.get(s.room_list[s.room]['url'],
                             verify=False,
                             timeout=10)
            page = r.content.decode('utf-8')
        except requests.exceptions.ConnectionError as errc:
            print('Error Connecting:', errc)
        except requests.exceptions.Timeout as errt:
            print('Timeout Error:', errt)

        search_start = page.find('TXmit":"')  # Search this pattern
        search_start += 8  # Shift...
        search_stop = page.find('"', search_start)  # And close it...

        # If transmitter...
        if search_stop != search_start:

            if s.transmit is False:
                s.transmit = True

            s.call_current = l.sanitize_call(page[search_start:search_stop])

            if (s.call_previous != s.call_current):
                s.tot_start = time.time()
                s.tot_current = s.tot_start
                s.call_previous = s.call_current

                if s.call_date[0] == '' or s.call_date[0] > s.now:
                    blanc = 0
                else:
                    blanc = l.convert_time_to_second(
                        s.now) - l.convert_time_to_second(s.call_date[0])

                for i in range(9, 0, -1):
                    s.call[i] = s.call[i - 1]
                    s.call_date[i] = s.call_date[i - 1]
                    s.call_blanc[i] = s.call_blanc[i - 1]
                    s.call_time[i] = s.call_time[i - 1]

                s.call[0] = s.call_current
                s.call_blanc[0] = l.convert_second_to_time(blanc)

            else:
                if s.tot_start is '':
                    s.tot_start = time.time()
                    s.tot_current = s.tot_start

                    if s.call_date[0] == '' or s.call_date[0] > s.now:
                        blanc = 0
                    else:
                        blanc = l.convert_time_to_second(
                            s.now) - l.convert_time_to_second(s.call_date[0])

                    for i in range(9, 0, -1):
                        s.call[i] = s.call[i - 1]
                        s.call_date[i] = s.call_date[i - 1]
                        s.call_blanc[i] = s.call_blanc[i - 1]
                        s.call_time[i] = s.call_time[i - 1]

                    s.call[0] = s.call_current
                    s.call_blanc[0] = l.convert_second_to_time(blanc)

                else:
                    s.tot_current = time.time()

            s.duration = int(s.tot_current) - int(s.tot_start)

            # Save stat only if real transmit
            if (s.stat_save is False and s.duration > s.intempestif):
                #s.node = l.save_stat_node(s.node, s.call[0], 0)
                s.qso += 1
                tmp = datetime.datetime.now() - datetime.timedelta(seconds=3)
                s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])
                s.all = l.save_stat_all(s.all, s.call[0],
                                        tmp.strftime('%H:%M:%S'),
                                        l.convert_second_to_time(s.duration),
                                        True)

                s.stat_save = True

            # Format call time
            tmp = datetime.datetime.now()
            s.now = tmp.strftime('%H:%M:%S')
            s.hour = int(tmp.strftime('%H'))

            s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])

            s.call_date[0] = s.now
            s.call_time[0] = s.duration

            if s.duration > s.intempestif:
                s.all = l.save_stat_all(s.all, s.call[0],
                                        tmp.strftime('%H:%M:%S'),
                                        l.convert_second_to_time(s.duration),
                                        False)

            #sys.stdout.flush()

        # If no Transmitter...
        else:
            if s.transmit is True:
                '''
                if s.duration > s.intempestif:
                    #print tmp.strftime('%H:%M:%S')
                    #sys.stdout.flush()
                    s.all = l.save_stat_all(s.all, s.call[0], '00:00:00', l.convert_second_to_time(s.duration))
                '''

                if s.room == 'RRF':
                    #print l.convert_second_to_time(s.duration), s.tot_limit
                    #sys.stdout.flush()
                    if l.convert_second_to_time(s.duration) > s.tot_limit:
                        tmp = datetime.datetime.now()
                        s.tot = l.save_stat_tot(s.tot, s.call[0],
                                                tmp.strftime('%H:%M:%S'))

                if s.stat_save is True:
                    if s.duration > 600:  # I need to fix this bug...
                        s.duration = 0
                    #s.node = l.save_stat_node(s.node, s.call[0], s.duration)
                    s.day_duration += s.duration
                if s.stat_save is False:
                    tmp = datetime.datetime.now()
                    s.porteuse = l.save_stat_porteuse(s.porteuse, s.call[0],
                                                      tmp.strftime('%H:%M:%S'))

                s.transmit = False
                s.stat_save = False
                s.tot_current = ''
                s.tot_start = ''

        # Count node
        search_start = page.find('nodes":[')  # Search this pattern
        search_start += 9  # Shift...
        search_stop = page.find('],"TXmit"', search_start)  # And close it...

        tmp = page[search_start:search_stop]
        tmp = tmp.replace('"', '')
        s.node_list = tmp.split(',')

        for k, n in enumerate(s.node_list):
            s.node_list[k] = l.sanitize_call(n)

        for n in [
                'RRF', 'RRF2', 'RRF3', 'R.R.F', 'R.R.F_V2', 'TECHNIQUE',
                'BAVARDAGE', 'INTERNATIONAL', 'LOCAL', 'EXPERIMENTAL',
                'MsgNodeJoined('
        ]:
            if n in s.node_list:
                s.node_list.remove(n)

        if s.node_list_old == []:
            s.node_list_old = s.node_list
        else:
            if s.node_list_old != s.node_list:
                if (list(set(s.node_list_old) - set(s.node_list))):
                    s.node_list_out = list(
                        set(s.node_list_old) - set(s.node_list))
                    for n in s.node_list_out:
                        if n in s.node_list_in:
                            s.node_list_in.remove(n)
                    s.node_list_out = sorted(s.node_list_out)

                if (list(set(s.node_list) - set(s.node_list_old))):
                    s.node_list_in = list(
                        set(s.node_list) - set(s.node_list_old))
                    for n in s.node_list_in:
                        if n in s.node_list_out:
                            s.node_list_out.remove(n)
                    s.node_list_in = sorted(s.node_list_in)

                s.node_list_old = s.node_list

        s.node_count = len(s.node_list)

        if s.node_count > s.node_count_max:
            s.node_count_max = s.node_count

        if s.node_count < s.node_count_min:
            s.node_count_min = s.node_count

        # Compute duration
        if s.transmit is True and s.tot_current > s.tot_start:
            s.duration = int(s.tot_current) - int(s.tot_start)
        if s.transmit is False:
            s.duration = 0

        # Save log
        l.log_write()

        chrono_stop = time.time()
        chrono_time = chrono_stop - chrono_start
        if chrono_time < s.main_loop:
            sleep = s.main_loop - chrono_time
        else:
            sleep = 0
        #print "Temps d'execution : %.2f %.2f secondes" % (chrono_time, sleep)
        #sys.stdout.flush()
        time.sleep(sleep)
Esempio n. 4
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', ['help', 'interface=', 'i2c-port=', 'i2c-address=', 'display=', 'display-width=', 'display-height=', 'display-theme=', 'follow=', 'refresh=', 'latitude=', 'longitude='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--interface'):
            if arg not in ['i2c', 'spi']:
                print('Unknown interface type (choose between \'i2c\' and \'spi\')')
                sys.exit()
            s.interface = arg
        elif opt in ('--i2c-port'):
            s.i2c_port = int(arg)
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in ['sh1106', 'ssd1306', 'ssd1327', 'ssd1351', 'st7735']:
                print('Unknown display type (choose between \'sh1106\', \'ssd1306\',  \'ssd1327\', \'ssd1351\' and \'st7735\')')
                sys.exit()
            s.display = arg
        elif opt in ('--display-width'):
            s.display_width = int(arg)
        elif opt in ('--display-height'):
            s.display_height = int(arg)
        elif opt in ('--follow'):
            if arg in ['RRF', 'TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'FON']:
                s.room_current = arg
            else:
                tmp = l.scan(arg)
                if tmp is False:
                    s.room_current = 'RRF'
                else:
                    s.room_current = tmp
                    s.callsign = arg
                    s.scan = True
        elif opt in ('--refresh'):
            s.refresh = float(arg)
        elif opt in ('--latitude'):
            s.latitude = float(arg)
        elif opt in ('--longitude'):
            s.longitude = float(arg)
        elif opt in ('--display-theme'):
            s.display_theme = arg

    # Set serial
    if s.interface == 'i2c':
        serial = i2c(port=s.i2c_port, address=s.i2c_address)
        if s.display == 'sh1106':
            s.device = sh1106(serial, width=s.display_width, height=s.display_height, rotate=0)
        elif s.display == 'ssd1306':
            s.device = ssd1306(serial, width=s.display_width, height=s.display_height, rotate=0)
        elif s.display == 'ssd1327':
            s.device = ssd1327(serial, width=s.display_width, height=s.display_height, rotate=0, mode='RGB')
    else:
        serial = spi(device=0, port=0)
        if s.display == 'ssd1351':        
            s.device = ssd1351(serial, width=s.display_width, height=s.display_height, rotate=1, mode='RGB', bgr=True)
        elif s.display == 'st7735':
            s.device = st7735(serial, width=s.display_width, height=s.display_height, rotate=3, mode='RGB')

    init_message = []

    # Let's go
    init_message.append('RRFDisplay ' + s.version)
    init_message.append('')
    init_message.append('88 et 73 de F4HWN')
    init_message.append('')
    d.display_init(init_message)

    # Lecture du fichier de theme
    init_message.append('Chargement Theme')
    d.display_init(init_message)
    s.theme = cp.ConfigParser()
    s.theme.read('./themes/' + s.display_theme)

    # Lecture initiale de la progation et du cluster
    init_message.append('Requete Propagation')
    d.display_init(init_message)
    l.get_solar()

    init_message.append('Requete Cluster')
    d.display_init(init_message)
    l.get_cluster()

    init_message.append('Let\'s go')
    d.display_init(init_message)

    # Boucle principale
    s.timestamp_start = time.time()

    rrf_data = ''
    rrf_data_old = ''

    #print s.scan
    #print s.callsign
    #print s.room_current

    while(True):
        chrono_start = time.time()

        tmp = datetime.datetime.now()
        s.day = tmp.strftime('%Y-%m-%d')
        s.now = tmp.strftime('%H:%M:%S')
        s.hour = int(tmp.strftime('%H'))
        s.minute = int(s.now[3:-3])
        s.seconde = int(s.now[-2:])

        if s.seconde % 15 == 0 and s.scan == True: # On scan
            tmp = l.scan(s.callsign)
            if tmp is not False:
                #print s.now, tmp
                s.room_current = tmp

        if s.minute == 0: # Update solar propagation
            l.get_solar()

        if s.minute % 4 == 0: # Update cluster
            l.get_cluster()

        url = s.room[s.room_current]['url']

        # Requete HTTP vers le flux json du salon produit par le RRFDisplay 
        try:
            r = requests.get(url, verify=False, timeout=0.5)
        except requests.exceptions.ConnectionError as errc:
            #print ('Error Connecting:', errc)
            pass
        except requests.exceptions.Timeout as errt:
            #print ('Timeout Error:', errt)
            pass

        # Controle de la validité du flux json
        try:
            rrf_data = r.json()
        except:
            pass

        if rrf_data != '' and rrf_data != rrf_data_old: # Si le flux est valide
            rrf_data_old = rrf_data
            data_abstract = rrf_data['abstract'][0]
            data_activity = rrf_data['activity']
            data_transmit = rrf_data['transmit'][0]
            data_last = rrf_data['last']
            data_all = rrf_data['all']

            s.message[1] = l.sanitize_call(data_last[0]['Indicatif'])
            s.message[2] = l.sanitize_call(data_last[1]['Indicatif'])
            s.message[3] = l.sanitize_call(data_last[2]['Indicatif'])

            if s.device.height == 128:      # Only if place...
                try:
                    data_elsewhere = rrf_data['elsewhere'][0]

                    i = 0
                    s.transmit_elsewhere = False
                    for data in rrf_data['elsewhere'][6]:
                        if data in ['RRF', 'TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'FON']:
                            tmp = rrf_data['elsewhere'][6][data]
                            if tmp != 0:
                                s.transmit_elsewhere = True
                                s.raptor[i] = l.convert_second_to_time(tmp) + '/' + data[:3] + '/' + l.sanitize_call(rrf_data['elsewhere'][1][data]) + '/' + str(rrf_data['elsewhere'][5][data])
                            else:
                                s.raptor[i] = l.convert_second_to_time(tmp) + '/' + data[:3] + '/' + l.convert_time_to_string(rrf_data['elsewhere'][3][data]) + '/' + str(rrf_data['elsewhere'][5][data])

                            i += 1
                except:
                    pass

            if data_transmit['Indicatif'] != '':
                if s.transmit is False:      # Wake up screen...
                    s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

                s.call_current = l.sanitize_call(data_transmit['Indicatif'])
                s.call_type = data_transmit['Type']
                s.call_description = data_transmit['Description']
                s.call_tone = data_transmit['Tone']
                s.call_locator = data_transmit['Locator']
                s.call_sysop = data_transmit['Sysop']
                s.call_prenom = data_transmit['Prenom']
                s.call_latitude = data_transmit['Latitude']
                s.call_longitude = data_transmit['Longitude']

                s.duration = data_transmit['TOT']

            else:
                if s.transmit is True:       # Sleep screen...
                    s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

                # Load Histogram
                for q in range(0, 24):
                    s.qso_hour[q] = data_activity[q]['TX']

                # Load Last
                limit = len(rrf_data['last'])
                s.call = [''] * 10 
                s.call_time = [''] * 10 

                for q in range(0, limit):
                    s.call[q] = l.sanitize_call(rrf_data['last'][q]['Indicatif'])
                    s.call_time[q] = rrf_data['last'][q]['Heure']

                # Load Best
                limit = len(rrf_data['all'])
                s.best = [''] * 10 
                s.best_time = [0] * 10 

                for q in range(0, limit):
                    s.best[q] = l.sanitize_call(rrf_data['all'][q]['Indicatif'])
                    s.best_time[q] = l.convert_time_to_second(rrf_data['all'][q]['Durée'])

            if(s.seconde < 10):     # TX today
                s.message[0] = 'TX total ' + str(data_abstract['TX total'])

            elif(s.seconde < 20):   # Active node
                s.message[0] = 'Links actifs ' + str(data_abstract['Links actifs'])

            elif(s.seconde < 30):   # Online node
                s.message[0] = 'Links total ' + str(data_abstract['Links connectés'])
                
            elif(s.seconde < 40):   # Total emission
                tmp = l.convert_time_to_string(data_abstract['Emission cumulée'])
                if 'h' in tmp:
                    tmp = tmp[0:6]
                s.message[0] = 'BF total ' + tmp

            elif(s.seconde < 50):   # Last TX
                s.message[0] = 'Dernier ' + data_last[0]['Heure']

            elif(s.seconde < 60):   # Scan
                if s.scan is True:
                    s.message[0] = 'Suivi de ' + s.callsign
                else:
                    s.message[0] = 'Salon ' + s.room_current[:3]

        # Print screen
        if s.device.height == 128:
            d.display_128()
        else:
            d.display_64()

        chrono_stop = time.time()
        chrono_time = chrono_stop - chrono_start
        if chrono_time < s.refresh:
            sleep = s.refresh - chrono_time
        else:
            sleep = 0
        #print "Temps d'execution : %.2f %.2f secondes" % (chrono_time, sleep)
        #sys.stdout.flush()

        time.sleep(sleep)
Esempio n. 5
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', [
            'help', 'i2c-port=', 'i2c-address=', 'display=', 'display-width=',
            'display-height=', 'room=', 'latitude=', 'longitude='
        ])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--i2c-port'):
            s.i2c_port = arg
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in ['sh1106', 'ssd1306']:
                print 'Unknown display type (choose between \'sh1106\' and \'ssd1306\')'
                sys.exit()
            s.display = arg
        elif opt in ('--display-width'):
            s.display_width = int(arg)
        elif opt in ('--display-height'):
            s.display_height = int(arg)
        elif opt in ('--room'):
            if arg not in ['RRF', 'TEC', 'FON']:
                print 'Unknown room name (choose between \'RRF\', \'TEC\' and \'FON\')'
                sys.exit()
            s.room = arg
        elif opt in ('--latitude'):
            s.latitude = float(arg)
        elif opt in ('--longitude'):
            s.longitude = float(arg)

    # Set serial
    serial = i2c(port=s.i2c_port, address=s.i2c_address)
    if s.display == 'sh1106':
        s.device = sh1106(serial,
                          width=s.display_width,
                          height=s.display_height,
                          rotate=0)
    else:
        s.device = ssd1306(serial,
                           width=s.display_width,
                           height=s.display_height,
                           rotate=0)

    # Set url
    if s.room == 'RRF':
        url = 'http://rrf.f5nlg.ovh/api/svxlink/RRF'
    elif s.room == 'TEC':
        url = 'http://rrf.f5nlg.ovh/api/svxlink/technique'
    elif s.room == 'FON':
        url = 'http://fon.f1tzo.com:81'

    # Boucle principale
    s.timestamp_start = time.time()

    while (True):

        # If midnight...
        tmp = datetime.datetime.now()
        s.day = tmp.strftime('%Y-%m-%d')
        s.now = tmp.strftime('%H:%M:%S')
        s.hour = int(tmp.strftime('%H'))
        s.minute = int(s.now[3:-3])
        s.seconde = int(s.now[-2:])

        if (s.now[:5] == '00:00'):
            s.qso_total += s.qso
            s.qso = 0
            for q in xrange(0, 24):  # Clean histogram
                s.qso_hour[q] = 0
            s.history.clear()  # Clear history

        # Request HTTP datas
        try:
            r = requests.get(url, verify=False, timeout=10)
            page = r.content
        except requests.exceptions.ConnectionError as errc:
            print('Error Connecting:', errc)
        except requests.exceptions.Timeout as errt:
            print('Timeout Error:', errt)

        search_start = page.find('TXmit":"')  # Search this pattern
        search_start += 8  # Shift...
        search_stop = page.find('"', search_start)  # And close it...

        # If transmitter...
        if search_stop != search_start:

            if s.transmit is False:  # Wake up screen...
                s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)

            # Clean call
            tmp = page[search_start:search_stop]
            tmp = tmp.replace('(', '')
            tmp = tmp.replace(') ', ' ')
            tmp = tmp.replace('\u0026U', '&')  # Replace ampersand...

            s.call_current = tmp

            if (s.call_previous != s.call_current):
                s.tot_start = time.time()
                s.tot_current = s.tot_start
                s.call_previous = s.call_current

                for i in xrange(4, 0, -1):
                    s.call[i] = s.call[i - 1]
                    s.call_time[i] = s.call_time[i - 1]

                s.call[0] = s.call_current
            else:
                if s.tot_start is '':
                    s.tot_start = time.time()
                    s.tot_current = s.tot_start

                    for i in xrange(4, 0, -1):
                        s.call[i] = s.call[i - 1]
                        s.call_time[i] = s.call_time[i - 1]

                    s.call[0] = s.call_current
                else:
                    s.tot_current = time.time()

            s.duration = int(s.tot_current) - int(s.tot_start)

            # Save stat only if real transmit
            if (s.stat_save is False and s.duration > 2):
                s.history = l.save_stat(s.history, s.call[0])
                s.qso += 1
                s.stat_save = True

            # Format call time
            tmp = datetime.datetime.now()
            s.now = tmp.strftime('%H:%M:%S')
            s.hour = int(tmp.strftime('%H'))

            s.qso_hour[s.hour] = s.qso - sum(s.qso_hour[:s.hour])

            s.call_time[0] = s.now

            s.message[0] = s.call[2]
            s.message[1] = s.call[1]
            s.message[2] = s.call[0]

        # If no Transmitter...
        else:
            if s.transmit is True:  # Sleep screen...
                s.transmit = l.wake_up_screen(s.device, s.display, s.transmit)
                s.stat_save = False
                s.tot_current = ''
                s.tot_start = ''

            s.message[0] = s.call[1]
            s.message[1] = s.call[0]
            if s.qso == 0:
                s.call_time[0] = 'Waiting TX'
                s.message[2] = s.call_time[0]
            else:
                s.message[2] = 'Last TX ' + s.call_time[0]

        if (s.blanc_alternate == 0):  # TX today
            tmp = 'TX Today '
            tmp += str(s.qso)

            s.message[4] = tmp

            s.blanc_alternate = 1

        elif (s.blanc_alternate == 1):  # Boot time
            tmp = 'Up '
            tmp += l.calc_uptime(time.time() - s.timestamp_start)

            s.message[4] = tmp

            s.blanc_alternate = 2

        elif (s.blanc_alternate == 2):  # TX total
            tmp = 'TX Total '
            tmp += str(s.qso_total + s.qso)

            s.message[4] = tmp

            s.blanc_alternate = 3

        elif (s.blanc_alternate == 3):  # Best link
            if len(s.history) >= 5:
                best = max(s.history, key=s.history.get)
                s.message[4] = best + ' ' + str(s.history[best]) + ' TX'
            else:
                s.message[4] = 'Need more datas'

            s.blanc_alternate = 4

        elif (s.blanc_alternate == 4):  # count node

            search_start = page.find('nodes":[')  # Search this pattern
            search_start += 9  # Shift...
            search_stop = page.find('],"TXmit"',
                                    search_start)  # And close it...

            tmp = page[search_start:search_stop]

            tmp = tmp.split(',')

            s.message[4] = 'Online nodes ' + str(len(tmp))

            s.blanc_alternate = 0

        # Print screen
        if s.device.height == 64:
            d.display_64()
        else:
            d.display_32()

        time.sleep(2)
Esempio n. 6
0
def main(argv):
    # Check and get arguments

    try:
        options, remainder = getopt.getopt(argv, '', ['help', 'debug=', 'path=', 'year=', 'month=', 'week=', 'day=', 'room=', 'order=', 'format='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            usage()
            sys.exit()
        elif opt in ('--path'):
            s.analyse_path = arg
        elif opt in ('--debug'):
            if arg not in ['True', 'False']:
                print('Unknown debug mode (choose between \'True\' and \'False\')')
                sys.exit()
            if arg == 'True':
                s.analyse_debug = True
            else:
                s.analyse_debug = False
        elif opt in ('--year'):
            s.analyse_year = arg
            s.analyse_type = 'year'
        elif opt in ('--month'):
            s.analyse_month = arg
            if int(s.analyse_month) <= 0:
                today = datetime.date.today().strftime("%Y-%m-%d")
                today = datetime.datetime.strptime(today, '%Y-%m-%d').date()
                past = today + relativedelta(months=int(s.analyse_month))
                past = str(past).split('-')
                s.analyse_year = str(past[0])
                s.analyse_month = str(past[1]) 
            s.analyse_type = 'month'
        elif opt in ('--week'):
            s.analyse_week = arg
            if s.analyse_week == '0':
                #s.analyse_week = str(datetime.date.today().isocalendar()[1] - 1)
                s.analyse_week = str(datetime.date.today().isocalendar()[1]) # Patch week (29/05/2021) 
            s.analyse_type = 'week'
        elif opt in ('--day'):
            s.analyse_day = arg
            s.analyse_type = 'day'
        elif opt in ('--room'):
            if arg not in ['ALL', 'EXTRA', 'RRF', 'TECHNIQUE', 'BAVARDAGE', 'LOCAL', 'INTERNATIONAL', 'EXPERIMENTAL', 'FON']:
                print('Unknown room name (choose between \'ALL\', \'EXTRA\', \'RRF\', \'TECHNIQUE\', \'BAVARDAGE\', \'LOCAL\', \'INTERNATIONAL\', \'EXPERIMENTAL\' and \'FON\')')
                sys.exit()
            if arg == 'ALL':
                s.analyse_room = ['RRF', 'TECHNIQUE', 'BAVARDAGE', 'LOCAL', 'INTERNATIONAL', 'EXPERIMENTAL']
            elif arg == 'EXTRA':
                s.analyse_room = ['RRF', 'TECHNIQUE', 'BAVARDAGE', 'LOCAL', 'INTERNATIONAL', 'EXPERIMENTAL', 'FON']
            else:
                s.analyse_room = [arg]
        elif opt in ('--order'):
            if arg not in ['BF', 'TX', 'INTEMPESTIF', 'RATIO']:
                print('Unknown order type (choose between \'BF\', \'TX\', \'INTEMPESTIF\' and \'RATIO\')')
                sys.exit()
            s.analyse_order = arg
        elif opt in ('--format'):
            if arg not in ['TEXT', 'JSON']:
                print('Unknown format type (choose between \'TEXT\' and \'JSON\')')
                sys.exit()
            s.analyse_format = arg

    # Debug trace

    when = ''
    if s.analyse_type == 'year':
        when = 'de l\'année ' + s.analyse_year
    elif s.analyse_type == 'month':
        if s.analyse_month == str(0):
            when = 'depuis le début du mois'
        else:
            when = 'du mois ' + s.analyse_month + '/' + s.analyse_year
    elif s.analyse_type == 'week':
        when = 'depuis le début de la semaine '
    elif s.analyse_type == 'day':
        if s.analyse_day == str(1):
            when = 'aujourd\'hui'
        else:
            when = 'sur les ' + s.analyse_day + ' derniers jours'

    if s.analyse_debug is True:
        print(l.color.BLUE + 'Path : ' + l.color.END + s.analyse_path)
        print(l.color.BLUE + 'Room : ' + l.color.END + ', '.join(s.analyse_room))
        print(l.color.BLUE + 'Search type : ' + l.color.END + s.analyse_type)
        print(l.color.BLUE + 'Search year : ' + l.color.END + s.analyse_year)
        if s.analyse_type == 'month':
            print(l.color.BLUE + 'Search month : ' + l.color.END + s.analyse_month)
        elif s.analyse_type == 'week':
            print(l.color.BLUE + 'Search week : ' + l.color.END + s.analyse_week)
        elif s.analyse_type == 'day':
            print(l.color.BLUE + 'Search day : ' + l.color.END + s.analyse_day)
        print(l.color.BLUE + 'Search order : ' + l.color.END + s.analyse_order)
        print(l.color.BLUE + 'Search format : ' + l.color.END + s.analyse_format)
        print('===========')

    # Loop

    flux = {}
    graph = {}

    for r in s.analyse_room:
        time_max = 0
        file = []
        all = {}

        if s.analyse_type == 'year':
            s.analyse_pattern = s.analyse_year
            path = s.analyse_path + r + '-' + s.analyse_pattern + '-*/rrf.json'
            file = glob.glob(path)
            file.sort()
        elif s.analyse_type == 'month':
            s.analyse_pattern = s.analyse_year + '-' +  s.analyse_month
            path = s.analyse_path + r + '-' + s.analyse_pattern + '-*/rrf.json'
            file = glob.glob(path)
            file.sort()
        elif s.analyse_type == 'week':
            s.analyse_pattern = s.analyse_week
            start_date = time.asctime(time.strptime(s.analyse_year + ' %d 1' % int(s.analyse_pattern), '%Y %W %w'))
            start_date = datetime.datetime.strptime(start_date, '%a %b %d %H:%M:%S %Y')
            file = [s.analyse_path + r + '-' + start_date.strftime('%Y-%m-%d') + '/rrf.json']
            for i in range(1, 7):
                file.append(s.analyse_path + r + '-' + (start_date + datetime.timedelta(days=i)).strftime('%Y-%m-%d') + '/rrf.json')
        else:
            s.analyse_pattern = int(s.analyse_day) - 1
            start_date = datetime.datetime.now() - datetime.timedelta(s.analyse_pattern)
            file = [s.analyse_path + r + '-' + start_date.strftime('%Y-%m-%d') + '/rrf.json']
            for i in range(1, s.analyse_pattern + 1):
                file.append(s.analyse_path + r + '-' + (start_date + datetime.timedelta(days=i)).strftime('%Y-%m-%d') + '/rrf.json')

        # Surf files

        for f in file:

            # Debug trace
            if s.analyse_debug is True:
                print(f)
            
            if os.path.isfile(f):
                rrf_json = open(f)
                rrf_data = rrf_json.read()
                rrf_data = rrf_data.replace('Extended', '') # Fix old format !
                try:
                    rrf_data = json.loads(rrf_data)


                    tmp = f.split('-')
                    created_data = tmp[3][0:2] + '/' + tmp[2] + '/' + tmp[1]
                    created_data_iso = tmp[1] + '/' + tmp[2] + '/' + tmp[3][0:2]
                    for data in rrf_data['abstract']:
                        if created_data in graph:
                            graph[created_data] += l.convert_time_to_second(data['Emission cumulée'])
                        else:
                            graph[created_data] = l.convert_time_to_second(data['Emission cumulée'])

                    for data in rrf_data['all']:
                        indicatif = re.sub(' +', ' ', data['Indicatif'])
                        check = indicatif.split(' ')
                        if 'proxy to:' not in indicatif: # Sometimes bug
                            if len(check) == 3 or indicatif in ['TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'GW-C4FM-30262', 'RRF', 'GW-ALLSTAR-40020'] or r == 'FON':
                                try:
                                    all[indicatif][0] += l.convert_time_to_second(data['Durée'])
                                    if all[indicatif][0] > time_max:
                                        time_max = all[indicatif][0]
                                    all[indicatif][1] += data['TX']
                                    if created_data_iso > all[indicatif][5]: 
                                        all[indicatif][5] = created_data_iso  
                                except:
                                    all[indicatif] = [l.convert_time_to_second(data['Durée']), data['TX'], 0, 0, 0, created_data_iso]

                    for data in rrf_data['porteuse']:
                        indicatif = data['Indicatif']
                        check = indicatif.split(' ')
                        if 'proxy to:' not in indicatif: # Sometimes bug
                            if len(check) == 3 or indicatif in ['TECHNIQUE', 'INTERNATIONAL', 'LOCAL', 'BAVARDAGE', 'GW-C4FM-30262', 'RRF', 'GW-ALLSTAR-40020'] or r == 'FON':
                                try:
                                    all[indicatif][2] += data['TX']
                                    if created_data_iso > all[indicatif][5]:
                                        all[indicatif][5] = created_data_iso
                                except:
                                    all[indicatif] = [0, 0, data['TX'], 0, 0, created_data_iso]
                except:
                    pass 

        # Clean artefect

        #time_format = '{:0>' + str(len(str(time_max // 3600))) + 'd}'
        time_format = '{:0>3d}'

        # Compute ratio and abstract

        abstract = {
            "Salon": '',
            "Links total": 0, 
            "Emission cumulée": 0, 
            "TX total": 0, 
            "TX moyen": 0,
            "Intempestifs total": 0
        }

        for e in all:
            abstract['Links total'] += 1
            abstract['Emission cumulée'] += all[e][0]
            abstract['TX total'] += all[e][1]
            abstract['Intempestifs total'] += all[e][2]
            if all[e][2] != 0:  # Prevent divide by zero...
                all[e][3] = all[e][0] / all[e][2]
            else:
                all[e][3] = -1
            if all[e][1] != 0:  # Prevent divide by zero...
                all[e][4] = all[e][0] / all[e][1]
            else:
                all[e][4] = -1

        abstract['Salon'] = r
        if abstract['TX total'] != 0:
            abstract['TX moyen'] = abstract['Emission cumulée'] / abstract['TX total']
        else:
            abstract['TX moyen'] = 0
        abstract['Emission cumulée'] = l.convert_second_to_time(abstract['Emission cumulée'])

        # Sort by order 

        if s.analyse_order == 'BF':
            tmp = sorted(list(all.items()), key=lambda x: x[1][0])
            tmp.reverse()
        elif s.analyse_order == 'TX':
            tmp = sorted(list(all.items()), key=lambda x: x[1][1])
            tmp.reverse()
        elif s.analyse_order == 'INTEMPESTIF':
            tmp = sorted(list(all.items()), key=lambda x: x[1][2])
            tmp.reverse()
        elif s.analyse_order == 'RATIO':
            tmp = sorted(list(all.items()), key=lambda x: x[1][3])
            tmp.reverse()
        elif s.analyse_order == 'BAVARD':
            tmp = sorted(list(all.items()), key=lambda x: x[1][4])
            tmp.reverse()

        # Compute log

        log = []
        indice = 1
        for e in tmp:
            log.append({'Pos': indice, 'Indicatif': e[0], 'Emission cumulée': l.convert_second_to_time(e[1][0], time_format), 'TX total': e[1][1], 'TX moyen': e[1][4], 'Intempestifs total': e[1][2], 'Ratio': e[1][3], 'Last': e[1][5]})
            indice += 1

        # Prepare JSON

        flux.update({r: {'abstract': [abstract], 'log': log}})

    # Prepare total

    total = {}
    for r in s.analyse_room:
        for e in flux[r]['log']:
            indicatif = e['Indicatif']
            emission = l.convert_time_to_second(e['Emission cumulée'])
            tx = e['TX total']
            intempestifs = e['Intempestifs total']
            last = e['Last']

            #print r, indicatif, emission, tx, intempestifs, last

            if indicatif in total:
                total[indicatif][0] += emission
                total[indicatif][1] += tx
                total[indicatif][2] += intempestifs
                if total[indicatif][5] < last:
                    total[indicatif][5] = last
                    
            else:
                total[indicatif] = [emission, tx, intempestifs, 0, 0, last]

    # Compute ratio and abstract

    abstract = {
        "Salon": '',
        "Links total": 0, 
        "Emission cumulée": 0, 
        "TX total": 0, 
        "TX moyen": 0,
        "Intempestifs total": 0
    }

    for e in total:
        abstract['Links total'] += 1
        abstract['Emission cumulée'] += total[e][0]
        abstract['TX total'] += total[e][1]
        abstract['Intempestifs total'] += total[e][2]
        if total[e][2] != 0:  # Prevent divide by zero...
            total[e][3] = total[e][0] / total[e][2]
        else:
            total[e][3] = -1
        if total[e][1] != 0:  # Prevent divide by zero...
            total[e][4] = total[e][0] / total[e][1]
        else:
            total[e][4] = -1

    abstract['Salon'] = 'Global'

    flux.update({'Counter': abstract['Emission cumulée']})
    if abstract['TX total'] != 0:
        abstract['TX moyen'] = abstract['Emission cumulée'] / abstract['TX total']
    else:
        abstract['TX moyen'] = 0
    abstract['Emission cumulée'] = l.convert_second_to_time(abstract['Emission cumulée'])

    # Sort by order 

    if s.analyse_order == 'BF':
        tmp = sorted(list(total.items()), key=lambda x: x[1][0])
        tmp.reverse()
    elif s.analyse_order == 'TX':
        tmp = sorted(list(total.items()), key=lambda x: x[1][1])
        tmp.reverse()
    elif s.analyse_order == 'INTEMPESTIF':
        tmp = sorted(list(total.items()), key=lambda x: x[1][2])
        tmp.reverse()
    elif s.analyse_order == 'RATIO':
        tmp = sorted(list(total.items()), key=lambda x: x[1][3])
        tmp.reverse()
    elif s.analyse_order == 'BAVARD':
        tmp = sorted(list(total.items()), key=lambda x: x[1][4])
        tmp.reverse()

    # Compute log

    log = []
    indice = 1

    for e in tmp:
        log.append({'Pos': indice, 'Indicatif': e[0], 'Emission cumulée': l.convert_second_to_time(e[1][0], time_format), 'TX total': e[1][1], 'TX moyen': e[1][4], 'Intempestifs total': e[1][2], 'Ratio': e[1][3], 'Last': e[1][5]})
        indice += 1

    flux.update({'Global': {'abstract': [abstract], 'log': log}})

    flux.update({'Stat': s.stat_list})
    flux.update({'When': when})

    now = datetime.datetime.now()
    flux.update({'Update': now.strftime('%H:%M, le %d/%m/%Y')})

    histogram = []
    od = collections.OrderedDict(sorted(graph.items()))
    for k, v in od.items():
        histogram.append({'Date': k, 'Secondes': v, 'Temps': l.convert_second_to_time(v)})

    #print(histogram)

    flux.update({'Histogram': histogram})

    print(json.dumps(flux, sort_keys=True))
Esempio n. 7
0
def main(argv):

    # Check and get arguments
    try:
        options, remainder = getopt.getopt(argv, '', [
            'help', 'interface=', 'i2c-port=', 'i2c-address=', 'display=',
            'display-width=', 'display-height='
        ])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt in ('--interface'):
            if arg not in ['i2c', 'spi']:
                print 'Unknown interface type (choose between \'i2c\' and \'spi\')'
                sys.exit()
            s.interface = arg
        elif opt in ('--i2c-port'):
            s.i2c_port = int(arg)
        elif opt in ('--i2c-address'):
            s.i2c_address = int(arg, 16)
        elif opt in ('--display'):
            if arg not in [
                    'sh1106', 'ssd1306', 'ssd1327', 'ssd1351', 'st7735'
            ]:
                print 'Unknown display type (choose between \'sh1106\', \'ssd1306\',  \'ssd1327\', \'ssd1351\' and \'st7735\')'
                sys.exit()
            s.display = arg
        elif opt in ('--display-width'):
            s.display_width = int(arg)
        elif opt in ('--display-height'):
            s.display_height = int(arg)

    # Set serial
    if s.interface == 'i2c':
        serial = i2c(port=s.i2c_port, address=s.i2c_address)
        if s.display == 'sh1106':
            s.device = sh1106(serial,
                              width=s.display_width,
                              height=s.display_height,
                              rotate=0)
        elif s.display == 'ssd1306':
            s.device = ssd1306(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=0)
        elif s.display == 'ssd1327':
            s.device = ssd1327(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=0,
                               mode='RGB')
    else:
        serial = spi(device=0, port=0)
        if s.display == 'ssd1351':
            s.device = ssd1351(serial,
                               width=s.display_width,
                               height=s.display_height,
                               rotate=1,
                               mode='RGB',
                               bgr=True)
        elif s.display == 'st7735':
            s.device = st7735(serial,
                              width=s.display_width,
                              height=s.display_height,
                              rotate=3,
                              mode='RGB')

    while True:
        print 'Start'
        l.scroll_message("Il etait une fois tout petit chaton.")
        print 'Stop'
Esempio n. 8
0
def main(argv):

    # Check et capture des arguments
    try:
        options, remainder = getopt.getopt(argv, '', ['help', 'version', 'scan=', 'scan_sleep=', 'park=', 'park_sleep=', 'debug='])
    except getopt.GetoptError:
        l.usage()
        sys.exit(2)
    for opt, arg in options:
        if opt == '--help':
            l.usage()
            sys.exit()
        elif opt == '--version':
            print(s.version)
            sys.exit()
        elif opt in ('--scan'):
            if arg in ['True', 'true']:
                s.scan = True
            else:
                s.scan = False
        elif opt in ('--scan_sleep'):
            s.scan_sleep = float(arg)
        elif opt in ('--park'):
            if arg in ['True', 'true']:
                s.park = True
            else:
                s.park = False
        elif opt in ('--park_sleep'):
            s.park_sleep = float(arg)
        elif opt in ('--debug'):
            if arg in ['True', 'true']:
                s.debug = True
            else:
                s.debug = False

    if s.scan is True: # Si scan simple
        l.where_is()
        file = open('/tmp/RRFRaptor_scan.tcl', 'w')
        while(True):
            if s.room_current not in s.room_passive:  # Si ce n'est pas un salon passif
                if l.read_log() is True:
                    file.write('set RRFRaptor "' + l.scan() + '"\n')
                    file.close()
                    sys.exit()
            else: # Si c'est un salon passif, le scan ne fonctionne pas
                file.write('set RRFRaptor "None"\n')
                file.close()
                sys.exit()

    else: # Sinon, boucle principale

        # Log des parametres au demarrage
        
        now = datetime.datetime.now()

        print(now.strftime('%H:%M:%S') + ' - Initialisation RRFRaptor...')
        print('           -> version    = ' + s.version)
        print('           -> scan       = ' + str(s.scan))
        print('           -> scan_sleep = ' + str(s.scan_sleep))
        print('           -> park       = ' + str(s.park))
        print('           -> park_sleep = ' + str(s.park_sleep))
        print('           -> debug      = ' + str(s.debug))

        while(True):
            # Lecture du salon courant
            l.where_is()
            now = datetime.datetime.now()

            if s.room_current not in s.room_passive:  # Si ce n'est pas un salon passif
                # Lecture de l'activité
                l.read_log()

                # Gestion de la temporisation
                s1 = s.room[s.room_current]['last']
                s2 = time.time()

                # Gestion du parking
                if s.park is True and s.room_current != s.room_base: # Si on doit parker...
                    if (s2 - s1) > s.park_sleep: # Et que la temporisation est atteinte, on park
                        s.room_current = s.room_base
                        l.qsy(s.room_current)
                        s.room[s.room_current]['last'] = s1
                        print(now.strftime('%H:%M:%S') + ' - Parking sur ' + s.room_current + '...')

                # Gestion du scan
                if (s2 - s1) > s.scan_sleep: # Si la temporisation atteinte, on scan
                    if s.debug is True or s.scan is True: # Attention, on réutilise ici la variable s.scan mais ne pas la confondre avec l'option --scan
                        s.scan = False
                        print(now.strftime('%H:%M:%S') + ' - Scan en cours...')
                    l.qsy()
                else: # Sinon, on affiche éventuellement une trace
                    if s.debug is True:
                        print(now.strftime('%H:%M:%S') + ' - Standby sur ' + s.room_current + ' depuis ' + str(int(s2 - s1)) + ' secondes')
                    else:
                        if s.scan is False: # Attention, on réutilise ici la variable s.scan mais ne pas la confondre avec l'option --scan
                            print(now.strftime('%H:%M:%S') + ' - Standby sur ' + s.room_current + ' (reset scan_sleep)')
                    s.scan = True

            else: # Sinon on ne fait rien sur le perroquet
                if s.debug is True:
                    print(now.strftime('%H:%M:%S') + ' - ' + s.room_current)

            # On controle toutes les 5 secondes, c'est suffisant...
            time.sleep(5)
            sys.stdout.flush()
Esempio n. 9
0
        l = []
        ma = line.split(':')
        if len(ma) > 1:
            map2 = ma[1].split(",")
            l.append(ma[0])
            l.append(map2)
        else:
            l.append(ma[0])
        params.append(l)
    return params


if __name__ == '__main__':

    if (len(sys.argv) != 5):
        lib.usage()

    inst_file = sys.argv[1]
    data_file = sys.argv[2]
    reg_file = sys.argv[3]
    config_file = sys.argv[4]

    insts = read_file(inst_file)
    data = read_file(data_file)
    regs = read_file(reg_file)
    configs = read_file(config_file)

    'preprocess raw data'
    insts = preprocess(insts)
    data = preprocess(data)
    regs = preprocess(regs)