Beispiel #1
0
 def find_chain(features, collection_edges, alist=[], id=None):
     _ids = find_next_by_node(features, collection_edges, [], id)
     for _id in _ids:
         obj = _.find(features, {'_id':_id})
         if obj :
             from_index = _.find_index(features, {'_id':id})
             to_index = _.find_index(features, {'_id':_id})
             if obj.has_key('properties') and obj['properties'].has_key('devices'):
                 alist.append({
                     'lnbr_idx': len(alist) + 1,
                     'from_id': add_mongo_id(id),
                     'to_id': obj['_id'],
                     # 'from_idx': from_index,
                     # 'to_idx': to_index,
                 })
             alist = find_chain(features, collection_edges, alist, obj['_id'])
     return alist
def ssh_key_is_present(client, module, id):
    server_id = module.params.get('server_id')
    user_description = client.describe_user(
        ServerId=server_id, UserName=module.params.get('user_name'))
    if len(user_description["User"]["SshPublicKeys"]) > 0:
        return py_.find_index(user_description["User"]["SshPublicKeys"],
                              {"SshPublicKeyId": id}) != -1
    else:
        return False
Beispiel #3
0
 def find_chain(features, collection_edges, alist=[], id=None):
     _ids = find_next_by_node(features, collection_edges, [], id)
     for _id in _ids:
         obj = _.find(features, {'_id': _id})
         if obj:
             from_index = _.find_index(features, {'_id': id})
             to_index = _.find_index(features, {'_id': _id})
             if obj.has_key('properties') and obj['properties'].has_key(
                     'devices'):
                 alist.append({
                     'lnbr_idx': len(alist) + 1,
                     'from_id': add_mongo_id(id),
                     'to_id': obj['_id'],
                     # 'from_idx': from_index,
                     # 'to_idx': to_index,
                 })
             alist = find_chain(features, collection_edges, alist,
                                obj['_id'])
     return alist
Beispiel #4
0
def items_common(a: SnapList, b: SnapList) -> Tuple[SnapList, SnapList]:
    """
    Return new [a, b] for SnapItems that are present in a AND b.
    The items are identified using the first element of each row and are returned
    ordered as in a.
    """

    n_a = []
    n_b = []
    for item_id, item_data in a:
        idx_b = py_.find_index(b, lambda x: x[0] == item_id)
        if idx_b > -1:
            n_a.append((item_id, item_data))
            n_b.append((item_id, b[idx_b][1]))

    return n_a, n_b
Beispiel #5
0
    def write_to_ru_files(self, ru_file, ru_file_parsed, en_file_parsed):
        for idx, en_message in enumerate(en_file_parsed.body):
            if isinstance(en_message, ast.ResourceComment) or isinstance(
                    en_message, ast.GroupComment) or isinstance(
                        en_message, ast.Comment):
                continue

            ru_message_analog_idx = py_.find_index(
                ru_file_parsed.body,
                lambda ru_message: self.find_duplicate_message_id_name(
                    ru_message, en_message))
            have_changes = False

            # Attributes
            if getattr(en_message, 'attributes',
                       None) and ru_message_analog_idx != -1:
                if not ru_file_parsed.body[ru_message_analog_idx].attributes:
                    ru_file_parsed.body[
                        ru_message_analog_idx].attributes = en_message.attributes
                    have_changes = True
                else:
                    for en_attr in en_message.attributes:
                        ru_attr_analog = py_.find(
                            ru_file_parsed.body[ru_message_analog_idx].
                            attributes,
                            lambda ru_attr: ru_attr.id.name == en_attr.id.name)
                        if not ru_attr_analog:
                            ru_file_parsed.body[
                                ru_message_analog_idx].attributes.append(
                                    en_attr)
                            have_changes = True

            # New elements
            if ru_message_analog_idx == -1:
                ru_file_body = ru_file_parsed.body
                if (len(ru_file_body) >= idx + 1):
                    ru_file_parsed = self.append_message(
                        ru_file_parsed, en_message, idx)
                else:
                    ru_file_parsed = self.push_message(ru_file_parsed,
                                                       en_message)
                have_changes = True

            if have_changes:
                serialized = serializer.serialize(ru_file_parsed)
                self.save_and_log_file(ru_file, serialized, en_message)
Beispiel #6
0
 def create_xls(filepath, line_py, data):
     if os.path.exists(filepath):
         print('File exist, removing...')
         os.remove(filepath)
     wb = xlwt.Workbook()
     ws = wb.add_sheet('Sheet1')
     alist = _.filter_(data, lambda x:x['line_py'] == line_py)
     ftu_count = 0
     if line_py == 'jfyk':
         ftu_count = 8
     if line_py == 'pzz':
         ftu_count = 10
     for i in range(1, ftu_count+1):
         if _.find_index(alist, {'switch_alias':i}) > -1:
             ws.write(0, i - 1, 1)
         else:
             ws.write(0, i - 1, 0)
     wb.save(filepath)
Beispiel #7
0
def add_user(client, user_name, user_home_directory, user_home_directory_type,
             user_home_directory_mappings, user_policy, user_role,
             user_ssh_public_key_body, user_tags, name):
    result = {}
    sftp_server = find_sftp_server(client, name)
    exists = False
    if sftp_server is not None:
        sftp_server_id = sftp_server['Server']['ServerId']
        users = client.list_users(ServerId=sftp_server_id)

        if users is not None:
            exists = (py_.find_index(users['Users'], {"UserName": user_name})
                      != -1)

        add_user_kwargs = dict(Role=user_role,
                               ServerId=sftp_server_id,
                               UserName=user_name)

        if user_home_directory is not None:
            add_user_kwargs['HomeDirectory'] = user_home_directory
        if user_home_directory_type is not None:
            add_user_kwargs['HomeDirectoryType'] = user_home_directory_type
        if user_home_directory_mappings is not None:
            add_user_kwargs[
                'HomeDirectoryMappings'] = user_home_directory_mappings
        if user_policy is not None:
            add_user_kwargs['Policy'] = user_policy
        if user_ssh_public_key_body is not None:
            add_user_kwargs['SshPublicKeyBody'] = user_ssh_public_key_body
        if user_tags is not None:
            add_user_kwargs['Tags'] = user_tags

        if not exists:
            result = client.create_user(**add_user_kwargs)
        else:
            result = client.update_user(**add_user_kwargs)

    return result
Beispiel #8
0
        def _get_table_hashes(table_config):
            if "groupby" in table_config:
                group_fields = ", ".join(table_config["groupby"])
                select_fields = f"{group_fields}, md5({table_config['table']}::text) as hash"
                stmt = f"SELECT {select_fields} FROM {table_config['table']} ORDER BY {group_fields}"

                grouped_data = []
                for res in db.query(stmt):
                    group_values = [
                        res[field] for field in table_config["groupby"]
                    ]

                    group_values_idx = py_.find_index(
                        grouped_data, lambda x: x[0] == group_values)
                    if group_values_idx > -1:
                        grouped_data[group_values_idx][1].append(res["hash"])
                    else:
                        grouped_data.append([group_values, [res["hash"]]])

                return grouped_data
            else:
                stmt = f"SELECT md5({table_config['table']}::text) as hash FROM {table_config['table']}"
                return [r["hash"] for r in db.query(stmt)]
Beispiel #9
0
 def filt(x):
     return _.find_index(ftu_fault, {'sim':x['sim']}) > -1
Beispiel #10
0
def pi_handle_ws_recv_callback(aConfig, data):
    global gSensorControl
    def cmd_camera_stream_start_stop(aConfig, start_stop):
        if start_stop.lower() == 'start':
            start_stop = 'Start'
        if start_stop.lower() == 'stop':
            start_stop = 'Stop'
        app = aConfig['gConfig']['wsgi']['application']

        if 'uv4l' in aConfig['gConfig']['applications'][app] and 'janus' in aConfig['gConfig']['applications'][app]:
            uv4l = aConfig['gConfig']['applications'][app]['uv4l']
            janus = aConfig['gConfig']['applications'][app]['janus']
            url = ''
            if start_stop == 'Start':
                url = '%s://%s:%s/janus?gateway_url=%s://%s:%s&gateway_root=%s&room=%s&room_pin=%s&username=%s&reconnect=%s&action=%s' % \
                      (uv4l['protocol'],
                       uv4l['host'],
                       uv4l['port'],
                       janus['protocol'],
                       janus['host'],
                       janus['port'],
                       janus['base_path'],
                       janus['room'],
                       janus['room_pin'],
                       janus['username'],
                       janus['reconnect'],
                       start_stop)
            elif start_stop == 'Stop':
                url = '%s://%s:%s/janus?action=%s' % \
                      (uv4l['protocol'],
                       uv4l['host'],
                       uv4l['port'],
                       start_stop)
            if url:
                print(url)
                check_output(['curl', '-s', url, '>/dev/null'])

    try:
        obj = json.loads(data)
        if isinstance(obj, dict) and 'device_serial_no' in obj and 'op' in obj:
            if gSensorControl and 'device_serial_no' in gSensorControl and gSensorControl['device_serial_no'] == obj['device_serial_no']:
                if obj['op'] == OPERATOR['OP_ENABLE_CAMERA']:
                    cmd_camera_stream_start_stop(aConfig, 'start')
                elif obj['op'] == OPERATOR['OP_DISABLE_CAMERA']:
                    cmd_camera_stream_start_stop(aConfig, 'stop')

                if 'serial_no' in obj and len(obj['serial_no']):
                    sensor = _.find(gSensorControl['sensors'], {'serial_no':obj['serial_no']})
                    index = _.find_index(gSensorControl['sensors'], {'serial_no':obj['serial_no']})
                    if sensor:
                        if obj['op'] == OPERATOR['OP_DISABLE_SENSOR']:
                            gSensorControl['sensors'][index]['enable'] = False
                        elif obj['op'] == OPERATOR['OP_ENABLE_SENSOR']:
                            gSensorControl['sensors'][index]['enable'] = True
                        if 'interval' in obj and (isinstance(obj['interval'], int) or isinstance(obj['interval'], float)):
                            gSensorControl['sensors'][index]['interval'] = obj['interval']
                else:
                    for i in range(len(gSensorControl['sensors'])):
                        if obj['op'] == 'OP_DISABLE_SENSOR':
                            gSensorControl['sensors'][i]['enable'] = False
                        elif obj['op'] == 'OP_ENABLE_SENSOR':
                            gSensorControl['sensors'][i]['enable'] = True
                        if 'interval' in obj and (isinstance(obj['interval'], int) or isinstance(obj['interval'], float)):
                            gSensorControl['sensors'][i]['interval'] = obj['interval']


            else:
                print('unknown device_serial_no:[%s]' % obj['device_serial_no'])

    except Exception as e:
        print (e)
        raise
Beispiel #11
0
def pi_internal_sensor_queue_send_loop(aConfig):
    global gQueueSensor, gWebSocketConnection, gSensorControl, gSensorData

    def computeHeight(pressure):
        return 44330.8 * (1 - pow(pressure / 1013.25, 0.190263))

    def get_sensor_data(aConfig, key, device_serial_no, sensor_type, serial_no):
        global gSensorData
        ret = None
        if key == 'DOF10':
            if key in gSensorData and len(list(gSensorData[key].keys())):
                # print(gSensorData['DOF10'])
                ret = {
                    'type': sensor_type,
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'timestamp': datetime.datetime.now(),
                    'value': {
                        'temp': float('{0:.1f}'.format(gSensorData['DOF10']['temperature'])),
                        'ypr': {
                            'yaw': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][2])),
                            'pitch': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][1])),
                            'roll': float('{0:.5f}'.format(gSensorData['DOF10']['fusionPose'][0])),
                        },
                        'quat':{
                            'w':float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][0])),
                            'x': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][1])),
                            'y': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][2])),
                            'z': float('{0:.5f}'.format(gSensorData['DOF10']['fusionQPose'][3])),
                        },
                        'height': float('{0:.1f}'.format(computeHeight(gSensorData['DOF10']['pressure']))),
                        'pressure': float('{0:.1f}'.format(gSensorData['DOF10']['pressure'])),
                    },
                    'op': OPERATOR['OP_TRANSFER'],
                }
        elif key.lower() == 'battery':
            if key in gSensorData and len(list(gSensorData[key].keys())):
                ret = {
                    'type': sensor_type,
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'timestamp': datetime.datetime.now(),
                    'value': {
                        'bus_voltage': float('{0:.2f}'.format(gSensorData['battery']['bus_voltage'])),
                        'current': float('{0:.2f}'.format(gSensorData['battery']['current'])),
                        'power': float('{0:.2f}'.format(gSensorData['battery']['power'])),
                    },
                    'op': OPERATOR['OP_TRANSFER'],
                }
        return ret

    # def get_sensor_device(aConfig, key):
    #     ret = None
    #     if key == 'DOF10':
    #         try:
    #             import RTIMU
    #         except:
    #             print('RTIMU import error')
    #             return ret
    #         SETTINGS_FILE = "RTIMU_CONFIG"
    #         print("Using settings file [%s.ini]" % SETTINGS_FILE)
    #         if not os.path.exists(SETTINGS_FILE + ".ini"):
    #             print("Settings file does not exist, will be created")
    #         setting = RTIMU.Settings(SETTINGS_FILE)
    #         imu = RTIMU.RTIMU(setting)
    #         pressure = RTIMU.RTPressure(setting)
    #
    #         print("IMU Name: " + imu.IMUName())
    #         print("Pressure Name: " + pressure.pressureName())
    #         if (not imu.IMUInit()):
    #             print("IMU Init Failed")
    #             return None
    #         else:
    #             print("IMU Init Succeeded");
    #
    #             imu.setSlerpPower(0.02)
    #             imu.setGyroEnable(True)
    #             imu.setAccelEnable(True)
    #             imu.setCompassEnable(True)
    #
    #         if (not pressure.pressureInit()):
    #             print("Pressure sensor Init Failed")
    #             return None
    #         else:
    #             print("Pressure sensor Init Succeeded")
    #             ret = {
    #                 'imu': imu,
    #                 'pressure': pressure,
    #             }
    #     return ret

    def register(aConfig, device_serial_no, sensor_type, serial_no, wsurl):
        global gSensorControl, gWebSocketConnection
        try:
            if gWebSocketConnection is None:
                # print(wsurl)
                gWebSocketConnection = pi_create_websocket(wsurl)
            if gWebSocketConnection and not gWebSocketConnection.connected:
                gWebSocketConnection.connect(wsurl, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
            if gWebSocketConnection and gWebSocketConnection.connected:
                item = {
                    'device_serial_no': device_serial_no,
                    'serial_no': serial_no,
                    'op': OPERATOR['OP_REGISTER'],
                    'type': sensor_type,
                    'enable':True,
                    'is_internal': True,
                    'interval': 1.0,
                }
                gWebSocketConnection.send(json.dumps(item, ensure_ascii=True))

        except Exception as e:
            print(e)
            print('register failed')

    def rtimulib_loop(serial_no):
        global gSensorControl, gSensorData
        try:
            import RTIMU
        except:
            print('RTIMU import error')
            return
        SETTINGS_FILE = "RTIMU_CONFIG"
        print("Using settings file [%s.ini]" % SETTINGS_FILE)
        if not os.path.exists(SETTINGS_FILE + ".ini"):
            print("Settings file does not exist, will be created")
        setting = RTIMU.Settings(SETTINGS_FILE)
        imu = RTIMU.RTIMU(setting)
        pressure = RTIMU.RTPressure(setting)

        print("IMU Name: " + imu.IMUName())
        print("Pressure Name: " + pressure.pressureName())
        if (not imu.IMUInit()):
            print("IMU Init Failed")
            return
        else:
            print("IMU Init Succeeded");

            imu.setSlerpPower(0.02)
            imu.setGyroEnable(True)
            imu.setAccelEnable(True)
            imu.setCompassEnable(True)

        if (not pressure.pressureInit()):
            print("Pressure sensor Init Failed")
            return None

        interval = float(imu.IMUGetPollInterval())
        if not 'DOF10' in gSensorData:
            gSensorData['DOF10'] = {}
        while True:
            sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
            if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                if imu.IMURead():
                    gSensorData['DOF10'] = imu.getIMUData()
                    (gSensorData['DOF10']['pressureValid'], gSensorData['DOF10']['pressure'], gSensorData['DOF10']['temperatureValid'],gSensorData['DOF10']['temperature']) = pressure.pressureRead()

            else:
                interval = 1000.0
            gevent.sleep(interval / 1000.0)

    def pigpio_loop(key, i2c_addr, serial_no):
        global gSensorControl, gSensorData, aConfig
        try:
            import pigpio
        except:
            print('pigpio import error')
            return
        if key == 'battery':
            from INA226 import INA226Device
            ina226 = None
            try:
                ina226 = INA226Device(address=i2c_addr, initdata={'max_current_excepted':12})
            except Exception as e:
                print (e)
                return
            if ina226:
                if not 'battery' in gSensorData:
                    gSensorData['battery'] = {}
                interval = 1000.0
                while True:
                    sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                    if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                        gSensorData['battery']['bus_voltage'] = ina226.read_bus_voltage()
                        gSensorData['battery']['current'] = ina226.read_current_by_shuntvolt()
                        gSensorData['battery']['power'] = ina226.read_power()
                    else:
                        interval = 1000.0
                    gevent.sleep(interval / 1000.0)

    def loop(aConfig, device_serial_no, key, sensor_type, serial_no, wsurl):
        global gSensorControl, gWebSocketConnection
        register(aConfig, device_serial_no, sensor_type, serial_no, wsurl)
        sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
        if sensor:
            while True:
                sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                interval = sensor['interval']
                if sensor and (sensor['enable'] is True or sensor['enable'].lower() == 'true'):
                    try:
                        if gWebSocketConnection is None:
                            gWebSocketConnection = pi_create_websocket(wsurl)
                        if gWebSocketConnection and not gWebSocketConnection.connected:
                            gWebSocketConnection.connect(wsurl, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
                        item = get_sensor_data(aConfig, key, device_serial_no, sensor_type,  serial_no)
                        if gWebSocketConnection and item:
                            gWebSocketConnection.send(json.dumps(item,  ensure_ascii=True))
                    except Empty:
                        pass
                    except Exception as e:
                        # print('loop error')
                        # print(e)
                        pass
                    finally:
                        try:
                            gWebSocketConnection.send('')
                        except:
                            gWebSocketConnection.close()
                gevent.sleep(interval)
        else:
            print('cannot get sensor:%s' % serial_no)

    app = aConfig['gConfig']['wsgi']['application']
    if 'queue' in aConfig['gConfig']['applications'][app] \
            and 'internal_sensor' in aConfig['gConfig']['applications'][app]['queue'] \
            and 'websocket' in aConfig['gConfig']['applications'][app]:
        internal_sensor = aConfig['gConfig']['applications'][app]['queue']['internal_sensor']
        device_serial_no = None

        if 'device_info' in aConfig['gConfig']['applications'][app] \
                and 'serial_no' in aConfig['gConfig']['applications'][app]['device_info'] \
                and len(aConfig['gConfig']['applications'][app]['device_info']['serial_no']):
            device_serial_no = aConfig['gConfig']['applications'][app]['device_info']['serial_no']

        websocketcfg = aConfig['gConfig']['applications'][app]['websocket']
        wsurl = '%s://%s:%s%s' % (websocketcfg['remote_protocol'], websocketcfg['remote_host'], websocketcfg['remote_port'],
                                  websocketcfg['remote_base'])
        for key in internal_sensor.keys():
            serial_no = None
            chip = None
            sensor_type = None
            i2c_addr = None
            if 'enable' in internal_sensor[key] and internal_sensor[key]['enable'].lower() == 'true':
                interval = 1.0
                if 'i2c_addr' in internal_sensor[key]:
                    i2c_addr = int(internal_sensor[key]['i2c_addr'], 16)
                if 'queue_consume_interval' in internal_sensor[key]:
                    interval = float(internal_sensor[key]['queue_consume_interval'])
                if 'type' in internal_sensor[key]:
                    sensor_type = internal_sensor[key]['type']
                    if isinstance(sensor_type, str):
                        sensor_type = int(sensor_type)
                    elif isinstance(sensor_type, list):
                        sensor_type = _.map_(sensor_type, lambda x:int(x))
                if 'serial_no' in internal_sensor[key]:
                    serial_no = internal_sensor[key]['serial_no']
                if gSensorControl is None:
                    gSensorControl = {}
                if device_serial_no:
                    gSensorControl['device_serial_no'] = device_serial_no
                if not 'sensors' in gSensorControl:
                    gSensorControl['sensors'] = []
                if serial_no and sensor_type:
                    sensor = _.find(gSensorControl['sensors'], {'serial_no': serial_no})
                    sensor_index = _.find_index(gSensorControl['sensors'], {'serial_no': serial_no})
                    if sensor:
                        sensor['enable'] = True
                        sensor['is_internal'] = True
                        sensor['interval'] = interval
                        sensor['type'] = sensor_type
                        gSensorControl['sensors'][sensor_index] = sensor
                    else:
                        sensor = {}
                        sensor['serial_no'] = serial_no
                        sensor['enable'] = True
                        sensor['is_internal'] = True
                        sensor['interval'] = interval
                        sensor['type'] = sensor_type
                        gSensorControl['sensors'].append(sensor)
                    # device = get_sensor_device(aConfig, key)
                    if key == 'DOF10':
                        gevent.spawn(rtimulib_loop, serial_no)
                        gevent.spawn(loop, aConfig, device_serial_no, key, sensor_type, serial_no, wsurl)
                    elif key in ['battery']:
                        gevent.spawn(pigpio_loop, key, i2c_addr, serial_no)
                        gevent.spawn(loop, aConfig, device_serial_no, key, sensor_type, serial_no, wsurl)
Beispiel #12
0
def pi_sensor_queue_send_loop(aConfig):
    global gQueueSensor, gWebSocketConnection, gSensorControl
    app = aConfig['gConfig']['wsgi']['application']
    if 'queue' in aConfig['gConfig']['applications'][app] \
            and 'sensor' in aConfig['gConfig']['applications'][app]['queue'] \
            and 'websocket' in aConfig['gConfig']['applications'][app]:
        sensor = aConfig['gConfig']['applications'][app]['queue']['sensor']
        interval = float(sensor['queue_consume_interval'])
        websocketcfg = aConfig['gConfig']['applications'][app]['websocket']
        wsurl = '%s://%s:%s%s' % (websocketcfg['remote_protocol'], websocketcfg['remote_host'], websocketcfg['remote_port'], websocketcfg['remote_base'])

        device_serial_no = None
        if 'device_info' in aConfig['gConfig']['applications'][app] \
                and 'serial_no' in aConfig['gConfig']['applications'][app]['device_info'] \
                and len(aConfig['gConfig']['applications'][app]['device_info']['serial_no']):
            device_serial_no = aConfig['gConfig']['applications'][app]['device_info']['serial_no']
        while True:
            try:
                if gWebSocketConnection is None:
                    gWebSocketConnection = pi_create_websocket(wsurl)

                if gWebSocketConnection and not gWebSocketConnection.connected:
                    gWebSocketConnection.connect(wsurl, sslopt={"cert_reqs": ssl.CERT_NONE, "check_hostname": False})
                if gQueueSensor and gWebSocketConnection:
                    item = {}
                    if not gQueueSensor.empty():
                        item = gQueueSensor.get()
                    if 'serial_no' in item:
                        if gSensorControl is None:
                            gSensorControl = {}
                        if device_serial_no and not 'device_serial_no' in gSensorControl:
                            gSensorControl['device_serial_no'] = device_serial_no
                            gSensorControl['sensors'] = []

                        sensor = _.find(gSensorControl['sensors'], {'serial_no': item['serial_no']})
                        sensor_index = _.find_index(gSensorControl['sensors'], {'serial_no': item['serial_no']})
                        if sensor is None:
                            sensor = {}
                            sensor['serial_no'] = item['serial_no']
                            sensor['type'] = item['type']
                            sensor['enable'] = True
                            sensor['is_internal'] = False
                            sensor['interval'] = 1.0
                            gSensorControl['sensors'].append(sensor)
                        else:
                            if 'enable' in item:
                                sensor['enable'] = item['enable']
                            if 'is_internal' in item:
                                sensor['is_internal'] = item['is_internal']
                            if 'interval' in item:
                                sensor['interval'] = item['interval']
                            if 'type' in item:
                                sensor['type'] = item['type']
                            gSensorControl['sensors'][sensor_index] = sensor

                        if sensor['enable'] is True or sensor['enable'].lower() == 'true':
                            item['device_serial_no'] = device_serial_no
                            gWebSocketConnection.send(json.dumps(item,  ensure_ascii=True))
            except Empty:
                pass
            except Exception as e:
                pass
            finally:
                try:
                    gWebSocketConnection.send('')
                except:
                    gWebSocketConnection.close()
            gevent.sleep(interval)
start_index = 0
end_index = 0
result = ""

for matchNum, match in enumerate(matches):
    if matchNum == 8:
        matchNum = matchNum + 1

        result = match.group() + "}"
        user = json.loads(result)

        x_data = user['x']
        y_data = user['y']

        start_index = py_.find_index(x_data, lambda x: r.start in x)
        end_index = py_.find_index(x_data, lambda x: r.end in x)

        measurments = y_data[start_index:end_index]
        avg_a = np.average(measurments)

        start_date = x_data[start_index]
        end_date = x_data[end_index]
        time_usage = (datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S.%f") -
                      datetime.strptime(
                          start_date, "%Y-%m-%d %H:%M:%S.%f")).total_seconds()

        power_usage = round(((avg_a * VOLTAGE) / 60 / 60) * time_usage, 6)
        print("From: " + start_date + "\nTo: " + end_date + "\n((" +
              str(avg_a) + "mA * " + str(VOLTAGE) + "V / 60 / 60 ) * " +
              str(time_usage) + "S) = " + str(power_usage) + "mWh")
Beispiel #14
0
            data = myfile.read()

        matches = re.finditer(regex, data)

        title = ""

        for matchNum, match in enumerate(matches):
            matchNum = matchNum + 1

            title = match.group()

            titleList = title.split(' ')
            if len(titleList) < 15:
                continue

            flag_str = titleList[py_.find_index(titleList, lambda x: "x" in x)]

            flag = 0
            if "2" in flag_str:
                flag = 1

            location = titleList[1]
            network = titleList[2]
            dbm = titleList[5]
            if "dBm" not in dbm:
                dbm = "0dbm"

            sec = py_.find_index(titleList, lambda x: "SEC" in x)
            delay = titleList[sec - 1]
            iterations = titleList[sec + 1]
Beispiel #15
0
    def handle_geo_within(session, aConfig, querydict, user_id):
        statuscode, mimetype, body = 200, 'text/json', '{}'
        app = aConfig['gConfig']['wsgi']['application']
        db, collection = get_collection(aConfig, app, 'main', 'collection_features')
        limit = 0
        if 'limit' in querydict and isinstance(querydict['limit'], int):
            limit = querydict['limit']
        if 'geometry' in querydict:
            geojsonobj = querydict['geometry']
            if isinstance(geojsonobj, str) :
                try:
                    geojsonobj = json.loads(geojsonobj)
                except:
                    geojsonobj = {}
            if 'type'in geojsonobj:
                cond = {'geometry2d':{'$geoWithin':{'$geometry':geojsonobj}}}
                if 'webgis_type' in querydict:
                    if isinstance(querydict['webgis_type'], str) :
                        cond['properties.webgis_type'] = querydict['webgis_type']
                    if isinstance(querydict['webgis_type'], list):
                        cond['properties.webgis_type'] = {'$in': querydict['webgis_type']}
                arr = list(collection.find(cond).limit(limit))
                body = json.dumps(remove_mongo_id(arr), ensure_ascii=True, indent=4)
            else:
                body = json.dumps({'result': 'geometry_geojson_required'}, ensure_ascii=True, indent=4)
        else:
            body = json.dumps({'result': 'geometry_required'}, ensure_ascii=True, indent=4)
        return statuscode, mimetype, body


        statuscode, mimetype, body = 200, 'text/json', '{}'
        if check_permission(user_id, 'enable_sensor'):
            device_id = None
            db, collection = get_collection(aConfig, app, 'main', 'collection_device')

            if 'tower_id' in querydict:
                device_id = get_device_from_tower(session, aConfig, querydict['tower_id'])
            if 'device_id' in querydict:
                device_id = querydict['device_id']

            #add for db
            device = None
            if device_id:
                cond = {'_id': device_id}
                device = collection.find_one(add_mongo_id(cond))
                if 'sensor_id' in querydict and len(querydict['sensor_id']):
                    sensor_id = querydict['sensor_id']
                    gevent.spawn(savedb, collection, querydict, device, device_id, sensor_id, enable)
                else:
                    gevent.spawn(savedb, collection, querydict, device, device_id, None, enable)

            #add for gSensorControlList
            device = None
            if device_id:
                device = _.find(gSensorControlList, {'_id': device_id})
                device_index = _.find_index(gSensorControlList, {'_id': device_id})
                if device and 'sensors' in device:
                    pass
                else:
                    device = {}
                    device['_id'] = device_id
                    device['sensors'] = []

                if 'sensor_id' in querydict and len(querydict['sensor_id']):
                    sensor_id = querydict['sensor_id']
                    sensor = _.find(device['sensors'], {'_id': sensor_id})
                    if sensor:
                        index = _.find_index(device['sensors'], {'_id': sensor_id})
                        sensor['enable'] = enable
                        if 'interval' in querydict and (isinstance(querydict['interval'], int) or isinstance(querydict['interval'], float)):
                            sensor['interval'] = querydict['interval']
                        device['sensors'][index] = sensor
                    else:
                        sensor = {}
                        sensor['_id'] = sensor_id
                        sensor['enable'] = enable
                        if 'interval' in querydict and (isinstance(querydict['interval'], int) or isinstance(querydict['interval'], float)):
                            sensor['interval'] = querydict['interval']
                        device['sensors'].append(sensor)
                else:
                    for i in range(len(device['sensors'])):
                        device['sensors'][i]['enable'] = enable
                        if 'interval' in querydict and (isinstance(querydict['interval'], int) or isinstance(querydict['interval'], float)):
                            device['sensors'][i]['interval'] = querydict['interval']
                if device_index < 0:
                    gSensorControlList.append(device)
                else:
                    gSensorControlList[device_index] = device

            else:
                body = json.dumps({'result': 'cannot_find_device_id'}, ensure_ascii=True, indent=4)

        else:
            body = json.dumps({'result':'permission_deny'}, ensure_ascii=True, indent=4)
        return statuscode, mimetype, body