def init_data(): """设备启动获取运行参数""" # id = request.values.get('id') type_ = request.values.get('type', None, type=int) ip = request.remote_addr os = request.values.get('os', '') result = ErrorReturn(ErrorDefs.UnknownError) # if not id or not(os) or not(type_): # return ErrorReturn(ErrorDefs.ParameterInvalid).response if type_ not in SystemDeviceType.ValidatedList: return ErrorReturn(ErrorDefs.ParameterInvalid, u'设备类型不存在').response if type_ == SystemDeviceType.InnerBox: result = init_innerbox() if type_ == SystemDeviceType.OuterBox: result = init_outerbox() if type_ == SystemDeviceType.InnerScreen: result = init_innerbox() if type_ in (SystemDeviceType.PropCallApp, SystemDeviceType.PropSentryApp): result = init_propapp(type_) return result.response
def update_share_device(): """更新共享设备信息""" user = g.user share_id = request.values.get('share_id') name = request.values.get('name') expire = request.values.get('expire') # 过期时间 password = request.values.get('password', '') user_limit = request.values.get('user_limit', 0, type=int) status = request.values.get('status', '') if status not in ('open', 'close'): return ErrorReturn(ErrorDefs.ParameterInvalid, u'提交参数错误').response link = model.SharedDeviceLink.get(user_id=user.id, _id=ObjectId(share_id)) if not link: return ErrorReturn(ErrorDefs.ObjectNotExist).response if not password: password = '' link.name = name link.expire_time = expire link.password = password.strip() link.user_limit = user_limit link.status = status link.save() return CR(result='').response
def get_ticket(): """上传微信 code , 与微信服务器交互,获得open_id,并返回token到前端""" main = instance.serviceManager.get('main') code = request.values.get('code') encryptedData = request.values.get('encryptedData') iv = request.values.get('encryptedData') if not code: return ErrorReturn(ErrorDefs.UserNotExist).response appid = main.getConfig().get('wx_settings').get('appid') secret = main.getConfig().get('wx_settings').get('secret') params = dict(appid=appid, secret=secret, js_code=code, grant_type='authorization_code') url = main.getConfig().get('wx_settings').get('code2session_url') resp = requests.get(url, params) data = resp.json() open_id = '' session_key = '' union_id = '' # if data.get('errcode') == 0: open_id = data.get('openid') session_key = data.get('session_key') # union_id = data.get('unionid') if not open_id: return ErrorReturn(ErrorDefs.AccessDenied, u'微信服务器返回错误:{}'.format( data.get('errcode'))).response user = model.User.get_or_new(platform='wx', account=open_id) user.platform = 'wx' user.last_login = timestamp_current() user.save() auth = AuthToken() auth.login_time = timestamp_current() auth.user_id = user.account auth.user_name = user.name auth.platform = 'wx' auth.open_id = open_id user.token = auth.encode() user.save() result = dict(open_id=open_id, union_id=union_id, token=user.token) return CR(result=result).response
def get_innerbox_list(): """查询室内机列表""" # auth = g.auth # token = request.values.get('token') type_ = request.values.get("type", type=int) ip = request.remote_addr.split(':')[-1] result = [] if type_ in SystemDeviceType.ValidatedList and type_ != SystemDeviceType.OuterBox: """室内发起获取园区所有室内机的请求""" rs = model.InnerBox.find() for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) if type_ == SystemDeviceType.OuterBox: """室外机查询室内机""" # 判别是围墙机还是单元机 box = model.OuterBox.get(ip=ip) if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室外主机未登记') if box.type == 'A': # 围墙机,返回所有 rs = model.InnerBox.find() for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) if box.type == 'B': # 单元机 ,返回本单元相关的室内主机 rs = model.InnerBox.find(building_id=box.building_id) for r in rs: result.append(dict(ip=r.ip, room_id=r.room_id)) return CR(result=result).response
def create_cargo_address(): """查询本人创建的共享设备信息 支持 共享设备编号查询 或 设备编号查询 如果共享记录未创建则创建,并返回 """ user = g.user name = request.values.get('name') phone = request.values.get('phone') address_ = request.values.get('address', '') is_default = request.values.get('is_default', 0, type=int) if not name or not phone or not address_: return ErrorReturn(ErrorDefs.ParameterInvalid, u'必须提供联系人、手机号、收件地址').response if is_default: # 将其他记录设置为非默认 model.CargoAddress.collection().update_many( { 'user_id': user.id, 'is_default': 1 }, {'$set': { 'is_default': 0 }}) address = model.CargoAddress() address.user_id = user.id address.name = name address.phone = phone address.address = address_ address.is_default = is_default address.order = timestamp_current() address.update_time = timestamp_current() address.save() return CR(result=address.id).response
def set_device_fence(): """设置设备的围栏参数 """ user = g.user device_id = request.values.get('device_id') data = {} for k, v in request.args.items(): data[k] = v fence = model.Fence.get_or_new(device_id=device_id) object_assign(fence, data) if fence.type not in FenceType.ALL: return ErrorReturn(ErrorDefs.ParameterInvalid).response fence.index = int(fence.index) fence.enable = int(fence.enable) fence.cx = float(fence.cx) fence.cy = float(fence.cy) fence.radius = int(fence.radius) fence.x1 = float(fence.x1) fence.y1 = float(fence.y1) fence.x2 = float(fence.x2) fence.y2 = float(fence.y2) fence.alarm_type = int(fence.alarm_type) device = model.Device.get(device_id=device_id) main = instance.serviceManager.get('main') # 发送设置围栏命令 cmd = '' cc = main.getCommandController(device.device_type) if fence.type == FenceType.CIRCLE: cmd = cc.setCircleFence(fence.cx, fence.cy, fence.radius, fence.inout) if cmd: main.sendCommand(device_id, cmd) fence.save() return CR().response
def get_group_info(): """获取设备详情 """ user = g.user group_id = request.values.get('group_id') include_devices = request.values.get('include_devices',0,type = int) group = model.Group.get(_id=ObjectId(group_id), user_id=user.id) if not group: return ErrorReturn(ErrorDefs.ObjectNotExist).response result = group.dict() if include_devices: result['devices'] = [] rs = model.DeviceGroupRelation.collection().find( {'group_id': group_id }).sort([('order',pymongo.ASCENDING)]) for rel in list(rs): # device = model.Device.get(device_id = rel.device_id) devrel = model.DeviceUserRelation.get(user_id = user.id,device_id = rel['device_id']) if devrel: data = dict( device_id= devrel.device_id, device_type = devrel.device_type, name = devrel.device_name ) result['devices'].append(data) result['device_count'] = len(result['devices']) return CR(result=result).response
def get_device_info(): """""" user = g.user device_id = request.values.get('device_id') rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if not rel: # 设备不存在 return ErrorReturn(ErrorDefs.ObjectNotExist).response device = model.Device.get(device_id=device_id) result = dict(device_id=device_id, device_type=device.device_type, imei=device.imei, sim=device.sim, mobile=device.mobile, admin_mobile=device.admin_mobile, name=rel.device_name, image=rel.device_image, update_time=rel.update_time, is_share_device=rel.is_share_device, share_user_id=rel.share_user_id, share_device_link=rel.share_device_link, password=device.password, map_scale=rel.map_scale) if not result['password']: result['password'] = '' result['capacity'] = capacity.get_product_features(device.device_type) if not rel.device_name: result['name'] = device.name return CR(result=result).response
def get_code_list(): date = request.values.get('date', '') strategy_id = request.values.get('strategy_id') if not strategy_id or not date: return ErrorReturn(ErrorDefs.ParameterInvalid).response date = parse(date) conn = instance.datasourceManager.get('mongodb').conn dbname = 'TradeFisher_{}-{}-{}'.format(date.year, date.month, date.day) db = conn[dbname] model.CodeSettings.__database__ = db model.CodePrice.__database__ = db model.CodePosition.__database__ = db result = [] for cs in model.CodeSettings.find(strategy_id=strategy_id): data = cs.dict() price = model.CodePrice.get(code=cs.code) if price: data['price'] = price.dict() data['price']['time'] = str(data['price']['time']) pos = model.CodePosition.get(strategy_id=strategy_id, code=cs.code) if pos: data['pos'] = pos.dict() result.append(data) return CR(result=result).response
def init_outerbox(): """室外机登录""" ip = request.remote_addr.split(':')[-1] box = model.OuterBox.get(ip=ip) # 根据ip检查设备是否登记 if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室外主机未登记') box.login_time = timestamp_current() box.save() data = {} garden = model.HomeGarden.get(id='8888') data['propcenter_ip'] = garden.property_call_server data['stream_server_url'] = garden.stream_server_url innerbox_list = [] rs = model.InnerBox.find(garden_id=garden.id, building_id=box.building_id) for _ in rs: innerbox_list.append(dict(room_id=_.room_id, ip=_.ip)) sentry_list = [] rs = model.SentryApp.find(garden_id=garden.id) for _ in rs: sentry_list.append(dict(name=_.name, ip=_.ip)) data['innerbox_list'] = innerbox_list data['sentry_list'] = sentry_list result = data return CR(result=result)
def _get_position_path(start, end, granule, device_id): """查询设备历史轨迹点 start - 开始时间 end - 结束时间 , 最大时长不能超过 1 周 """ from mantis.BlueEarth.tools.geotools import wgs84_to_gcj02 import path DAY = 3600 * 24 WEEK = 3600 * 24 * 7 user = g.user # device_id = request.values.get('device_id') # start = request.values.get('start',type=int) # end = request.values.get('end',0,type=int) # granule = request.values.get('granule',0,type=int) # 时间刻度(分钟) # duration = request.values.get('duration',1,type=int) if granule: granule = granule * 60 if not end: end = start + DAY if end - start > WEEK: return ErrorReturn(ErrorDefs.ReachLimit).response rel = model.DeviceUserRelation.get(user_id=user.id, device_id=device_id) if not rel: return ErrorReturn(ErrorDefs.ObjectNotExist, u'设备不存在').response coll = model.Position.collection() rs = coll.find({ 'device_id': device_id, 'timestamp': { '$gte': start, '$lt': end } }).sort('timestamp', 1) rs = list(rs) result = rs # last = None result = path.clean_path(rs) for p in result: del p['_id'] # if p['speed'] == 0: # continue p['lon'], p['lat'] = wgs84_to_gcj02(p['lon'], p['lat']) return result
def update_device(): user = g.user device_id = request.values.get('device_id') password = request.values.get('password') name = request.values.get('name') mobile = request.values.get('mobile') # 设备内置电话号码 admin_mobile = request.values.get('admin_mobile') # 管理人手机号 image = request.values.get('image') map_scale = request.values.get('map_scale', 0, type=int) device = model.Device.get(device_id=device_id) if not device: return ErrorReturn(ErrorDefs.ObjectNotExist).response # 检测设备是否已经添加了 rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if not rel: # 设备不存在 return ErrorReturn(ErrorDefs.ObjectNotExist).response if name: rel.device_name = name # 仅修改用户设备名称,原始设备名称并不修改 if map_scale: rel.map_scale = map_scale # 保存设备当前的地图缩放级别 if rel.is_share_device: # 共享设备的话,用户只能修改名称 if name: rel.save() return CR().response if name or map_scale: rel.save() kwargs = {} if password: kwargs['password'] = password if mobile: kwargs['mobile'] = mobile if admin_mobile: kwargs['admin_mobile'] = admin_mobile if image: kwargs['image'] = image if kwargs: device.update(**kwargs) return CR().response
def device_login(): """设备主机登陆,服务器校验合法性,并返回接入服务器地址""" main = instance.serviceManager.get('main') id_ = request.values.get('id') type_ = request.values.get('type') ver = request.values.get('ver') time = request.values.get('time') sign = request.values.get('sign','').upper() if not id_ or not type_ or not ver or not time or not sign: # if not id_ or not type_ : return ErrorReturn(ErrorDefs.ParameterInvalid).response secret_key = main.getConfig().get('device_secret_key') value,_ = make_signature(secret_key,dict(id=id_,type=type_,ver=ver,time=time)) if value != sign: instance.getLogger().error(u"数据签名计算错误") return ErrorReturn(ErrorDefs.ParameterInvalid).response device = model.SmartDevice.get(id = id_) if not device: return ErrorReturn(ErrorDefs.ObjectNotExist,u'设备不存在').response # 加入 认证处理时间 data = dict(id=id_,type=type_,ver=ver,time=time,auth_time=timestamp_current()) token = device_token_create(data,device.secret_key) main = instance.serviceManager.get('main') boxserver = main.getConfig().get('boxserver') host,port = boxserver.split(':') result = dict(token=token, server_ip=host, server_port=int(port), server_time=timestamp_current() ) # server = model.DeviceServer.get(id=device.server_id) # if not server: # return ErrorReturn(ErrorDefs.DeviceServerNotFound).response # # result = dict( token = token, server_ip = server.ip, server_port = server.port , # server_time = timestamp_current() # ) return CR(result= result).response
def get_device_password(): """找回设备密码 ,系统并不创建密码 如果设备未激活,未绑定手机,则读取设备密码并发送短信到用户手机 支持短设备号 """ from mantis.BlueEarth.utils import make_password, encrypt_text user = g.user open_id = g.auth.open_id device_id = request.values.get('device_id') # phone = request.values.get('phone') phone = '' if not device_id: return ErrorReturn(ErrorDefs.ParameterInvalid).response device_id = device_id.lower() device = model.Device.get(device_id=device_id) if not device: device = model.Device.get(short_id=device_id) if not device: return ErrorReturn(ErrorDefs.ObjectNotExist).response # 设备已经被激活了,且存在电话号码,则向电话号码发送密码 if device.active: phone = device.admin_mobile else: return ErrorReturn(ErrorDefs.AccessDenied, u'设备未激活,无法发送设备密码! ').response password = device.password if not password: return ErrorReturn(ErrorDefs.ObjectNotExist, u'设备密码未设置,请用默认密码登录! ').response if not phone: return ErrorReturn(ErrorDefs.ObjectNotExist, u'设备未设置电话号码,请联系系统运营人员! ').response # if not password: # 密码不存在则创建初始设备密码 # password = encrypt_text(make_password()) # device.password = password # device.save() phone = phone.strip() if phone: main = instance.serviceManager.get('main') main.sendDevicePassword(phone, device.device_id, password) return CR(errmsg=u'密码已成功发送至' + phone).response
def opendoor_innerbox(): room_id = request.values.get('room_id') secret_key = request.values.get('secret_key') if not room_id or not secret_key: return ErrorReturn(ErrorDefs.ParameterInvalid).response # 查询室内机主机ip box = model.InnerBox.get(room_id=room_id) # 根据ip检查设备是否登记 if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室内主机未登记') ip = box.ip # 发送开门请求 url = 'http://{}:7890/smartbox/api/emergency/opendoor'.format(box.ip) token = Constants.SUPER_ACCESS_TOKEN requests.post(url, data=dict(token=token, rand_key=secret_key)) return CR().response
def share_device_follower_allow(denied=False): """ 允许follower访问设备 GET /share-device/follower/allow """ user = g.user follower_id = request.values.get('follower_id') follower = model.ShareDeviceFollower.get(_id=ObjectId(follower_id)) if not follower: return ErrorReturn(ErrorDefs.ObjectNotExist).response # 防止非法跨用户操作 share = model.SharedDeviceLink.get(_id=ObjectId(follower.share_id), user_id=user.id) if not share: return ErrorReturn(ErrorDefs.ObjectNotExist).response follower.denied = denied follower.save() return CR().response
def remove_cargo_address(): """ """ user = g.user id = request.values.get('id') address = model.CargoAddress.get(_id=ObjectId(id)) if not address: return ErrorReturn(ErrorDefs.ObjectNotExist, u'对象不存在').response address.delete() return CR(result=address.id).response
def get_device_fence(): """获得设备的围栏参数 """ user = g.user device_id = request.values.get('device_id') fence = model.Fence.get(device_id=device_id) if not fence: return ErrorReturn(ErrorDefs.ObjectNotExist).response result = fence.dict() return CR(result=result).response
def remove_favorite(): """ """ user = g.user id = request.values.get('id') favorite = model.Favorite.get(_id=ObjectId(id)) if not favorite: return ErrorReturn(ErrorDefs.ObjectNotExist, u'对象不存在').response favorite.delete() return CR().response
def query_bars(): """ 列举所有已订阅的合约代码 :param symbol :param scale :param product_class :param start : timestamp 70's :param end : timestamp 70' :param limit 查询返回记录最大个数,默认值零表示返回记录不限。 :return: """ symbol = request.values.get('symbol', '') if not symbol: return ErrorReturn(ErrorDefs.ParameterInvalid).response scale = request.values.get('scale', '15m').lower() product_class = request.values.get('product_class', ProductClass.Future) start = request.values.get('start', 0) end = request.values.get('end', 0) limit = request.values.get('limit', 500) if scale not in TimeScale.SCALES.keys(): return ErrorReturn(ErrorDefs.BAR_SCALE_INVALID).response service = instance.serviceManager.get('main') dbconn = service.datasourceManager.get('mongodb').conn dbname = DatabaseDefs.get(product_class, {}).get('bars', '').format(scale) coll = dbconn[dbname][symbol] sortkey = 'datetime' dtstart = datetime.datetime.fromtimestamp(int(start)) dtend = datetime.datetime.fromtimestamp(int(end)) case = {"datetime": {"$gte": dtstart, "$lte": dtend}} if sortkey: cursor = coll.find(case).sort(sortkey, ASCENDING) else: cursor = coll.find(case) result = list(cursor.limit(limit)) for r in result: r['datetime'] = time.mktime(r['datetime'].timetuple()) return CR().assign(result).response
def set_view_device_top(): """设备信息置顶""" user = g.user device_id = request.values.get('device_id') device = model.Device.get(device_id=device_id) if not device: return ErrorReturn(ErrorDefs.ObjectNotExist).response # 检测设备是否已经添加了 rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if not rel: # 设备不存在 return ErrorReturn(ErrorDefs.ObjectNotExist).response kwargs = {} kwargs['order'] = -timestamp_current() device.update(**kwargs) return CR().response
def update_user_info(): kwargs = request.values.to_dict() user = model.User.get(_id=ObjectId(g.user.id)) if not user: return ErrorReturn(ErrorDefs.ObjectNotExist).response valid_fields = {} for k, v in kwargs.items(): if k in ('name', 'avatar', 'mobile', 'email', 'address'): valid_fields[k] = v user.update(**valid_fields) return CR().response
def create_group(): """创建设备组 """ user = g.user name = request.values.get('name') comment = request.values.get('comment','') if not name: return ErrorReturn(ErrorDefs.ParameterInvalid).response if model.Group.get(name=name): return ErrorReturn(ErrorDefs.ObjectHasExist,u'相同组名已存在').response group = model.Group() group.name = name group.comment = comment group.order = timestamp_current() group.user_id = user.id group.create_time = timestamp_current() group.update_time = timestamp_current() group.save() return CR(result=group.id).response
def get_cargo_address(): """查询本人创建的共享设备信息 支持 共享设备编号查询 或 设备编号查询 如果共享记录未创建则创建,并返回 """ user = g.user id = request.values.get('id') address = model.CargoAddress.get(user_id=user.id, _id=ObjectId(id)) if not address: return ErrorReturn(ErrorDefs.ObjectNotExist, u'地址对象不存在').response result = address.dict() return CR(result=result).response
def create_share_device(): """创建设备共享 url: /share-device post """ user = g.user device_id = request.values.get('device_id') name = request.values.get('name') expire = request.values.get('expire') # 过期时间 password = request.values.get('password', '') user_limit = request.values.get('user_limit', 0, type=int) status = request.values.get('status', 'open') #1.设备是否存在 #2.是否已创建共享设备 rel = model.DeviceUserRelation.get(user_id=user.id, device_id=device_id) if not rel: return ErrorReturn(ErrorDefs.ObjectNotExist, u'设备不存在').response link = model.SharedDeviceLink.get(user_id=user.id, device_id=device_id) if link and link.name == name: return ErrorReturn(ErrorDefs.ObjectHasExist, u'名称重复,请重新填写').response if not password: password = '' link = model.SharedDeviceLink() link.user_id = user.id link.open_id = user.account link.device_id = device_id link.device_type = rel.device_type link.name = name link.expire_time = expire link.password = password.strip() link.user_limit = user_limit link.create_time = timestamp_current() link.status = status link.save() return CR(result=link.id).response
def add_device(): """添加用户设备 默认密码为设备编码后缀4位数字 """ user = g.user device_id = request.values.get('device_id') password = request.values.get('password') name = request.values.get('name') device = model.Device.get(device_id=device_id) if not password: return ErrorReturn(ErrorDefs.NeedPassword).response if not device: return ErrorReturn(ErrorDefs.ObjectNotExist, u'设备不存在').response if not device.password: # 密码不存在就采用设备后四位 if password != device_id[-4:]: return ErrorReturn(ErrorDefs.PasswordError).response else: if password != device.password: return ErrorReturn(ErrorDefs.PasswordError).response if not device.active: device.active = True device.save() # 检测设备是否已经添加了 rel = model.DeviceUserRelation.get(user_id=str(user.id), device_id=device_id) if rel: return CR(result=str(rel.id)).response rel = model.DeviceUserRelation() rel.user_id = user.id rel.device_id = device_id rel.update_time = timestamp_current() rel.device_type = device.device_type rel.save() return CR(result=rel.id).response
def remove_group(): """删除设备 """ user = g.user group_id = request.values.get('group_id') group = model.Group.get(_id=ObjectId(group_id),user_id=user.id) model.DeviceGroupRelation.collection().delete_many({'group_id': group_id}) if not group: return ErrorReturn(ErrorDefs.ObjectNotExist).response group.delete() return CR().response
def get_strategy_list(): date_s = request.values.get('date', '') if not date_s: return ErrorReturn(ErrorDefs.ParameterInvalid).response date = parse(date_s) conn = instance.datasourceManager.get('mongodb').conn dbname = 'TradeFisher_{}-{}-{}'.format(date.year, date.month, date.day) db = conn[dbname] model.StrategyParam.__database__ = db sts = model.StrategyParam.find() result = [] for s in sts: s.date = date_s result.append(s.dict()) return CR(result=result).response
def get_user_info(): user = g.user open_id = g.auth.open_id user = model.User.get(_id=ObjectId(g.user.id)) if not user: return ErrorReturn(ErrorDefs.ObjectNotExist).response result = dict(account=user.account, name=user.name, avatar=user.avatar, mobile=user.mobile, email=user.email, address=user.address) return CR(result=result).response
def init_innerbox(): """室内机设备请求运行参数""" ip = request.remote_addr.split(':')[-1] box = model.InnerBox.get(ip=ip) # 根据ip检查设备是否登记 if not box: return ErrorReturn(ErrorDefs.ObjectNotExist, u'室内主机未登记') box.login_time = datetime.datetime.now() box.save() data = {} garden = model.HomeGarden.get(id='8888') data['propcenter_ip'] = garden.property_call_server data['net_ip'] = ip data['family_ip'] = '' data['room_id'] = box.room_id sentry_list = [] rs = model.SentryApp.find(garden_id=garden.id) for _ in rs: sentry_list.append(dict(name=_.name, ip=_.ip)) outerbox_list = [] rs = model.OuterBox.find(garden_id=garden.id, building_id=box.building_id) for _ in rs: outerbox_list.append( dict(type='B', name=_.name, ip=_.ip, is_primary=_.is_primary, floor=_.floor)) rs = model.OuterBox.find(garden_id=garden.id, type='A') # 围墙机 for _ in rs: outerbox_list.append( dict(type='A', name=_.name, ip=_.ip, is_primary=_.is_primary, floor=_.floor)) data['sentry_list'] = sentry_list data['outerbox_list'] = outerbox_list result = data return CR(result=result)