Example #1
0
def daemon_restart():
    config = Configuration()
    config.load()
    cmd = [config.interpreter, os.path.abspath(os.path.join(os.path.dirname(__file__), 'uploader.py')), 'restart']
    subprocess.Popen(cmd)
    time.sleep(0.5)
    return redirect(url_for('daemon_status'))
Example #2
0
def main():
    configutation = Configuration().load()
    path = configutation.get('upload_folder')
    if path:
        for file_name in get_file_names(path):
            file_changed = False
            result = None
            f = os.path.basename(file_name)
            file_object = get_file_object_or_create(f)
            current_file_info = get_file_info(file_name)
            current_file_timestamp = current_file_info[0].replace('-', '').replace(':', '').replace(' ', '')
            # file exist
            if file_object.timestamp:
                if file_object.timestamp < current_file_timestamp:
                    file_changed = True
                    # 2. TODO: Do POST, set result
                    result = 200
                    # 2. Update model
                    file_object.updated_at = datetime.utcnow()
                    file_object.timestamp = current_file_timestamp
            else:
                # 1. TODO: Do POST, set result
                result = 200
                file_object.updated_at = datetime.utcnow()
                file_object.timestamp = current_file_timestamp
                file_changed = True
            db.session.add(file_object)
            db.session.commit()

            if file_changed:
                event_type_file_changed = EventType.query.get(4)
                event_file_changed = Event(name='%s changed ' % f, event_type=event_type_file_changed,
                                               file=file_object, date=None, file_attrs=str(current_file_info),
                                               result_code=None)
                db.session.add(event_file_changed)
                db.session.commit()

            if result:
                event_type_uploading = EventType.query.get(3)
                event_file_uploading = Event(name='%s uploading ' % f, event_type=event_type_uploading,
                                             file=file_object, date=None, file_attrs=str(current_file_info),
                                             result_code=result)
                db.session.add(event_file_uploading)
                db.session.commit()
Example #3
0
 def packages(self, request):
     api_log.debug('%s - [GET] %s/packages',
                   request.getHost().host, self.path)
     try:
         config = Configuration()
         data = json.dumps(config.get_packages(), cls=PGEncoder)
     except ConfigurationException as e:
         data = {'status': 'failed', 'error': str(e)}
     api_log.debug(data)
     return data
Example #4
0
 def site(self, request):
     api_log.debug('%s - [GET] %s/site', request.getHost().host, self.path)
     try:
         config = Configuration()
         data = json.dumps(config.get_site(), cls=PGEncoder)
     except ConfigurationException as e:
         data = {'status': 'failed', 'error': str(e)}
     except psycopg2.InterfaceError as e:
         if str(e) == "connection already closed":
             api_log.debug("Exiting due to DB Error: %s", e)
             os._exit(-1)
     api_log.debug(data)
     return data
Example #5
0
 def run(self):
     configuration = Configuration()
     configuration.load()
     path = configuration.upload_folder
     tick = configuration.tick
     #file_name = os.path.abspath(os.path.join(os.path.dirname(__file__), 'fuckup.log'))
     while True:
         if path:
             for file_name in get_file_names(path):
                 file_changed = False
                 result = None
                 f = os.path.basename(file_name)
                 file_object = get_file_object_or_create(f)
                 current_file_info = get_file_info(file_name)
                 current_file_timestamp = current_file_info[0].replace('-', '').replace(':', '').replace(' ', '')
                 #file exist
                 if file_object.timestamp:
                     if int(file_object.timestamp) < int(current_file_timestamp):
                         file_changed = True
                         upload_file(file_name, file_object, current_file_timestamp)
                 else:
                     file_changed = True
                     upload_file(file_name, file_object, current_file_timestamp)
         time.sleep(float(tick))
Example #6
0
    def addComponentsOSC(self, component):
        """Adds a sensor data component to the OSC message"""
        for data in component.data:
            self.msg_builder.add_arg(float(data))

    def addCalibrationStatus(self, calibration_status):
        """Adds the calibration status data to the OSC message"""
        self.msg_builder.add_arg(calibration_status[0] & 0x03)
        self.msg_builder.add_arg((calibration_status[0] & 0x0C) >> 2)
        self.msg_builder.add_arg((calibration_status[0] & 0x30) >> 4)
        self.msg_builder.add_arg((calibration_status[0] & 0xC0) >> 6)


if __name__ == '__main__':
    # shortcut to not have to find out the port yourself
    serial_port = Configuration.get_correct_serial_port()

    remote_id = 0x6120  # remote device network ID
    remote = True  # whether to use a remote device
    if not remote:
        remote_id = None

    index = 0
    previous_cycle_time = 0
    current_cycle_time = 0

    # import properties from saved properties file
    (remote, remote_id, anchors, attributes_to_log, to_use_file, filename,
     use_processing) = Configuration.get_properties()

    if not remote:
            single.device_range = device_range
            single.sensor_data = sensor_data
            single.loop_status = loop_status

            if loop_status != POZYX_SUCCESS:
                single.num_of_error += 1


class ContinueI(Exception):
    pass


continue_i = ContinueI()

if __name__ == "__main__":
    serial_port = Configuration.get_correct_serial_port()
    pozyx = PozyxSerial(serial_port)
    use_velocity = True

    # import properties from saved properties file
    config = Configuration.get_properties()
    tags = config.tags
    anchors = config.anchors
    attributes_to_log = config.attributes_to_log
    to_use_file = config.use_file
    filename = config.data_file
    range_anchor_id = config.range_anchor_id
    alpha_pos = config.position_smooth
    alpha_vel = config.velocity_smooth
    smooth_velocity = alpha_vel < 1.00
    share_data_over_lan = config.share_data_over_lan
Example #8
0
    output += ", Gain "
    output += str(uwb_settings.gain_db) + " dB"
    return output


if __name__ == '__main__':
    # ***DEFAULTS*** #
    # set to True if local tag needs to change settings as well.
    set_local = True
    # set to True if needed to save to flash
    save_to_flash = True
    # don't try to remotely change settings, it doesn't work.
    devices = [0x0000]
    # ***END DEFAULTS*** #

    serial_port = Configuration.get_correct_serial_port()
    pozyx = PozyxSerial(serial_port)

    uwb_settings = None

    arguments = sys.argv
    arg_length = len(arguments)

    # no arguments added on, only call was to script
    if arg_length is 1:
        print("Showing old UWB settings for the local device.")
        # shows the previous UWB settings
        c = ChangeUWBSettings(pozyx, uwb_settings, devices, set_local,
                              save_to_flash)
        sys.exit(0)
    # all 5 UWB arguments were passed plus the call to the script
Example #9
0
    def bill(self, session, subscriber, destination_number, context, duration):
        if context == 'LOCAL':
            bill_log.info(
                '==========================================================================='
            )
            bill_log.info('LOCAL Context')
            bleg_connected = session.getVariable('bleg_uuid')
            hangup_cause = session.getVariable('hangup_cause')
            #subscriber = session.getVariable('bleg_destination_number')
            #print session.getVariable('bleg_billsec')

            configuration = Configuration()
            try:
                _charge_local = configuration.check_charge_local_calls()
                if _charge_local == 1:
                    _charge = configuration.get_charge_local_calls()
                    if duration > int(_charge[1]):
                        call_cost = _charge[0]
                    else:
                        call_cost = 0
                else:
                    return
            except:
                bill_log.error('Error reading local calls charge config.')
                return

            # set destination_name and cost for the CDR
            session.setVariable('destination_name', 'Local')
            session.setVariable('cost', str(call_cost))
            bill_log.info('Call duration: %d sec Call cost: %.2f' %
                          (duration, call_cost))

            if call_cost > Decimal('0.00'):
                sub = Subscriber()
                try:
                    previous_balance = sub.get_balance(subscriber)
                    current_balance = previous_balance - call_cost
                    real_balance = 0 if current_balance < 0 else current_balance
                    bill_log.info(
                        'Previous balance: %.2f Current Balance: %.2f' %
                        (previous_balance, real_balance))
                    sub.set_balance(subscriber, real_balance)
                    bill_log.info('Billing %s completed successfully' %
                                  subscriber)
                except SubscriberException as e:
                    bill_log.error('Error during billing the subscriber: %s' %
                                   e)
            else:
                bill_log.info('Call too short to Bill')

        if context == 'OUTBOUND':
            bill_log.info(
                '==========================================================================='
            )
            bill_log.info(
                'OUTBOUND Context Bill subscriber %s destination %s' %
                (subscriber, destination_number))

            sub = Subscriber()
            # get rate
            rate = self.get_rate(destination_number)
            log_dest = rate[1]
            package = sub.get_package(subscriber)
            if package == 1 and rate[1] == "Mexico Cellular-Telcel":
                bill_log.info(
                    'Subscriber has package, removing 5 mins from call duration of %s seconds',
                    duration)
                log_dest = rate[1] + ' (P)'
                duration = duration - 300
                if duration < 0:
                    duration = 0
            if 'charge_outbound_rate_type' in globals(
            ) and charge_outbound_rate_type == 'sec':
                call_cost = Decimal(
                    math.ceil((rate[3] / 60) * duration * 100) / 100).quantize(
                        Decimal('0.01'))
            else:
                call_cost = self.get_call_cost(duration, rate[3])

            try:
                previous_balance = sub.get_balance(subscriber)
                current_balance = previous_balance - call_cost
                if current_balance < 0:
                    # There was not enough balance to cover the rounded up minutes
                    real_balance = 0
                    # Log what we ACTUALLY deducted in the CDR
                    call_cost = previous_balance
                else:
                    real_balance = current_balance
                bill_log.info('Previous balance: %.2f Current Balance: %.2f' %
                              (previous_balance, real_balance))
                sub.set_balance(subscriber, real_balance)
                bill_log.info('Billing %s completed successfully' % subscriber)
            except SubscriberException as e:
                bill_log.error('Error during billing the subscriber: %s' % e)

            # set destination_name and cost for the CDR
            session.setVariable('destination_name', log_dest)
            session.setVariable('cost', str(call_cost))
            bill_log.info('Call duration: %d sec Call cost: %.2f' %
                          (duration, call_cost))

        if context == 'INBOUND':
            bill_log.info(
                '==========================================================================='
            )
            bill_log.info('INBOUND Context')
            bleg_connected = session.getVariable('bleg_uuid')
            hangup_cause = session.getVariable('hangup_cause')
            subscriber = session.getVariable('bleg_destination_number')
            #print session.getVariable('bleg_billsec')
            configuration = Configuration()

            if (bleg_connected != '' and bleg_connected != None
                ) and hangup_cause == 'NORMAL_CLEARING':
                bill_log.info('Call B-leg was connected. Bill subscriber %s' %
                              subscriber)
                try:
                    charge_info = configuration.get_charge_inbound_calls()
                    if charge_info[1] == 'call':
                        bill_log.info('Charge type: per call, Cost: %s' %
                                      charge_info[0])
                        call_cost = charge_info[0]
                        try:
                            sub = Subscriber()
                            previous_balance = sub.get_balance(subscriber)
                            current_balance = previous_balance - call_cost
                            bill_log.info(
                                'Previous balance: %.2f Current Balance: %.2f'
                                % (previous_balance, current_balance))
                            sub.set_balance(subscriber, current_balance)
                            bill_log.info('Billing %s completed successfully' %
                                          subscriber)
                        except SubscriberException as e:
                            bill_log.error(
                                'Error during billing the subscriber: %s' % e)
                    elif charge_info[1] == 'min':
                        bill_log.info(
                            'Charge type rate per min, cost per min: %s' %
                            charge_info[0])
                        # BUG: Cannot get b-leg billsec from FS. Use the billsec of a-leg instead
                        call_cost = self.get_call_cost(duration,
                                                       charge_info[0])
                        bill_log.info('Call duration %s sec Call cost: %s' %
                                      (duration, call_cost))
                        try:
                            sub = Subscriber()
                            previous_balance = sub.get_balance(subscriber)
                            current_balance = previous_balance - call_cost
                            bill_log.info(
                                'Previous balance: %.2f Current Balance: %.2f'
                                % (previous_balance, current_balance))
                            sub.set_balance(subscriber, current_balance)
                            bill_log.info('Billing %s completed successfully' %
                                          subscriber)
                        except SubscriberException as e:
                            bill_log.error(
                                'Error during billing the subscriber: %s' % e)
                except ConfigurationException as e:
                    bill_log.error(e)
            else:
                bill_log.info(
                    'Call B-leg was not connected. Not billing subscriber %s' %
                    subscriber)
Example #10
0
#!/usr/bin/env python
from pyrogram import Client
from modules.configuration import Configuration
from modules.sms import GetSMSCode
from time import sleep

cfg_obj = Configuration()
config = cfg_obj.load()
sms = GetSMSCode(config)


def phone_code_callback(mobile_number):
    sleep(30)
    code = sms.get_code(mobile_number)
    return code


def main():
    mobile_number = sms.get_mobile_number()
    # Get current account balance before signup
    print(sms.account_info)
    try:
        app = Client(session_name=mobile_number,
                     phone_number=mobile_number,
                     phone_code=phone_code_callback,
                     first_name="John",
                     last_name="Doe")

        with app:
            print(app.get_me())
Example #11
0
def upload_file(filename, file_object, current_file_timestamp):
    """
    server file uploader
    """
    base_name = os.path.basename(filename)
    file_attrs_str = str(get_file_info(filename))
    try:
        configuration = Configuration()
        configuration.load()
        api_key = configuration.api_key
        url = configuration.url
        payload = {'api_key': api_key, 'hide_old': 0}
        code, response = post_multipart(url=url, payload=payload,
                                        file_name=filename)

        print response
        event_type_uploading = EventType.query.get(3)
        event_post_results = Event(name='%s post results: %s' % (base_name, str({'code': code, 'response': response})),
                                   event_type=event_type_uploading, file=None, date=None, file_attrs=file_attrs_str,
                                   result_code=code)
        db.session.add(event_post_results)
        db.session.commit()
        if code == 200:
            task_id = (json.loads(response)).get('task_id')
            if task_id:
                ready = False
                t0 = time.time()# time started
                expected_waiting_time = 35
                loop_num = 0
                while not ready:
                    try:
                        r = requests.get(url, params={'task_id': task_id,
                                                      'api_key': api_key,
                                                      }, verify=False)
                        print r.text
                        if r.status_code == 200:
                            if json.loads(r.text).get('ready') is True:
                                # log ready
                                available = json.loads(r.text).get('available')
                                updated = json.loads(r.text).get('updated')
                                file_object.updated_at = datetime.utcnow()
                                file_object.timestamp = current_file_timestamp
                                db.session.add(file_object)
                                db.session.commit()

                                event_results = Event(name='%s upload successful!!! results: available: %d, updated %d' %
                                                           (base_name, available, updated),
                                                      event_type=event_type_uploading,
                                                      file=file_object,
                                                      date=None,
                                                      file_attrs=file_attrs_str,
                                                      result_code=r.status_code)
                                db.session.add(event_results)
                                db.session.commit()
                                break
                        else:
                            # reason?
                            reason = 'unknown'
                            event_results = Event(name='%s results: file not uploaded, reason %s' % (base_name, reason),
                                                      event_type=event_type_uploading,
                                                      file=None,
                                                      date = None,
                                                      file_attrs=file_attrs_str,
                                                      result_code= r.status_code)
                            db.session.add(event_results)
                            db.session.commit()
                            break

                    except Exception as e:
                        event_results = Event(name='%s: system error %s' % (base_name, e.args[0]),
                                                      event_type=event_type_uploading,
                                                      file=None,
                                                      date = None,
                                                      file_attrs=file_attrs_str,
                                                      result_code= None)
                        db.session.add(event_results)
                        db.session.commit()
                        break
                    time.sleep(expected_waiting_time)
                    current, total = 0, 0
                    try:
                        current = json.loads(r.text).get('state').get('current')
                        total = json.loads(r.text).get('state').get('total')
                    except:
                        pass
                    t = math.floor(time.time() - t0)
                    if total != 0 and current != 0 and loop_num != 0 :
                            expected_waiting_time = math.floor((total - current) * t / current)
                    loop_num += 1
    except ValueError as ve:
        event_type_error = EventType.query.get(2)
        event_configuration_error = Event(name='%d config error %s' % (base_name, ve.args[0]),
                                    event_type=event_type_error,file=None, date=None,
                                    file_attrs=file_attrs_str, result_code=None)
        db.session.add(event_configuration_error)
        db.session.commit()