Пример #1
0
def run_all():
    process_manager = app.config['PROCESS_MANAGER']
    device_manager = app.config['DEVICE_MANAGER']
    body = request.json

    devices = Device.from_json_request(body, many=True)
    results = []
    for device in devices:
        address = device.address
        device = _run(address, device, device_manager, process_manager)
        results.append(device)
    # save location mapping information
    location_mapping_df = Device.to_location_mapping_csv(*devices, pid=app.config['SELECTED_SUBJECT'])
    if app.config['SELECTED_SUBJECT'] is None:
        logging_folder = False
    else:
        logging_folder = os.path.abspath(os.path.join('data-logging', 'DerivedCrossParticipants'))
    os.makedirs(logging_folder, exist_ok=True)
    logging.info('Create logging folder: ' + logging_folder)
    output_file = os.path.join(logging_folder,'location_mapping.csv')
    if os.path.exists(output_file):
        location_mapping_df.to_csv(output_file, header=False, index=False, mode='a')
    else:
        location_mapping_df.to_csv(output_file, header=True, index=False)
    logging.info('Saved location mapping information')
    response = Device.to_json_responses(*results, time.time())
    return jsonify(response), 200
Пример #2
0
    def post(self):
        jdatas = json.loads(self.request.body)
        #device_mac = self.get_argument('mac', '')
        device_mac = jdatas['mac']

        dev = Device()
        device_id = dev.get_device_by_mac(device_mac)
        #position_infos = self.get_argument('positions', [])
        position_infos = jdatas['positions']

        for pos_info in position_infos:
            position = pos_info['position']
            object_name = pos_info['object_name']
            duration = pos_info['duration']
            pos = Position()
            pos.device_id = device_id
            pos.position = position
            pos.object_name = object_name
            pos.duration = duration
            pos_id = pos.create()
            print pos_id
            if not pos_id:
                self.write('fail')
                return
        self.write('ok')
Пример #3
0
 def update(self):
     Device.reset()
     Device.equipdb_devices = self.equipDB.getAllDevices()
     for device in Device.equipdb_devices:
         query =     "SELECT devices.serialnb, devices.location, ipinfo.ipaddress "+\
                     "FROM lhcb_lg_devices devices "+\
                     "LEFT JOIN lhcb_ipinfo ipinfo ON lower(devices.devicename) = ipinfo.ipname "+\
                     "WHERE lower(devices.devicename) = '"+lower(device.IPname)+"'"
         result = self.confDB.executeSelectQuery(query)
         if len(result) == 0:
             if device.CMACadd is not None and device.CMACadd is not None:
                 """new device with dhcp-data"""
                 Device.new_devices_with_dhcp.append(device)
                 Device.new_devices.append(device)
             else:
                 """new device without dhcp-data"""
                 Device.new_devices_no_dhcp.append(device)
                 Device.new_devices.append(device)
         else:
             """device found, check if data has changed"""
             for data in result:
                 if data[0] != device.sn or data[1] != device.loc or data[
                         2] != device.CIPadd:
                     """device data has changed"""
                     Device.changed_devices.append(device)
                 else:
                     """device is up to date"""
                     Device.up_to_date_devices.append(device)
     Device.printInfo()
Пример #4
0
    def post(self):
        jdatas = json.loads(self.request.body)
        for jdata in jdatas:

            device_mac = jdata['mac']
            data_content = jdata['data_content']
            #insert the new data to redis
            r=redis.Redis()
            r.set("col_datas_%s"%(device_mac), data_content)
            #get the last table in redis and if there is not a record in redis and get the newest record in the table map
            index = r.get("last_data_table_index")
            if not index:
                index = Data_Table_Map.get_last_table_index()
            print "last index:", index
            dtm = Data_Table_Map.find_first("where `index`=?", int(index))
            #print "add last index table!:----------",dtm.index
            if dtm == None:
                Data_Table_Map.add_table(index)
            
            #parse the data
            #insert into the table
            #if the line of table more than 20w records then create a new table and update table map in the database
            date = data_content['date']
            content = data_content['content']
            dev = Device()
            dev = dev.get_device_by_mac(device_mac)
            DataParser.get_instance().parse_dev(index, dev.id, dev.dev_type,  content)
        self.write('ok')
Пример #5
0
def img_upload(device_mac, device_pos,created_at, meta):
    if device_mac == "":
        return False

    if device_pos == "":
        return False
    dev = Device()
    pos = Position()
    #print "upload_img",device_mac,device_pos

    device_id = dev.get_device_by_mac(device_mac)
    position_id = pos.get_position_id(device_id, device_pos)
    print "upload",device_id,position_id
    upload_path = os.path.join(getPWDDir(), CAPTURED_DIR)
    filename = meta['filename']
    filename = os.path.basename(filename)
    print filename,'----',upload_path

    filepath = os.path.join(upload_path, filename)
    with open(filepath, 'wb') as up:
        up.write(meta['body'])

    img = Image()
    img.path = filename
    img.position_id = position_id
    img.created_at = created_at
    img_id = img.create()
    print img_id
    if not img_id:
        return False
    return True
Пример #6
0
    def post(self):
        jdatas = json.loads(self.request.body)
        device_mac = jdatas['mac']
        #device_mac = self.get_argument('mac','')
        dev = Device()
        self.device_id = dev.get_device_by_mac(device_mac)
        if self.device_id == None:
            self.write("fail")
            return

        #self.observed = self.get_argument('observed',False)
        #user_name = self.get_argument('user_name','')
        #user_password = self.get_argument('user_password','')

        self.observed = jdatas['observed']
        print "observed", self.observed
        user_name = jdatas['user_name']
        user_password = jdatas['user_password']

        res = task.user_login(user_name, user_password)
        if self.on_login_success(res):
            self.write("ok")
            return

        self.write('fail')
Пример #7
0
def get_osigs_for_event(event_key_name):
    logging.info('getting osig for event %s' % event_key_name)
    from model.lenspass.event import LensPassEvent
    from model.device import Device

    if event_key_name != 'all':
        event = LensPassEvent.get_by_key_name(event_key_name)
        if not event:
            raise errors.NoEntityError('event not found: %s' % event_key_name)
        devices = Device.get_by_key_name(event.devices)
    else:
        logging.info('getting all devices')
        devices = Device.all().order('-created').fetch(250)
    osigs = []

    for device in devices:
        if not device:
            logging.error('device not found')
            continue
        try:
            osigs.append({
                'filename': device.device_id,
                'content': get_device_osig(device.device_id)
            })
        except ValueError:
            logging.error('ValueError, unable to get osig for device %s' % device.device_id)
            continue

    logging.info('collected %s osigs' % len(osigs))

    return osigs
Пример #8
0
    def post(self):
        jdatas = json.loads(self.request.body)
        for jdata in jdatas:

            device_mac = jdata['mac']
            data_content = jdata['data_content']
            #insert the new data to redis
            r = redis.Redis()
            r.set("col_datas_%s" % (device_mac), data_content)
            #get the last table in redis and if there is not a record in redis and get the newest record in the table map
            index = r.get("last_data_table_index")
            if not index:
                index = Data_Table_Map.get_last_table_index()
            print "last index:", index
            dtm = Data_Table_Map.find_first("where `index`=?", int(index))
            #print "add last index table!:----------",dtm.index
            if dtm == None:
                Data_Table_Map.add_table(index)

            #parse the data
            #insert into the table
            #if the line of table more than 20w records then create a new table and update table map in the database
            date = data_content['date']
            content = data_content['content']
            dev = Device()
            dev = dev.get_device_by_mac(device_mac)
            DataParser.get_instance().parse_dev(index, dev.id, dev.dev_type,
                                                content)
        self.write('ok')
Пример #9
0
    def img_upload(self, device_mac, device_pos, created_at, meta):
        if device_mac == "":
            return False

        if device_pos == "":
            return False
        dev = Device()
        pos = Position_Image()
        #print "upload_img",device_mac,device_pos

        device_id = dev.get_device_by_mac(device_mac)
        position_id = pos.get_position_id(device_id, device_pos)
        print "upload", device_id, position_id
        upload_path = os.path.join(get_pwd_dir(), CAPTURED_DIR)
        filename = meta['filename']
        filename = os.path.basename(filename)
        print filename, '----', upload_path

        filepath = os.path.join(upload_path, filename)
        with open(filepath, 'wb') as up:
            up.write(meta['body'])

        img = Image()
        img.path = filename
        img.position_id = position_id
        img.created_at = created_at
        img_id = img.create()
        r = redis.Redis()
        r.set('image_path_%s_%s' % (device_mac, device_pos), img.path)
        print img_id
        if not img_id:
            return False
        return True
Пример #10
0
def stop_all():
    device_manager = app.config['DEVICE_MANAGER']
    print(request.json)
    devices = Device.from_json_request(request.json, many=True)
    addresses = list(map(lambda d: d.address, devices))
    results = []
    for address in addresses:
        device = _stop(address, device_manager)
        results.append(device)
    response = Device.to_json_responses(*results, time.time())
    return jsonify(response)
Пример #11
0
def get_all():
    # get query parameter
    scan = int(request.args.get('scan'))
    device_manager = app.config['DEVICE_MANAGER']
    devices = list(
        map(lambda device_state: device_state['device'], device_manager))
    logging.info(devices)
    if scan == 1:
        scanner = MetaWearScanner()
        addresses = scanner.scan()
        devices += [
            Device(address=address, status='stopped') for address in addresses
        ]
    response = Device.to_json_responses(*devices, timestamp=time.time())
    return jsonify(response), 200
Пример #12
0
    def get(self, *args, **kwargs):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html',
                               user_name=usr.name,
                               page_name="browser")
        sel_device_id = self.get_argument('sel_device_id', '')

        if sel_device_id == "":
            dev = devices[0]
        else:
            dev = Device.get(sel_device_id)
        owners = DataParser.get_instance().get_owners(dev.dev_type)
        sel_owner = self.get_argument('owner', '')
        if sel_owner == "":
            sel_owner = owners[0]

        datas_infos = DataParser.get_instance().get_data_types(
            dev.dev_type, sel_owner)

        #print sel_owner, owners
        return self.render(
            'preview.html',
            page_name='preview',
            devices=devices,
            sel_dev=dev,
            sel_owner=sel_owner,
            owners=owners,
            datas_infos=datas_infos,
            user_name=usr.name,
        )
Пример #13
0
class DeviceController():
    def __init__(self):
        self.device_model = Device()

    def get_devices_online(self, user_id=2):
        devices = []
        try:
            self.device_model.userid = user_id
            res = self.device_model.get_devices_online()

            for device in res:
                devices.append({
                    'device_id': device.id,
                    'device_status': device.status,
                    'device_mac': device.mac
                })

            status = 200
        except Exception as e:
            print(e)
            devices = []
            status = 400
        finally:

            return {'result': devices}
Пример #14
0
    def get(self):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html',
                               user_name=usr.name,
                               page_name="browser")

        sel_device_id = self.get_argument('sel_device_id', '')
        sel_device = Device.get(sel_device_id)
        if sel_device_id == '':
            sel_device = devices[0]

        owners = DataParser.get_instance().get_owners(sel_device.dev_type)
        sel_owner = self.get_argument('owner', '')
        if sel_owner == '':
            sel_owner = owners[0]

        data_infos = DataParser.get_instance().get_data_types(
            sel_device.dev_type, sel_owner)
        if data_infos and len(data_infos) > 1:
            sel_data_info = data_infos[0]
        else:
            sel_data_info = None
        return self.render('history.html',
                           page_name='history',
                           devices=devices,
                           sel_device=sel_device,
                           sel_owner=sel_owner,
                           owners=owners,
                           data_infos=data_infos,
                           sel_data=sel_data_info,
                           user_name=usr.name)
    def start(self):
        hosts = []
        if not ParseHostXml.parseHostXml(self._hostPath, hosts):
            self._logger.error("service : parse host xml file failed.")
            return -1

        for host in hosts:

            channel = Channel(host)

            collectResult = CollectResult()
            collectResult.setHostName(host.getHostName())
            collectResult.setIpAddress(host.getIpAddress())

            deviceInfo = Device()

            errCode = self.__getDeviceInfo(channel, host, deviceInfo)
            if errCode != NAGIOS_ERROR_SUCCESS:
                self._logger.error(
                    "service : get device info failed. host name:%s" %
                    host.getHostName())
                collectResult.setService({
                    service: errCode
                    for service in (host.getCollectBasic() if (
                        COLLECT_MODE_CMD_PLUGIN == self._mode
                    ) else host.getCollectExtension())
                })

            else:
                collectResult.setService(
                    self.collect(channel, host, deviceInfo))

            ProcessService.start(self._mode, self._targetPath, collectResult)

        return 0
Пример #16
0
    def get(self,*args, **kwargs):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")
        sel_device_id = self.get_argument('sel_device_id','')

        if sel_device_id == "":
            dev = devices[0]
        else:
            dev =Device.get(sel_device_id)
        owners = DataParser.get_instance().get_owners(dev.dev_type)
        sel_owner = self.get_argument('owner','')
        if sel_owner == "":
            sel_owner = owners[0]

        datas_infos = DataParser.get_instance().get_data_types(dev.dev_type, sel_owner)






        #print sel_owner, owners
        return self.render('preview.html',
                page_name='preview',
                devices = devices,
                sel_dev=dev,
                sel_owner=sel_owner,
                owners = owners,
                datas_infos = datas_infos,
                user_name=usr.name,
                )
Пример #17
0
    def get(self,*args, **kwargs):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        position = Position_Data()
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")
        positions = []
        sel_device_id = self.get_argument('sel_device_id','')
        if sel_device_id == "":
            dev = devices[0]
        else:
            dev =Device.get(sel_device_id)

        datas_infos = DataParser.get_instance().get_data_types(dev.dev_type)



        return self.render('preview.html',
                page_name='preview',
                devices = devices,
                sel_dev=dev,
                datas_infos = datas_infos,
                user_name=usr.name,
                )
Пример #18
0
 def get_data_info(self, tables, type_id, dev_id, owner, start_time,
                   end_time):
     data_list = []
     for table in tables:
         data_list.extend(
             Data.find_by(
                 'where device_id = ? and type_id = ? and owner= ? and created_at between ? and ?',
                 dev_id,
                 type_id,
                 owner,
                 start_time,
                 end_time,
                 sub_name=str(table.index)))
     res = {}
     dev = Device.get(dev_id)
     data_info = DataParser.get_instance().get_data_type(
         dev.dev_type, type_id, owner)
     res['name'] = data_info['name']
     res['type_id'] = data_info['type_id']
     res['unit'] = data_info['unit']
     res['values'] = []
     for data_item in data_list:
         res['values'].append(
             [data_item.created_at * 1000, data_item.value])
     return res
Пример #19
0
 def updateDevices(self, path):
     del self._devices[:]
     with open(path, 'r') as f:  #'../Web/appserver/config/default.json'
         ln = f.read()
         devices = json.loads(ln)
         for device in devices:
             self._devices.append(Device(**device))
Пример #20
0
    def get(self):
        dev_id = self.get_argument('dev_id', '')
        type_id = self.get_argument('type_id', '')
        owner = self.get_argument('owner', '')
        start_time = self.get_argument('start_time') + ':00'
        start_time = time.mktime(time.strptime(start_time,
                                               '%Y-%m-%d %H:%M:%S'))
        end_time = self.get_argument('end_time') + ':00'
        end_time = time.mktime(time.strptime(end_time, '%Y-%m-%d %H:%M:%S'))
        tables = Data_Table_Map.get_tables(start_time, end_time)

        if type_id != "":
            res = self.get_data_info(tables, type_id, dev_id, owner,
                                     start_time, end_time)
            self.write(json.dumps(res))
        else:
            dev = Device.get(dev_id)
            datas_info = DataParser.get_instance().get_data_types(
                dev.dev_type, owner)
            #print "tables:---------",len(tables),start_time, end_time, tables
            reses = []
            for di in datas_info:
                #print di['type_id']
                reses.append(
                    self.get_data_info(tables, di['type_id'], dev_id,
                                       di['owner'], start_time, end_time))
            self.write(json.dumps(reses))
Пример #21
0
    def get(self):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")

        sel_device_id = self.get_argument('sel_device_id','')
        sel_device = Device.get(sel_device_id)
        if sel_device_id == '':
            sel_device = devices[0]

        owners = DataParser.get_instance().get_owners(sel_device.dev_type)
        sel_owner = self.get_argument('owner','')
        if sel_owner == '':
            sel_owner = owners[0]


        data_infos = DataParser.get_instance().get_data_types(sel_device.dev_type, sel_owner)
        if data_infos and len(data_infos)>1:
            sel_data_info = data_infos[0]
        else:
            sel_data_info = None
        return self.render('history.html',
                           page_name = 'history',
                           devices = devices,
                           sel_device = sel_device,
                           sel_owner = sel_owner,
                           owners = owners,
                           data_infos =data_infos,
                           sel_data = sel_data_info,
                           user_name=usr.name)
Пример #22
0
def run(address):
    process_manager = app.config['PROCESS_MANAGER']
    device_manager = app.config['DEVICE_MANAGER']
    body = request.json
    device = Device.from_json_request(body)
    device = _run(address, device, device_manager, process_manager)
    response = device.to_json_response(time.time())
    return jsonify(response)
Пример #23
0
 def post(self):
     dev_id = self.get_argument('dev_id', '')
     dev = Device.get(dev_id)
     if dev:
         dev_type = dev.dev_type
         res = DataParser.get_instance().get_owners(dev_type)
         res = json.dumps(res)
         self.write(res)
Пример #24
0
 def post(self):
     dev_id = self.get_argument('dev_id','')
     dev = Device.get(dev_id)
     if dev:
         dev_type = dev.dev_type
         res = DataParser.get_instance().get_owners(dev_type)
         res = json.dumps(res)
         self.write(res)
def step_impl(context):
    context.room_2.device_list = [Device(21, c.INFINITY, False)]

    context.event_manager = EventObserver(context.room_2, context.mock_clientMqtt_2)
    context.event_manager.mqtt_manager.publish_urgent_msg_to_server = MagicMock()

    context.room_2.attach_observer(context.event_manager)

    context.dpop_to_test = DpopRoom(context.room_2, context.mock_clientMqtt_2)
Пример #26
0
def get(address):
    device_manager = app.config['DEVICE_MANAGER']
    device_state = find_device_state_by_address(address, device_manager)
    if device_state is not None:
        response = device_state['device'].to_json_response(time.time())
    else:
        response = Device(
            address=address,
            error_code='Device is not found').to_json_response(time.time())
    return jsonify(response)
Пример #27
0
 def get(self, *args, **kwargs):
     sel_device_id = self.get_argument('sel_device_id','')
     dev = Device.get(sel_device_id)
     if dev:
         r  = redis.Redis()
         data_content = r.get("col_datas_%s" %(dev.mac))
         data_content = eval(data_content)
         res = DataParser.get_instance().parse_to_json(dev.dev_type, data_content['content'], data_content['date']*1000, dev.id)
         res = json.dumps(res)
         self.write(res)
         return self.finish()
Пример #28
0
    def __init__(self):
        self._dispatcher = DeviceDispatcher()

        if len(sys.argv) < 2:
            raise ValueError('parameter must be dispatcher virtual device ID')

        self._device = Device(sys.argv[1], SignalSource='queue')

        if (not self._device.SignalSource == ''):
            self._signalSource = SignalSourceFactory.createInstance(
                self._device.SignalSource)
            self._signalSource.set_signal_received(self.on_signal_received)
Пример #29
0
 def __init__(self, properties: SimulationProperties):
     self.__stats = Stats(properties.num_sources, properties.num_devices)
     self.__generators = [
         Generator(i, l, self.__stats)
         for i, l in enumerate(properties.source_lambdas)
     ]
     self.__devices = [
         Device(i, t, self.__stats)
         for i, t in enumerate(properties.device_taus)
     ]
     self.__buffer = Buffer(properties.buffer_capacity, self.__stats)
     self.__max_requests = properties.max_requests
     self.__global_time = 0
Пример #30
0
    def get_data_info(self, tables, type_id, dev_id, start_time, end_time):
        data_list = []
        for table in tables:
            data_list.extend(Data.find_by('where device_id = ? and type_id = ? and created_at between ? and ?', dev_id, type_id, start_time, end_time, sub_name = str(table.index)))

        dev  = Device.get(dev_id)
        data_info = DataParser.get_instance().get_data_type(dev.dev_type, type_id)

        if data_info['duration'] == 0:
            return self.deal_for_single(data_list, data_info)

        if data_info['duration'] > 0:
            return self.deal_for_accumulate(data_list, data_info)
Пример #31
0
    def get(self, *args, **kwargs):
        sel_device_id = self.get_argument('sel_device_id','')
        dev = Device.get(sel_device_id)
        if dev:
            r  = redis.Redis()
            data_content = r.get("col_datas_%s" %(dev.mac))

            data_content = eval(data_content)
            res = DataParser.get_instance().parse_to_json(dev.dev_type, data_content['content'], data_content['date']*1000)
            #print "res:",res
            res = json.dumps(res)
            self.write(res)
            return self.finish()
Пример #32
0
 def get_data_info(self, tables, type_id, dev_id, owner, start_time, end_time):
     data_list = []
     for table in tables:
         data_list.extend(Data.find_by('where device_id = ? and type_id = ? and owner= ? and created_at between ? and ?', dev_id, type_id, owner, start_time, end_time, sub_name = str(table.index)))
     res = {}
     dev  = Device.get(dev_id)
     data_info = DataParser.get_instance().get_data_type(dev.dev_type, type_id, owner)
     res['name'] = data_info['name']
     res['type_id'] = data_info['type_id']
     res['unit'] = data_info['unit']
     res['values'] = []
     for data_item in data_list:
         res['values'].append([data_item.created_at*1000, data_item.value])
     return res
def step_impl(context):
    context.room_2.device_list = [Device(11, 40, False)]
    context.room_2.tau = 80

    context.dpop_to_test = DpopRoom(context.room_2, context.mock_clientMqtt_2)

    assert_that(
        not context.dpop_to_test.monitored_area.device_list[0].
        is_in_critic_state, 'device not in critical state')
    assert_that(
        context.dpop_to_test.monitored_area.device_list[0].end_of_prog > 30,
        'device end its program too soon')
    assert_that(context.dpop_to_test.monitored_area.tau < 180,
                'previous intervention is too recent')
Пример #34
0
    def post(self):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html', user_name=usr.name, page_name="browser")

        sel_device_id = self.get_argument('sel_device_id','')
        sel_device = Device.get(sel_device_id)
        if sel_device_id == '':
            sel_device = devices[0]

        data_infos = DataParser.get_instance().get_data_types(sel_device.dev_type)
        return self.write(json.dumps(data_infos))
Пример #35
0
def step_impl(context):
    context.dpop_to_test.monitored_area.tau = 181
    context.dpop_to_test.monitored_area.device_list = [
        Device(1, 240, False),
        Device(2, 240, False),
        Device(3, 240, False),
        Device(4, 240, False),
        Device(5, 240, False),
        Device(6, 240, False)
    ]
Пример #36
0
    def post(self):
        usr = self.get_current_user()
        device_observed = Device_Observed()
        devices = device_observed.observed_devices(usr.id)
        if not devices or len(devices) < 1:
            return self.render('no_devices.html',
                               user_name=usr.name,
                               page_name="browser")

        sel_device_id = self.get_argument('sel_device_id', '')
        sel_device = Device.get(sel_device_id)
        if sel_device_id == '':
            sel_device = devices[0]

        data_infos = DataParser.get_instance().get_data_types(
            sel_device.dev_type)
        return self.write(json.dumps(data_infos))
Пример #37
0
def _stop(address, device_manager):
    device_state = find_device_state_by_address(address, device_manager)
    if device_state is not None:
        stop_signal = device_state['stop_signal']
        state = device_state['state']
        p = device_state['process']
        device = device_state['device']
        stop_signal.set()
        while state.value != 'stopped':
            pass
        p.terminate()
        device.status = state.value
        remove_device_state_by_address(address, device_manager)
        logging.info('Stop a sensor: ' + address)
    else:
        device = Device(address=address, error_code='Device not found')
        logging.info('Sensor is not found')
    return device
Пример #38
0
    def get_data_info(self, tables, type_id, dev_id, start_time, end_time):
        data_list = []
        for table in tables:
            data_list.extend(
                Data.find_by(
                    'where device_id = ? and type_id = ? and created_at between ? and ?',
                    dev_id,
                    type_id,
                    start_time,
                    end_time,
                    sub_name=str(table.index)))

        dev = Device.get(dev_id)
        data_info = DataParser.get_instance().get_data_type(
            dev.dev_type, type_id)

        if data_info['duration'] == 0:
            return self.deal_for_single(data_list, data_info)

        if data_info['duration'] > 0:
            return self.deal_for_accumulate(data_list, data_info)
Пример #39
0
    def get(self):
        dev_id = self.get_argument('dev_id','')
        type_id = self.get_argument('type_id','')
        start_time=self.get_argument('start_time')+':00'
        start_time = time.mktime(time.strptime(start_time, '%Y-%m-%d %H:%M:%S'))
        end_time=self.get_argument('end_time')+':00'
        end_time = time.mktime(time.strptime(end_time, '%Y-%m-%d %H:%M:%S'))
        tables = Data_Table_Map.get_tables(start_time, end_time)

        if type_id != "":
            res = self.get_data_info(tables, type_id, dev_id, start_time, end_time)
            self.write(json.dumps(res))
        else:
            dev = Device.get(dev_id)
            datas_info = DataParser.get_instance().get_data_types(dev.dev_type)
            #print "tables:---------",datas_info
            reses = []
            for di in datas_info:
                #print di['type_id']
                reses.append(self.get_data_info(tables, di['type_id'], dev_id, start_time, end_time))
            self.write(json.dumps(reses))
Пример #40
0
 def post(self):
     jdatas = json.loads(self.request.body)
     #device_mac = self.get_argument('mac', '')
     #device_location = self.get_argument('location', '')
     device_mac = jdatas['mac']
     device_location = jdatas['location']
     print device_mac,'location:',device_location
     dev = Device()
     dev.mac=get_md5(device_mac)
     dev.location=device_location
     if None == dev.get_device_by_mac(device_mac):
         device_id = dev.create()
     else:
         device_id = dev.update_info()
     print device_id
     if not device_id:
         self.write('fail')
         return
     self.write('ok')
# coding=utf-8
from model.device import Device
from model.user import User
from model.device_observed import Device_Observed
import sys

def connect_db():
    import transwarp.db as dbutil
    dbutil.create_engine('sonic513', 'sonic513', 'tobacco_monitor', port=3306)

if __name__=="__main__":
    connect_db()
    user_name = sys.argv[1]
    mac = sys.argv[2]
    dev = Device.find_first("where mac = ?", mac.strip())
    usr = User.find_first("where name = ?", user_name.strip())
    dev_obs = Device_Observed()
    if dev_obs.observe(usr.id, dev.id):
        print "dev observe success!"
    else:
        print "dev observe fail!"
Пример #42
0
from model.device import Device
from model.device_observed import Device_Observed
from model.image import Image
from model.position import Position_Image
from model.data import Data, Data_Table_Map
from model.user import User

import sys

def connect_db():
    import transwarp.db as dbutil
    dbutil.create_engine('sonic513', 'sonic513', 'co2_monitor', port=3306)

if __name__=="__main__":
    connect_db()
    dev = Device()
    dev.create_table()
    usr = User()
    usr.create_table()
    doed = Device_Observed()
    doed.create_table()
    dtm = Data_Table_Map()
    dtm.create_table()
    #img = Image()
    #img.create_table()
    #pos_image = Position_Image()
    #pos_image.create_table()
    #data = Data()
    #data.create_table()

    
Пример #43
0
# coding=utf-8
from model.position import Position_Image
from model.device import Device
import sys

def connect_db():
    import transwarp.db as dbutil
    dbutil.create_engine('sonic513', 'sonic513', 'tobacco_monitor', port=3306)

if __name__=="__main__":
    connect_db()
    mac = sys.argv[1]
    position = sys.argv[2]
    object_name = sys.argv[3]
    duration = sys.argv[4]
    dev = Device.find_first("where mac=?", mac)
    if not dev:
        print "device with mac not found!"

    pos = Position_Image(position = int(position), object_name=object_name, device_id = dev.id, duration = duration)
    id= pos.create()
    if id:
        print "add image pos %s OK!" % position
    else:
        print "add image pos error!"
Пример #44
0
# coding=utf-8
from model.position import Position_Image
from model.device import Device
import sys


def connect_db():
    import transwarp.db as dbutil
    dbutil.create_engine('sonic513', 'sonic513', 'tobacco_monitor', port=3306)


if __name__ == "__main__":
    connect_db()
    mac = sys.argv[1]
    position = sys.argv[2]
    object_name = sys.argv[3]
    duration = sys.argv[4]
    dev = Device.find_first("where mac=?", mac)
    if not dev:
        print "device with mac not found!"

    pos = Position_Image(position=int(position),
                         object_name=object_name,
                         device_id=dev.id,
                         duration=duration)
    id = pos.create()
    if id:
        print "add image pos %s OK!" % position
    else:
        print "add image pos error!"
Пример #45
0
 def add_or_update_device(self):
     id_device = str(self.id) + str(len(self.device_list) + 1)
     critic_state = random() < 0.05
     self.device_list.append(
         Device(int(id_device), randint(c.MIN_TAU_VALUE, c.INFINITY),
                critic_state))
Пример #46
0
# coding=utf-8
from model.device import Device
import sys

def connect_db():
    import transwarp.db as dbutil
    dbutil.create_engine('sonic513', 'sonic513', 'tobacco_monitor', port=3306)

if __name__=="__main__":
    connect_db()
    location = sys.argv[1]
    mac = sys.argv[2]
    dev_type = sys.argv[3]
    dev = Device(location = location, mac=mac, dev_type = dev_type)
    id= dev.create()
    if id:
        print "add dev %s OK!" % mac
    else:
        print "add dev error!"
Пример #47
0
 def get(self):
     devs = Device.find_all()
     self.write(json.dumps(devs))
     self.finish()