def get(self): search = self.request.get('query') results = Course.find_with_partial_title(search) obj = { 'courses': map(lambda x: x.as_json(), results) } render_json(self, obj=obj)
def get_task_info(request, tid): """ 获取任务详情 :param request: :return: """ try: task = Task.objects.get(pk=tid) except Exception as e: logger.error(u"获取项目信息失败", e) return render_json({'result': False, 'message': u"获取项目信息失败"}) try: project = Project.objects.get(pk=task.project_id) project_name = project.name pid = project.pk except Exception as e: project_name = '' pid = '' task_part = task.participant.split(',') data = {} data.update({ 'tid': tid, 'pid': pid, 'task_name': task.name, 'project_name': project_name, 'task_intro': task.introduction, 'task_part': task_part, 'task_begintime': task.begin_time.strftime('%Y-%m-%d'), 'task_finishtime': task.finish_time.strftime('%Y-%m-%d'), 'task_level': task.level, 'task_status': task.status }) return render_json({'result': True, 'data': data})
def get_project_user(request): """ 获取项目所有用户 :param request: :return: """ pid = request.GET.get('pid', '') try: project = Project.objects.get(pk=pid) except Exception as e: logger.error(u"获取项目用户列表失败", e) return render_json({'result': False}) uids = project.participant.split(",") uids.append(project.owner) # 获取所有用户 user_info = get_all_users(request) user_list = [] # 过滤出当前项目下的用户 for uid in uids: user = user_info[int(uid)] name = user['name'] # for id, user in user_info.items(): user_list.append({'id': uid, 'text': name}) return render_json({'result': True, 'message': user_list})
def get_all_task(request): """ 获取所有任务 :param request: :return: """ try: tasks = Task.objects.get_all_task() except Exception as e: logger.error(u"获取任务失败", e) return render_json({'result': False, 'message': u"获取任务失败"}) users = get_users(request) data = [] for task in tasks: # 获取用户名 participant = task.participant.split(',') user_name = [] for id in participant: user = users[int(id)] user_name.append(user['name']) data.append({ 'task_name': task.name, 'task_introduction': task.introduction, 'task_participant': user_name, 'task_create_time': task.create_time.strftime('%Y-%m-%d'), 'task_finish_time': task.finish_time.strftime('%Y-%m-%d'), 'task_status': STATUS_CHOICES[int(task.status)], 'level': LEVEL[int(task.level)], }) return render_json({'result': True, 'data': data})
def update_project_info(request): """ 更新项目信息 :param request: :return: """ name = request.POST.get('pro_name', '') introduction = request.POST.get('pro_intro', '') participant = request.POST.get('pro_part', '') img = request.FILES.get('pro_img', '') pid = request.POST.get('pid', '') # 获取项目当前信息 try: project = Project.objects.filter(pk=pid) except Exception as e: logger.error(u"获取项目失败", e) return render_json({'result': False, 'message': u'获取项目失败'}) if not name: return render_json({'result': False, 'message': u'项目名不能为空'}) if img: import os try: # 根据时间戳存储图片 now = int(time.time()) ext = img.name.split('.')[-1] img_first_name = '.'.join(img.name.split('.')[:-1]) img_name = img_first_name + str(now) img_full_name = img_name + '.' + ext img_path = os.path.join(os.path.dirname(__file__), 'static/images/app/', img_full_name) with open(img_path, 'wb') as f: for item in img.chunks(): f.write(item) except Exception as e: logger.error(u'图片写入失败', e) return render_json({'result': False, 'message': u'图片写入失败'}) else: # 原先背景图 img_path = project[0].logo.split('/')[-1] img_full_name = img_path try: project.update(name=name, introduction=introduction, participant=participant, logo='/static/images/app/' + img_full_name) except Exception as e: logger.error(u"修改项目信息失败", e) return render_json({'result': False, 'message': u"修改项目信息失败"}) # 生成项目动态 content = request.session['name'] + u"修改了项目信息" title = u"项目信息修改" create_dynamic(request=request, pid=pid, content=content, title=title) return render_json({'result': True, 'message': u"项目信息修改成功"})
def file_upload(): """ 文件上传 :return: """ file = request.files.get('file') print(file.filename) if file.filename == '4.JPG': return render_json(MyResponse('上传成功', code='22')) return render_json(MyResponse('上传成功'))
def post(self): """ Add a user to a course Note: Does not use the decorator, because the user does not belong to the course yet """ course_token = self.request.get('key') course = Course.find_with_key(course_token) self.auth.user.add_course(course) render_json(self)
def create_project(request): """ 创建项目 :param request: :return: """ name = request.POST.get('pro_name', '') introduction = request.POST.get('pro_intro', '') participant = request.POST.get('pro_part', '') img = request.FILES.get('pro_img', '') if not name: return render_json({'result': False, 'message': u'项目名不能为空'}) if img: import os try: # 根据时间戳存储图片 now = int(time.time()) ext = img.name.split('.')[-1] img_first_name = '.'.join(img.name.split('.')[:-1]) img_name = img_first_name + str(now) img_full_name = img_name + '.' + ext img_path = os.path.join(os.path.dirname(__file__), 'static/images/app/', img_full_name) with open(img_path, 'wb') as f: for item in img.chunks(): f.write(item) except Exception as e: logger.error(u'图片写入失败', e) return render_json({'result': False, 'message': u'图片写入失败'}) else: # 默认背景图 img_full_name = 'cover-internet.jpg' try: project = Project.objects.create_project(request=request, name=name, introduction=introduction, participant=participant, logo='/static/images/app/' + img_full_name) except Exception as e: logger.error(u"创建项目失败", e) return render_json({'result': False, 'message': u"创建项目失败"}) # 生成项目动态 content = request.session['name'] + u"创建了项目" title = u"创建项目" create_dynamic(request=request, pid=project.pk, content=content, title=title) return render_json({'result': True, 'message': u"创建项目成功"})
def post(self): results = {} try: body = json.loads(self.request.body) search = TripSearch() utils.setattrs(search, body) search.put() results = search.to_dict() except ValueError: results = {'message': 'an error occured'} utils.render_json(self, results)
def delete_file(request): """ 删除文件 :param request: :return: """ fid = request.POST.get('fid', '') try: ProjectFile.objects.filter(pk=fid).update(is_active=False) except Exception as e: logger.error(u"删除文件失败", e) return render_json({'result': False, 'message': u"删除文件失败"}) return render_json({'result': True})
def quit(): motor.stop() state = device_state.loads() state['motor_running'] = False # hue.set_light(False, bri=0) calculated_bri.reset() return render_json(state)
def get_project_file(request, pid): """ 获取项目下文件 :param request: :return: """ # 获取所有用户 user_info = get_all_users(request) files = ProjectFile.objects.filter(project_id=pid) file_list = [] for file in files: user = user_info[int(file.user)] name = user['name'] ext = file.path.split('.')[-1] file_list.append({ 'fid': file.pk, 'name': file.name, 'size': file.size, 'user': name, 'path': file.path, 'ext': ext, 'create_time': file.create_time.strftime('%Y-%m-%d') }) return render_json({'result': True, 'data': file_list})
def post(self): results = [] if self.request.body: body = json.loads(self.request.body) search = {} if body.has_key('origin') and body.has_key('destination'): search['origin'] = body['origin'] search['destination'] = body['destination'] search['date'] = body['date'] if body.has_key('date') else str(datetime.date.today()) search['places'] = body['places'] if body.has_key('places') else 1 search_results = TripSearch.find_offers(search) for result in search_results: results.append(result.to_dict()) utils.render_json(self, results)
def update_task_user(request): """ 更新任务用户 :param request: :return: """ task_id = 1 participant = '14,12' try: info = Task.objects.update_task_user(task_id=task_id, participant=participant) except Exception as e: logger.error(u"更新任务用户信息失败", e) return render_json({'result': False, 'message': u'更新任务用户信息失败'}) return render_json({'result': True, 'message': u"更新任务用户信息成功"})
def change_user_info(request): """ 修改用户信息 :param request: :return: """ name = request.POST.get('name', '') email = request.POST.get('email', '') phone = request.POST.get('phone', '') job = request.POST.get('job', '') workplace = request.POST.get('workplace', '') qq = request.POST.get('qq', '') wechat = request.POST.get('wechat', '') m = re.match(r'^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$', email) if not m: return render_json({'result': False, 'message': u'请检查邮箱格式'}) p = re.match(r'^1[34578]\d{9}$', phone) if not p: return render_json({'result': False, 'message': u'请检查手机号格式'}) payload = { 'access_token': request.session['token'], 'name': name, 'phone': phone, 'qq': qq, 'email': email, 'job': job, 'workplace': workplace, 'wechat': wechat } try: res = requests.put('https://api.xiyoulinux.org/users/' + str(request.session['id']), data=payload) user_msg = json.loads(res.text) if 'error' in user_msg: message = u'更新用户信息失败' return render_json({'result': False, 'message': message}) # 刷新session信息 refresh_user_session(request, user_msg) except Exception as e: logger.error(u'更新用户信息失败', e) return render_json({'result': False, 'message': u'更新用户信息失败'}) return render_json({'result': True, 'data': user_msg})
def delete(self): results = {} try: body = json.loads(self.request.body) if body.has_key('id'): search = TripSearch.get_by_id(body['id']) if search: search.key.delete() results = {'message': 'deleted'} else: results = {'message': 'search not found'} else: results = {'message': 'id not received'} except ValueError: results = {'message': 'an error occured'} utils.render_json(self, results)
def put(self): results = {} try: body = json.loads(self.request.body) if body.has_key('id'): search = TripSearch.get_by_id(body['id']) if search: utils.setattrs(search, body) search.put() results = search.to_dict() else: results = {'message': 'search not found'} else: results = {'message': 'id not received'} except ValueError: results = {'message': 'an error occured'} utils.render_json(self, results)
def update_task_info(request): """ 更改任务信息 :param request: :return: """ tid = request.POST.get('tid', '') introduction = request.POST.get('intro', '') participant = request.POST.get('part', '') finish_time = request.POST.get('finish_time', '') begin_time = request.POST.get('begin_time', '') level = request.POST.get('level', '') project_id = request.POST.get('pid', '') status = request.POST.get('status', '') if not finish_time: finish_time = datetime.datetime.now() if not begin_time: begin_time = datetime.datetime.now() if status == 'true': task_status = 2 else: task_status = 0 try: task = Task.objects.filter(pk=tid) task.update(introduction=introduction, participant=participant, begin_time=begin_time, finish_time=finish_time, level=level, status=task_status) except Exception as e: logger.error(u'更新任务信息失败', e) return render_json({'result': False, 'messgae': u'更新任务信息失败'}) # 生成项目动态 content = request.session['name'] + u"更新了任务信息——" + task[0].name title = u"更新任务信息" create_dynamic(request=request, pid=project_id, content=content, title=title) return render_json({'result': True, 'message': u"更新任务信息成功"})
def get_gantt_project(request, pid): """ 获取项目gantt图数据 :param request: :return: """ # 获取所有用户 user_info = get_all_users(request) try: tasks = Task.objects.filter(project_id=pid).filter(status=0) except Exception as e: logger.error(u"获取项目甘特图失败", e) return render_json({"result": False}) COLORS = ['ganttRed', "ganttGreen", "ganttBlue", "ganttOrange"] data = [] for task in tasks: user_names = [] for id in task.participant.split(','): user = user_info[int(id)] user_names.append(user['name']) begin = "/Date(" + str( int(time.mktime(task.begin_time.timetuple()) * 1000)) + ")/" finish = "/Date(" + str( int(time.mktime(task.finish_time.timetuple()) * 1000)) + ")/" data.append({ 'name': task.name, "desc": task.introduction, "values": [{ "id": task.pk, "from": begin, "to": finish, "label": (",").join(user_names), "customClass": COLORS[task.pk % len(COLORS)] }] }) if not data: empty = True else: empty = False return render_json({'result': True, 'data': data, 'empty': empty})
def create_task(request): """ 创建任务 :param request: :return: """ name = request.POST.get('name', '') introduction = request.POST.get('intro', '') participant = request.POST.get('part', '') finish_time = request.POST.get('finish_time', '') begin_time = request.POST.get('begin_time', '') level = request.POST.get('level', '') project_id = request.POST.get('pid', '') if not name: return render_json({'result': False, 'message': u'任务名不能为空'}) if not finish_time: finish_time = datetime.datetime.now() if not begin_time: begin_time = datetime.datetime.now() try: task = Task.objects.create_task(request=request, name=name, introduction=introduction, participant=participant, begin_time=begin_time, finish_time=finish_time, level=level, project_id=project_id) except Exception as e: logger.error(u'创建任务失败', e) return render_json({'result': False, 'messgae': u'创建任务失败'}) # 生成项目动态 content = request.session['name'] + u"创建了一条任务——" + name title = u"任务创建" create_dynamic(request=request, pid=project_id, content=content, title=title) return render_json({'result': True, 'message': u"创建任务成功"})
def run_report(request, object_id, output_format='html'): obj = get_object_or_404(ReportRun, pk=object_id) result = obj.run() if output_format == 'html': return render_to_response( 'scorecard_processor/reportrun_run.html', {'object':obj, 'report':result}, RequestContext(request) ) else: return render_json({'data':result,'report':obj})
def get_all_user(request): """ 获取出当前用户外所有用户 :param request: :return: """ user_info = get_users(request) user_list = [] for id, user in user_info.items(): user_list.append({'id': id, 'text': user['name']}) return render_json({'result': True, 'message': user_list})
def delete_project(request): """ 删除项目 :param request: :return: """ pid = request.POST.get('pid', '') try: project = Project.objects.filter(pk=pid).update(is_active=False) except Exception as e: logger.error(u"删除项目失败", e) return render_json({'result': False, 'message': u"删除项目失败"}) # 将任务表中项目相关的任务标记为删除 try: tasks = Task.objects.filter(project_id=pid).update(is_active=False) except Exception as e: logger.error(u"更改任务状态失败", e) return render_json({'result': False, 'message': u"删除项目失败"}) return render_json({'result': True, 'message': u"删除项目成功"})
def get_all_project(request): """ 获取所有项目 :param request: :return: """ try: projects = Project.objects.get_all_project() except Exception as e: logger.error(u"获取项目失败", e) return render_json({'result': False, 'message': u"获取项目失败"}) data = [] for project in projects: data.append({ 'project_name': project.name, 'project_introduction': project.introduction, 'project_owner': project.owner, 'project_participant': project.participant, 'logo': project.logo }) return render_json({'result': True, 'data': data})
def delete_task(request): """ 删除任务 :param request: :return: """ tid = request.POST.get('tid', '') try: task = Task.objects.get(pk=tid) count = Task.objects.delete_task(tid=tid) except Exception as e: logger.error(u"删除任务失败", e) return render_json({'result': False, 'message': u"删除任务失败"}) # 生成项目动态 content = request.session['name'] + u"删除了一条任务——" + task.name title = u"删除任务" create_dynamic(request=request, pid=task.project_id, content=content, title=title) return render_json({'result': True, 'message': u"删除任务成功"})
def control_stop(): try: desired = float(request.args.get('desired')) current = float(request.args.get('current')) weight = float(request.args.get('weight')) desired = calculated_bri.write(desired, weight) diff = desired - current print '>> current: %d, desired: %d, diff: %d' % (current, desired, diff) log_data(current, desired) except Exception as e: print e state = device_state.loads() state['motor_running'] = False motor.stop() return render_json(state)
def get(self, *args, **kwargs): results = None user = users.get_current_user() if user: results = { 'user': { 'nickname': user.nickname(), 'email': user.email() }, 'url': users.create_login_url(self.request.path) } else: results = { 'user': None, 'url': users.create_logout_url(self.request.path) } return utils.render_json(self, results)
def paydetail(request): """获取支付信息""" if "openid" in request.session: openid = request.session["openid"] print "openid " + str(openid) # money = request.POST.get("money") or "0.01" # money = int(float(money) * 100) jsApi = JsApi_pub() unifiedOrder = UnifiedOrder_pub() unifiedOrder.setParameter("openid", openid) # openid unifiedOrder.setParameter("body", "商品购买") # 商品描述 order_id = request.REQUEST.get("order_id", "") order = MyOrder.objects.get(pk=order_id) # timeStamp = time.time() # out_trade_no = "{0}{1}".format(WxPayConf_pub.APPID, int(timeStamp * 100)) out_trade_no = order.out_trade_no if out_trade_no == "": # 订单编号 32 位,由14位长度 time_str + 18位长度的随机数字 time_str = generate_trade_time() nonce_str = generate_nonce_str(size=18, chars=string.digits) out_trade_no = time_str + nonce_str order.out_trade_no = out_trade_no order.save() # 总金额:商品金额+运费 payment_amount = order.order_subtotal payment_amount = int(float(payment_amount) * 100) unifiedOrder.setParameter("out_trade_no", str(out_trade_no)) # 商户订单号 unifiedOrder.setParameter("total_fee", str(payment_amount)) # 总金额 unifiedOrder.setParameter("notify_url", WxPayConf_pub.NOTIFY_URL) # 通知地址 unifiedOrder.setParameter("trade_type", "JSAPI") # 交易类型 # unifiedOrder.setParameter("attach", "6666") #附件数据,可分辨不同商家(string(127)) try: prepay_id = unifiedOrder.getPrepayId() jsApi.setPrepayId(prepay_id) jsApiParameters = jsApi.getParameters() except Exception as e: print (e) else: print jsApiParameters return HttpResponse(jsApiParameters) else: return render_json({"error": "no openid found"})
def get(self, *args, **kwargs): results = [] if args and len(args) == 2: try: searchId = int(args[1]) except ValueError: utils.render_json(self, {'error': 'invalid search'}) return search = TripSearch.get_by_id(searchId) if search: results = search.to_dict() else: utils.render_json(self, {'error': 'search not found'}) return else: searchs = TripSearch.query() results = [] for search in searchs: results.append(search.to_dict()) utils.render_json(self, results)
def lights_on(light_id): hue.set_light(True, light_id) return render_json({'light': light_id, 'state': 'on'}, code=201)
def task_index(request): """ 用户任务首页 :param request: :return: """ uid = request.session['id'] # 获取所用用户信息 users = get_all_users(request) try: nofinish_tasks = Task.objects.filter(status=0).filter( owner=uid).order_by('-level') finish_tasks = Task.objects.filter(status=2).filter( owner=uid).order_by('-level') except Exception as e: logger.error(u"查询任务失败", e) return render_json({'result': False}) unfinish_task = [] # 未完成任务 for tasks in nofinish_tasks: if str(request.session['id']) in tasks.participant.split(','): name = tasks.name finish_time = tasks.finish_time.strftime('%Y-%m-%d') owner = tasks.owner user = users[int(owner)] avatar = user['avatar'] level = tasks.level tid = tasks.pk unfinish_task.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid }) finish_task = [] # 已完成任务 for tasks in finish_tasks: if str(request.session['id']) in tasks.participant.split(','): name = tasks.name finish_time = tasks.finish_time.strftime('%Y-%m-%d') owner = tasks.owner user = users[int(owner)] avatar = user['avatar'] level = tasks.level tid = tasks.pk finish_task.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid }) task_today = [] # 今日任务 for task in nofinish_tasks: if checkTime(task.begin_time, task.finish_time): name = task.name finish_time = task.finish_time.strftime('%Y-%m-%d') owner = task.owner user = users[int(owner)] avatar = user['avatar'] level = task.level tid = task.pk task_today.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid, 'is_finish': False }) for task in finish_tasks: if checkTime(task.begin_time, task.finish_time): name = task.name finish_time = task.finish_time.strftime('%Y-%m-%d') owner = task.owner user = users[int(owner)] avatar = user['avatar'] level = task.level tid = task.pk task_today.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid, 'is_finish': True }) return render( request, 'task_user.html', { 'finish_task': finish_task, 'unfinish_task': unfinish_task, 'today_task': task_today })
def get_project_task(request, pid): """ 获取项目下的任务 :param request: :return: """ # 获取所用用户信息 users = get_all_users(request) try: nofinish_tasks = Task.objects.get_task_pid_unfinish(pid=pid) finish_tasks = Task.objects.get_task_pid_finish(pid=pid) except Exception as e: logger.error(u"查询任务失败", e) return render_json({'result': False}) unfinish_task = [] # 未完成任务 for tasks in nofinish_tasks: name = tasks.name finish_time = tasks.finish_time.strftime('%Y-%m-%d') owner = tasks.owner user = users[int(owner)] avatar = user['avatar'] level = tasks.level tid = tasks.pk unfinish_task.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid }) finish_task = [] # 已完成任务 for tasks in finish_tasks: name = tasks.name finish_time = tasks.finish_time.strftime('%Y-%m-%d') owner = tasks.owner user = users[int(owner)] avatar = user['avatar'] level = tasks.level tid = tasks.pk finish_task.append({ 'name': name, 'finish_time': finish_time, 'avatar': avatar, 'level': level, 'tid': tid }) # 获取项目动态 dynamic_list = [] dynamics = get_project_dynamic(request=request, pid=pid) for dynamic in dynamics: owner = dynamic.sender_id user = users[int(owner)] avatar = user['avatar'] dynamic_list.append({ 'content': dynamic.content, 'title': dynamic.title, 'create_time': dynamic.create_time.strftime('%Y-%m-%d'), 'avatar': avatar }) # 获取项目信息 try: project = Project.objects.get(pk=pid) except Exception as e: logger.error(u"获取项目信息失败", e) finish_task = [] unfinish_task = [] dynamic_list = [] project = {} project_info = {} project_info['project_name'] = project.name project_info['project_intro'] = project.introduction project_info['project_user'] = project.participant project_info['project_logo'] = project.logo if str(request.session['id']) == str(project.owner): project_owner = True else: project_owner = False return render( request, 'task_project.html', { 'pid': pid, 'project_owner': project_owner, 'finish_task': finish_task, 'unfinish_task': unfinish_task, 'dynamic_list': dynamic_list, 'project_info': project_info })
def upload_project_file(request): """ 上传项目文件 :param request: :return: """ # 获取所有用户 user_info = get_all_users(request) file = request.FILES.get('file', '') pid = request.POST.get('pid', '') name = file.name user = request.session['id'] import os try: # 根据时间戳存储文件 now = int(time.time()) ext = file.name.split('.')[-1] file_first_name = '.'.join(file.name.split('.')[:-1]) file_name = file_first_name + str(now) file_full_name = file_name + '.' + ext file_path = os.path.join(os.path.dirname(__file__), 'static/appfile/', file_full_name) with open(file_path, 'wb') as f: for item in file.chunks(): f.write(item) except Exception as e: logger.error(u'文件写入失败', e) return render_json({'result': False, 'message': u'文件写入失败'}) # 获取文件大小 try: size = os.path.getsize(file_path) new_size = formatSize(size) except Exception as e: logger.error(u"获取文件大小失败", e) return render_json({'result': False, 'message': u"获取文件大小失败"}) try: file = ProjectFile.objects.create(project_id=pid, name=name, user=user, size=new_size, path='static/appfile/' + file_full_name) except Exception as e: logger.error(u"上传文件失败", e) return render_json({'result': False, 'message': u"上传文件失败"}) file_list = [] user = user_info[int(file.user)] name = user['name'] ext = file.path.split('.')[-1] file_list.append({ 'fid': file.pk, 'name': file.name, 'size': file.size, 'user': name, 'path': file.path, 'ext': ext, 'create_time': file.create_time.strftime('%Y-%m-%d') }) return render_json({'result': True, 'data': file_list})
def test(request): json_data = {} return render_json(json_data)
def lights_off(light_id): hue.set_light(False, light_id) return render_json({'light': light_id, 'state': 'off'}, code=201)
def hello(): return render_json('hello')
def control(): try: desired = float(request.args.get('desired')) current = float(request.args.get('current')) weight = float(request.args.get('weight')) except Exception as e: print e return u'Invalid parameters' state = device_state.loads() print '-' * 80 print state print '-' * 80 desired = calculated_bri.write(desired, weight) diff = desired - current print '>> current: %d, desired: %d, diff: %d' % (current, desired, diff) log_data(current, desired) # if is_night(): if 0: print '>> nighttime' # curtain is still open if current > THRESHOLD and not curtain.is_closed(): # hue.set_light(False, bri=0) print '>> curtain is still open' motor.run_ccw() print '>> night: motor down' state['motor_running'] = True state['motor_dir'] = 'down' state['curtain'] = 'closed' curtain.set_closed() # if current < CURTAIN_MIN: # motor.stop() # curtain.set_closed() # state['curtain'] = 'closed' # state['motor_running'] = False # state['motor_dir'] = '' # curtain is closed else: print '>> curtain is closed' light_state = hue.get_light() if light_state['on']: current_light = light_state['bri'] print '>> bri: %d' % (current_light) bri = hue.change(diff, current_light) else: bri = MAX_LIGHT / 4 hue.set_light(True, bri=bri) state['light'] = True state['bri'] = bri return render_json(state) else: print '>> daytime' # if curtain is open, but still needs light if curtain.is_open(): print '>> fully open' light_state = hue.get_light() # if light is on if light_state['on']: current_light = light_state['bri'] bri = hue.change(diff, current_light) # closes curtain if bri == 0: print '>> bri: 0, turn off light' hue.set_light(False, bri=bri) state['light'] = False state['bri'] = bri motor.run_ccw() state['motor_running'] = True state['motor_dir'] = 'down' state['curtain'] = '' curtain.clear_open() return render_json(state) else: bri = MAX_LIGHT / 2 hue.set_light(True, bri=bri) state['light'] = True state['bri'] = bri print '>> bri: ', bri return render_json(state) # if curtain is not fully open else: print '>> not fully open' hue.set_light(False, bri=0) state['light'] = False state['bri'] = 0 # if needs motor up (more light): desired > current if diff > 0 and abs(diff) > THRESHOLD: current = int(current) # previous_max = curtain.log_max(current) # # if brightness does not increase, we assume the curtain fully open # if previous_max - current_int < THRESHOLD: # curtain.set_open() # if curtain is opening if state['motor_dir'] != 'down' and current > CURTAIN_MAX: curtain.set_open() motor.stop() state['curtain'] = 'open' state['motor_running'] = False state['motor_dir'] = '' else: motor.run_cw() print '>> motor up' state['motor_dir'] = 'up' state['motor_running'] = True state['curtain'] = '' curtain.clear_closed() return render_json(state) # if needs motor down if diff < 0 and abs(diff) > THRESHOLD: print '>> motor down' motor.run_ccw() state['motor_dir'] = 'down' state['motor_running'] = True curtain.clear_open() state['curtain'] = '' # if no light, set curtain state as closed if not state['light'] and current < CURTAIN_MIN: motor.stop() curtain.set_closed() state['curtain'] = 'closed' state['motor_running'] = False state['motor_dir'] = '' return render_json(state) # stops the motor else: motor.stop() state['motor_running'] = False state['motor_dir'] = '' if current < CURTAIN_MIN: state['curtain'] = 'closed' return render_json(state)
def to_json(self): return render_json(self.to_simple())
def motor_start_ccw(): motor.run_ccw() state = device_state.loads() state['motor_running'] = True state['motor_dir'] = 'down' return render_json(state)