diff options
author | CruiseDevice | 2018-02-19 15:01:22 +0530 |
---|---|---|
committer | CruiseDevice | 2018-02-19 15:01:22 +0530 |
commit | b84648fa3730d8b258bbc4ada0dcbde5a033f747 (patch) | |
tree | d97bfe8f70e43a58a2d7f8fe7a61a00554ba4f14 /myadmin | |
parent | 6f76f85bc264a58cea717ca8f8bd60b411828dd5 (diff) | |
download | SBHS-2018-Rpi-b84648fa3730d8b258bbc4ada0dcbde5a033f747.tar.gz SBHS-2018-Rpi-b84648fa3730d8b258bbc4ada0dcbde5a033f747.tar.bz2 SBHS-2018-Rpi-b84648fa3730d8b258bbc4ada0dcbde5a033f747.zip |
initial commit
Diffstat (limited to 'myadmin')
-rw-r--r-- | myadmin/.views.py.swp | bin | 0 -> 1024 bytes | |||
-rw-r--r-- | myadmin/urls-no-pwr.py | 25 | ||||
-rw-r--r-- | myadmin/urls.py | 14 | ||||
-rw-r--r-- | myadmin/views-no-pwr.py | 334 | ||||
-rw-r--r-- | myadmin/views.py | 199 | ||||
-rw-r--r-- | myadmin/views.py.save | 431 | ||||
-rw-r--r-- | myadmin/views.py.save.1 | 666 |
7 files changed, 1649 insertions, 20 deletions
diff --git a/myadmin/.views.py.swp b/myadmin/.views.py.swp Binary files differnew file mode 100644 index 0000000..e524746 --- /dev/null +++ b/myadmin/.views.py.swp diff --git a/myadmin/urls-no-pwr.py b/myadmin/urls-no-pwr.py new file mode 100644 index 0000000..7272f79 --- /dev/null +++ b/myadmin/urls-no-pwr.py @@ -0,0 +1,25 @@ +from django.conf.urls import url + +from . import views + +urlpatterns = [ + url(r'^admin/?$', views.index, name='admin_index'), + url(r'^admin/bookings/?$', views.booking_index, name='admin_bookings'), + url(r'^admin/webcam/?$', views.webcam_index, name='admin_webcam'), + url(r'^admin/viewlogs/?$', views.logs_index, name='admin_viewlogs'), + url(r'^admin/profile/([0-9]+)/?$', views.profile, name='admin_profile'), + url(r'^admin/testing/?$', views.testing, name='admin_testing'), + url(r'^admin/resetdevice/?$', views.reset_device, name='admin_reset_device'), + url(r'^admin/setdevice/?$', views.set_device_params, name='admin_set_device'), + url(r'^admin/gettemp/?$', views.get_device_temp, name='admin_get_temp'), + url(r'^admin/monitor/?$', views.monitor_experiment, name='admin_monitor'), + url(r'^admin/logs/([0-9]+)/?$', views.download_log, name='admin_logs'), + url(r'^admin/updatemid/?$', views.update_allocated_mid, name='admin_updatemid'), + url(r'^admin/changemid/?$', views.get_allocated_mids, name='admin_getmids'), + url(r'^admin/getusers/?$', views.get_users, name='admin_users'), + url(r'^admin/toggledevice', views.toggle_device_status, name='toggle_status'), + url(r'^admin/rangelogs/?$', views.range_logs, name='admin_range_logs'), + url(r'^admin/explogs/([0-9]+)/?$', views.download_experiment_log, name='admin_explogs'), + + url(r'^admin/toggle_allotment_mode/?$', views.toggle_allotment_mode, name='admin_toggle_allotment_mode'), +] diff --git a/myadmin/urls.py b/myadmin/urls.py index 7272f79..0bf89bf 100644 --- a/myadmin/urls.py +++ b/myadmin/urls.py @@ -4,9 +4,9 @@ from . import views urlpatterns = [ url(r'^admin/?$', views.index, name='admin_index'), + url(r'^admin/bookings/?$', views.booking_index, name='admin_bookings'), - url(r'^admin/webcam/?$', views.webcam_index, name='admin_webcam'), - url(r'^admin/viewlogs/?$', views.logs_index, name='admin_viewlogs'), + url(r'^admin/webcam/?$', views.webcam_index, name='admin_webcam'), url(r'^admin/profile/([0-9]+)/?$', views.profile, name='admin_profile'), url(r'^admin/testing/?$', views.testing, name='admin_testing'), url(r'^admin/resetdevice/?$', views.reset_device, name='admin_reset_device'), @@ -18,6 +18,16 @@ urlpatterns = [ url(r'^admin/changemid/?$', views.get_allocated_mids, name='admin_getmids'), url(r'^admin/getusers/?$', views.get_users, name='admin_users'), url(r'^admin/toggledevice', views.toggle_device_status, name='toggle_status'), + url(r'^admin/togglePowerState',views.toggle_power_state,name='toggle_power_state'), + + url(r'^admin/viewlogs/?$', views.logs_index, name='admin_viewlogs'), + url(r'^admin/viewlogsfolder/?$',views.logs_folder_index,name='admin_viewlogfolders'), + + url(r'^admin/switchOnAllBoards/?$',views.switch_on_all_boards,name='admin_switch_on'), + url(r'^admin/switchOffAllBoards/?$',views.switch_off_all_boards,name="admin_switch_off"), + + url(r'^admin/automatedSlotbooking/$',views.automated_slot_booking, name="atomated_slot_booking"), + url(r'^admin/rangelogs/?$', views.range_logs, name='admin_range_logs'), url(r'^admin/explogs/([0-9]+)/?$', views.download_experiment_log, name='admin_explogs'), diff --git a/myadmin/views-no-pwr.py b/myadmin/views-no-pwr.py new file mode 100644 index 0000000..4c6ccce --- /dev/null +++ b/myadmin/views-no-pwr.py @@ -0,0 +1,334 @@ +from django.shortcuts import render, redirect +from django.http import Http404,HttpResponse +from django.contrib.auth.decorators import login_required +from django.views.decorators.csrf import csrf_exempt +from django.db.models import Count +from django.db import connection +from django.core.exceptions import ObjectDoesNotExist +from sbhs_server.tables.models import Board, Booking, Slot, Experiment, Account, Webcam +from sbhs_server import settings,sbhs +import subprocess,json,serial,os, datetime, requests +# Create your views here. + +def checkadmin(req): + """ Checks for valid admin + Raises Http error if: + Requested user is not admin. + Input: s: request object. + Output: HttpResponse + """ + if not req.user.is_admin: + raise Http404 + +@login_required(redirect_field_name=None) +def index(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/index.html', {"boards": boards, "allotment_mode": allotment_mode}) + +@login_required(redirect_field_name=None) +def toggle_allotment_mode(req): + checkadmin(req) + Board.toggle_random_allotment() + return redirect(index) + +@login_required(redirect_field_name=None) +def booking_index(req): + checkadmin(req) + bookings = Booking.objects.order_by('-booking_date','-slot_id').filter(trashed_at__isnull=True).select_related()[:50] + return render(req, 'admin/booking_index.html', {"bookings": bookings}) + +@login_required(redirect_field_name=None) +def webcam_index(req): + checkadmin(req) + boards = Board.objects.filter(online=True) + for board in boards: + Webcam.load_image(board.mid) + return render(req, 'admin/webcam_index.html', {"boards": boards}) + +@login_required(redirect_field_name=None) +def logs_index(req): + checkadmin(req) + date = (datetime.datetime.now()).strftime("%Y-%m-%d") + return render(req, 'admin/user_logs.html', {"nowdate" : date}) + +@login_required(redirect_field_name=None) +def profile(req, mid): + checkadmin(req) + try: + filename = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(filename, "r") + f.close() + except: + raise Http404 + + delta_T = 1000 + data = subprocess.check_output("tail -n %d %s" % (delta_T, filename), shell=True) + data = data.split("\n") + plot = [] + heatcsv = "" + fancsv = "" + tempcsv = "" + + for t in xrange(len(data)): + line = data[t] + entry = line.strip().split(" ") + try: + plot.append([int(i) for i in entry[0:-1] + [float(entry[-1])]]) + heatcsv += "%d,%s\\n" % (t+1, entry[1]) + fancsv += "%d,%s\\n" % (t+1, entry[2]) + tempcsv += "%d,%s\\n" % (t+1, entry[3]) + except: + continue + + plot = zip(*plot) # transpose + + return render(req, "admin/profile.html", { + "mid": mid, + "delta_T": delta_T, + "heat": heatcsv, + "fan": fancsv, + "temp": tempcsv + }) + +@login_required(redirect_field_name=None) +def testing(req): + checkadmin(req) + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + + boards = Board.objects.filter(online=1) + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/testexp.html', {"boards": boards, "allotment_mode": allotment_mode, "mids": current_mids}) + +@csrf_exempt +def monitor_experiment(req): + checkadmin(req) + try: + mid = int(req.POST.get("mid")) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/monitor" + payload = {"mid":mid} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not fetch device logs.."} + return HttpResponse(json.dumps(retVal),content_type='application/json') + +@login_required(redirect_field_name=None) +def get_allocated_mids(req): + checkadmin(req) + with connection.cursor() as cursor: + cursor.execute("SELECT tables_board.mid, COUNT(tables_account.id), tables_board.id FROM tables_account RIGHT OUTER JOIN tables_board ON tables_account.board_id = tables_board.id WHERE tables_board.online = 1 GROUP BY tables_board.mid ORDER BY COUNT(tables_account.id)") + mid_count = cursor.fetchall() + + return render(req, 'admin/changeMID.html', {"mid_count" : mid_count}) + +@csrf_exempt +def get_users(req): + checkadmin(req) + try: + users = list(Account.objects.select_related().values_list("username", "board__mid")) + return HttpResponse(json.dumps({"status_code":200, "message":users}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":str(e)}), content_type="application/json") + + +@csrf_exempt +def toggle_device_status(req): + checkadmin(req) + + try : + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + + try: + brd = Board.objects.get(mid = mid) + brd.temp_offline = not brd.temp_offline + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":"Unsuccessful"}), content_type="application/json") + + +def user_exists(username): + try: + user = Account.objects.get(username=username) + except ObjectDoesNotExist: + return None + return user + +@csrf_exempt +def update_allocated_mid(req): + checkadmin(req) + try: + username = req.POST.get("username") + board_id = req.POST.get("board_id") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + user = user_exists(username) + if user is not None: + user.board_id = board_id + user.save() + else: + return HttpResponse(json.dumps({"status_code": 400, "message": "Username does not exist"}), content_type="application/json") + + return HttpResponse(json.dumps({"status_code": 200, "message": "MID changed successfully"}), content_type="application/json") + +@login_required(redirect_field_name=None) +def download_log(req, mid): + checkadmin(req) + try: + global_logfile = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(global_logfile, "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.Please Try in the next hour after your slot ends.") + +@login_required(redirect_field_name=None) +@csrf_exempt +def range_logs(req): + checkadmin(req) + try: + start_date = req.POST.get("start_date") + end_date = req.POST.get("end_date") + start_time = req.POST.get("start_time") + end_time = req.POST.get("end_time") + except: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + start = start_date + " " + start_time + end = end_date + " " + end_time + log_files = Experiment.objects.filter(created_at__range=[start, end]).values("id", "log") + + return HttpResponse(json.dumps({"status_code":200, "message":list(log_files)}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code": 500, "message": "Some error occured" + str(e)}), content_type="application/json") + +@login_required(redirect_field_name=None) +@csrf_exempt +def download_experiment_log(req, experiment_id): + """ Downloads the experimental log file. + Input: req: request object, experiment_id: experimental id + Output: HttpResponse object + """ + checkadmin(req) + try: + experiment_data = Experiment.objects.select_related("booking", "booking__account").get(id=experiment_id) + f = open(os.path.join(settings.EXPERIMENT_LOGS_DIR, experiment_data.log), "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.") + +@csrf_exempt +def reset_device(req): + """Resets the device to fan = 100 and heat = 0 + Takes mid as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + checkadmin(req) + mid=int(req.POST.get('mid')) + + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/resetdevice" + payload = {"mid":mid} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not reset the device.."} + return HttpResponse(json.dumps(retVal),content_type='application/json') + + +@csrf_exempt +def set_device_params(req): + """Sets the device parameters as per the arguments sent + Takes mid,fan,heat as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + checkadmin(req) + mid=int(req.POST.get('mid')) + fan=int(req.POST.get('fan')) + heat=int(req.POST.get('heat')) + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/setdevice" + payload = {"mid":mid, "fan":fan, "heat":heat} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not set the device params.."} + return HttpResponse(json.dumps(retVal),content_type='application/json') + +@csrf_exempt +def get_device_temp(req): + """Sets the device parameters as per the arguments sent + Takes mid,fan,heat as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + checkadmin(req) + mid=int(req.POST.get('mid')) + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/gettemp" + payload = {"mid":mid} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not get the device temperature.."+str(e)} + return HttpResponse(json.dumps(retVal),content_type='application/json') diff --git a/myadmin/views.py b/myadmin/views.py index 4c6ccce..2e82773 100644 --- a/myadmin/views.py +++ b/myadmin/views.py @@ -1,14 +1,33 @@ from django.shortcuts import render, redirect -from django.http import Http404,HttpResponse +from django.http import Http404, HttpResponse from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.db.models import Count from django.db import connection from django.core.exceptions import ObjectDoesNotExist from sbhs_server.tables.models import Board, Booking, Slot, Experiment, Account, Webcam -from sbhs_server import settings,sbhs -import subprocess,json,serial,os, datetime, requests +from sbhs_server import settings, sbhs +# from sbhs_server import switch_on, switch_off +import class_based_automated_slot_booking +import subprocess, json, serial, os, datetime, requests, zipfile +import sys, inspect +import time # Create your views here. +from time import gmtime, strftime +import random +import MySQLdb +import datetime + +from sbhs_server import credentials as credentials + +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +parentdir = os.path.dirname(currentdir) +sys.path.insert(0,parentdir) + +import switch_onn, switch_off#, check_future_slots +# ser.close() +ser = serial.Serial('/dev/ttyACM0') + def checkadmin(req): """ Checks for valid admin @@ -53,6 +72,43 @@ def logs_index(req): date = (datetime.datetime.now()).strftime("%Y-%m-%d") return render(req, 'admin/user_logs.html', {"nowdate" : date}) +def zipdir(path, ziph): + # ziph is zipfile handle + for root, dirs, files in os.walk(path): + for file in files: + ziph.write(os.path.join(root,file)) + +@login_required(redirect_field_name=None) +def logs_folder_index(req): + checkadmin(req) + # pass + if os.path.exists('Experiments.zip'): + os.remove('Experiments.zip') + zipf = zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED) + path = settings.BASE_DIR + '/experiments/' + # path = os.path.abspath("/experiments/") + zipdir(path,zipf) + zipf.close() + zip_file = open('Experiments.zip','r') + response = HttpResponse(zip_file, content_type='application/force-download') + response['Content-Disposition'] = 'attachment; filename="%s"' % 'Experiments.zip' + return response + +@login_required(redirect_field_name=None) +def switch_on_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_onn.switchOnn(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + +@login_required(redirect_field_name=None) +def switch_off_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_off.switchOff(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + + @login_required(redirect_field_name=None) def profile(req, mid): checkadmin(req) @@ -61,7 +117,8 @@ def profile(req, mid): f = open(filename, "r") f.close() except: - raise Http404 + # raise Http404("log does not exist for this profile") + return render(req,'admin/log_does_not_exist.html') delta_T = 1000 data = subprocess.check_output("tail -n %d %s" % (delta_T, filename), shell=True) @@ -117,18 +174,44 @@ def monitor_experiment(req): mid = int(req.POST.get("mid")) except Exception as e: return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + try: - ip = settings.pi_ip_map.get(str(mid)) - if ip is None: - return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") - url = "http://" + str(ip) + "/pi/admin/monitor" - payload = {"mid":mid} - r = requests.post(url , data = payload) + current_booking = Booking.objects.get(slot_id=current_slot_id, + booking_date=datetime.date.today(), + account__board__mid=mid) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid MID"}), content_type="application/json") + + try: + current_booking_id, current_user = current_booking.id, current_booking.account.username + + logfile = Experiment.objects.filter(booking_id=current_booking_id).order_by('created_at').reverse()[0].log + except: + return HttpResponse(json.dumps({"status_code":417, "message":"Experiment hasn't started"}), content_type="application/json") - return HttpResponse(r.text, content_type="application/json") + try: + # get last 10 lines from logs + stdin,stdout = os.popen2("tail -n 10 "+logfile) + stdin.close() + logs = stdout.readlines(); stdout.close() + screened_logs = [] + for line in logs: + screened_line = " ".join(line.split()[:4]) + "\n" + screened_logs.append(screened_line) + + logs = "".join(screened_logs) except Exception as e: - retVal={"status_code":500,"message":"Could not fetch device logs.."} - return HttpResponse(json.dumps(retVal),content_type='application/json') + return HttpResponse(json.dumps({"status_code":500, "message":"Some error occured"}), content_type="application/json") + + data = {"user": current_user, "logs": logs} + return HttpResponse(json.dumps({"status_code":200, "message":data}), content_type="application/json") @login_required(redirect_field_name=None) def get_allocated_mids(req): @@ -174,7 +257,6 @@ def toggle_device_status(req): if int(mid) in current_mids: return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") - try: brd = Board.objects.get(mid = mid) brd.temp_offline = not brd.temp_offline @@ -182,8 +264,62 @@ def toggle_device_status(req): return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") except Exception as e: - return HttpResponse(json.dumps({"status_code":500, "message":"Unsuccessful"}), content_type="application/json") + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + +@csrf_exempt +def toggle_power_state(req): + checkadmin(req) + # print 'inside toggle_power_state' + try: + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + try: + now = datetime.datetime.now() + # print 'now', now + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + # print 'currnet_slo' + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + try: + print 'mid', mid.strip() + brd = Board.objects.get(mid = mid) + brd.power_status = not brd.power_status + print ' brd.power_status ',int(brd.power_status) + # sys.argv = mid + # print 'sys.argv ',sys.argv + # ser = serial.Serial('/dev/ttyACM0') + # print switch_on.switchOn(sys.argv) + + if not brd.power_status: + m = str(mid).zfill(2) + print 'N ',m + time.sleep(2) + ser.write(b'N'+str(m)) + # switch_on.switchOn(m) + else: + m = str(mid).zfill(2) + print 'F ',m + time.sleep(2) + ser.write(b'F'+str(m)) + # switch_off.switchOff(sys.argv) + # ser.close() + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") def user_exists(username): try: @@ -212,6 +348,7 @@ def update_allocated_mid(req): @login_required(redirect_field_name=None) def download_log(req, mid): + print 'download log' checkadmin(req) try: global_logfile = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" @@ -220,7 +357,7 @@ def download_log(req, mid): f.close() return HttpResponse(data, content_type='text/text') except: - return HttpResponse("Requested log file doesn't exist.Please Try in the next hour after your slot ends.") + return HttpResponse("Requested log file doesn't exist.") @login_required(redirect_field_name=None) @csrf_exempt @@ -251,9 +388,11 @@ def download_experiment_log(req, experiment_id): Output: HttpResponse object """ checkadmin(req) + print 'download_experiment_log' try: experiment_data = Experiment.objects.select_related("booking", "booking__account").get(id=experiment_id) - f = open(os.path.join(settings.EXPERIMENT_LOGS_DIR, experiment_data.log), "r") + # f = open(experiment_data.log, "r") + f = open(settings.BASE_DIR + '/experiments/' + experiment_data.log,'r') data = f.read() f.close() return HttpResponse(data, content_type='text/text') @@ -310,6 +449,7 @@ def set_device_params(req): retVal={"status_code":500,"message":"Could not set the device params.."} return HttpResponse(json.dumps(retVal),content_type='application/json') + @csrf_exempt def get_device_temp(req): """Sets the device parameters as per the arguments sent @@ -319,16 +459,39 @@ def get_device_temp(req): status_code = 500 , data={error:errorMessage} """ checkadmin(req) + print 'inside get_device_temp function' mid=int(req.POST.get('mid')) + print 'mid',mid try: ip = settings.pi_ip_map.get(str(mid)) + print 'ip',ip if ip is None: return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") url = "http://" + str(ip) + "/pi/admin/gettemp" + print 'url ', url payload = {"mid":mid} + print 'payload',payload r = requests.post(url , data = payload) - + print 'r', r return HttpResponse(r.text, content_type="application/json") except Exception as e: retVal={"status_code":500,"message":"Could not get the device temperature.."+str(e)} return HttpResponse(json.dumps(retVal),content_type='application/json') + + +@login_required(redirect_field_name=None) +def automated_slot_booking(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + auto = class_based_automated_slot_booking.Automated_Slot_Booking() + + auto.SuperUserList() + auto.CurrentBookedAccount() + auto.BookedMidList() + auto.BookSlot() + auto.CloseDb() + + switch_onn.switchOnn(sys.argv) + # check_future_slots.check_future_slots() + # switch_on_all_boards() + return render(req,'admin/index.html',{'boards':boards}) diff --git a/myadmin/views.py.save b/myadmin/views.py.save new file mode 100644 index 0000000..b11ea54 --- /dev/null +++ b/myadmin/views.py.save @@ -0,0 +1,431 @@ +from django.shortcuts import render, redirect +from django.http import Http404, HttpResponse +from django.contrib.auth.decorators import login_required +from django.views.decorators.csrf import csrf_exempt +from django.db.models import Count +from django.db import connection +from django.core.exceptions import ObjectDoesNotExist +from sbhs_server.tables.models import Board, Booking, Slot, Experiment, Account, Webcam +from sbhs_server import settings, sbhs +# from sbhs_server import switch_on, switch_off +import class_based_automated_slot_booking +import subprocess, json, serial, os, datetime, requests, zipfile +import sys, inspect +import time +# Create your views here. +from time import gmtime, strftime +import random +import MySQLdb +import datetime + +from sbhs_server import credentials as credentials + +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +parentdir = os.path.dirname(currentdir) +sys.path.insert(0,parentdir) + +import switch_onn, switch_off#, check_future_slots +# ser.close() +ser = serial.Serial('/dev/ttyACM0') + + +def checkadmin(req): + """ Checks for valid admin + Raises Http error if: + Requested user is not admin. + Input: s: request object. + Output: HttpResponse + """ + if not req.user.is_admin: + raise Http404 + +@login_required(redirect_field_name=None) +def index(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/index.html', {"boards": boards, "allotment_mode": allotment_mode}) + +@login_required(redirect_field_name=None) +def toggle_allotment_mode(req): + checkadmin(req) + Board.toggle_random_allotment() + return redirect(index) + +@login_required(redirect_field_name=None) +def booking_index(req): + checkadmin(req) + bookings = Booking.objects.order_by('-booking_date','-slot_id').filter(trashed_at__isnull=True).select_related()[:50] + return render(req, 'admin/booking_index.html', {"bookings": bookings}) + +@login_required(redirect_field_name=None) +def webcam_index(req): + checkadmin(req) + boards = Board.objects.filter(online=True) + for board in boards: + Webcam.load_image(board.mid) + return render(req, 'admin/webcam_index.html', {"boards": boards}) + +@login_required(redirect_field_name=None) +def logs_index(req): + checkadmin(req) + date = (datetime.datetime.now()).strftime("%Y-%m-%d") + return render(req, 'admin/user_logs.html', {"nowdate" : date}) + +def zipdir(path, ziph): + # ziph is zipfile handle + for root, dirs, files in os.walk(path): + for file in files: + ziph.write(os.path.join(root,file)) + +@login_required(redirect_field_name=None) +def logs_folder_index(req): + checkadmin(req) + # pass + if os.path.exists('Experiments.zip'): + os.remove('Experiments.zip') + zipf = zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED) + zipdir('experiments/',zipf) + zipf.close() + zip_file = open('Experiments.zip','r') + response = HttpResponse(zip_file, content_type='application/force-download') + response['Content-Disposition'] = 'attachment; filename="%s"' % 'Experiments.zip' + return response + +@login_required(redirect_field_name=None) +def switch_on_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_onn.switchOnn(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + +@login_required(redirect_field_name=None) +def switch_off_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_off.switchOff(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + + +@login_required(redirect_field_name=None) +def profile(req, mid): + checkadmin(req) + try: + filename = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(filename, "r") + f.close() + except: + # raise Http404("log does not exist for this profile") + return render(req,'admin/log_does_not_exist.html') + + delta_T = 1000 + data = subprocess.check_output("tail -n %d %s" % (delta_T, filename), shell=True) + data = data.split("\n") + plot = [] + heatcsv = "" + fancsv = "" + tempcsv = "" + + for t in xrange(len(data)): + line = data[t] + entry = line.strip().split(" ") + try: + plot.append([int(i) for i in entry[0:-1] + [float(entry[-1])]]) + heatcsv += "%d,%s\\n" % (t+1, entry[1]) + fancsv += "%d,%s\\n" % (t+1, entry[2]) + tempcsv += "%d,%s\\n" % (t+1, entry[3]) + except: + continue + + plot = zip(*plot) # transpose + + return render(req, "admin/profile.html", { + "mid": mid, + "delta_T": delta_T, + "heat": heatcsv, + "fan": fancsv, + "temp": tempcsv + }) + +@login_required(redirect_field_name=None) +def testing(req): + checkadmin(req) + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + + boards = Board.objects.filter(online=1) + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/testexp.html', {"boards": boards, "allotment_mode": allotment_mode, "mids": current_mids}) + +@csrf_exempt +def monitor_experiment(req): + checkadmin(req) + try: + mid = int(req.POST.get("mid")) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + try: + current_booking = Booking.objects.get(slot_id=current_slot_id, + booking_date=datetime.date.today(), + account__board__mid=mid) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid MID"}), content_type="application/json") + + try: + current_booking_id, current_user = current_booking.id, current_booking.account.username + + logfile = Experiment.objects.filter(booking_id=current_booking_id).order_by('created_at').reverse()[0].log + except: + return HttpResponse(json.dumps({"status_code":417, "message":"Experiment hasn't started"}), content_type="application/json") + + try: + # get last 10 lines from logs + stdin,stdout = os.popen2("tail -n 10 "+logfile) + stdin.close() + logs = stdout.readlines(); stdout.close() + screened_logs = [] + for line in logs: + screened_line = " ".join(line.split()[:4]) + "\n" + screened_logs.append(screened_line) + + logs = "".join(screened_logs) + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":"Some error occured"}), content_type="application/json") + + data = {"user": current_user, "logs": logs} + return HttpResponse(json.dumps({"status_code":200, "message":data}), content_type="application/json") + +@login_required(redirect_field_name=None) +def get_allocated_mids(req): + checkadmin(req) + with connection.cursor() as cursor: + cursor.execute("SELECT tables_board.mid, COUNT(tables_account.id), tables_board.id FROM tables_account RIGHT OUTER JOIN tables_board ON tables_account.board_id = tables_board.id WHERE tables_board.online = 1 GROUP BY tables_board.mid ORDER BY COUNT(tables_account.id)") + mid_count = cursor.fetchall() + + return render(req, 'admin/changeMID.html', {"mid_count" : mid_count}) + +@csrf_exempt +def get_users(req): + checkadmin(req) + try: + users = list(Account.objects.select_related().values_list("username", "board__mid")) + return HttpResponse(json.dumps({"status_code":200, "message":users}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":str(e)}), content_type="application/json") + + +@csrf_exempt +def toggle_device_status(req): + checkadmin(req) + + try : + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + try: + brd = Board.objects.get(mid = mid) + brd.temp_offline = not brd.temp_offline + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + +@csrf_exempt +def toggle_power_state(req): + checkadmin(req) + # print 'inside toggle_power_state' + try: + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + now = datetime.datetime.now() + # print 'now', now + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + # print 'currnet_slo' + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + try: + print 'mid', mid.strip() + brd = Board.objects.get(mid = mid) + brd.power_status = not brd.power_status + print ' brd.power_status ',int(brd.power_status) + # sys.argv = mid + # print 'sys.argv ',sys.argv + # ser = serial.Serial('/dev/ttyACM0') + # print switch_on.switchOn(sys.argv) + + if not brd.power_status: + m = str(mid).zfill(2) + print 'N ',m + time.sleep(2) + ser.write(b'N'+str(m)) + # switch_on.switchOn(m) + else: + m = str(mid).zfill(2) + print 'F ',m + time.sleep(2) + ser.write(b'F'+str(m)) + # switch_off.switchOff(sys.argv) + # ser.close() + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + +def user_exists(username): + try: + user = Account.objects.get(username=username) + except ObjectDoesNotExist: + return None + return user + +@csrf_exempt +def update_allocated_mid(req): + checkadmin(req) + try: + username = req.POST.get("username") + board_id = req.POST.get("board_id") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + user = user_exists(username) + if user is not None: + user.board_id = board_id + user.save() + else: + return HttpResponse(json.dumps({"status_code": 400, "message": "Username does not exist"}), content_type="application/json") + + return HttpResponse(json.dumps({"status_code": 200, "message": "MID changed successfully"}), content_type="application/json") + +@login_required(redirect_field_name=None) +def download_log(req, mid): + checkadmin(req) + try: + global_logfile = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(global_logfile, "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.") + +@login_required(redirect_field_name=None) +@csrf_exempt +def range_logs(req): + checkadmin(req) + try: + start_date = req.POST.get("start_date") + end_date = req.POST.get("end_date") + start_time = req.POST.get("start_time") + end_time = req.POST.get("end_time") + except: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + start = start_date + " " + start_time + end = end_date + " " + end_time + log_files = Experiment.objects.filter(created_at__range=[start, end]).values("id", "log") + + return HttpResponse(json.dumps({"status_code":200, "message":list(log_files)}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code": 500, "message": "Some error occured" + str(e)}), content_type="application/json") + +@login_required(redirect_field_name=None) +@csrf_exempt +def download_experiment_log(req, experiment_id): + """ Downloads the experimental log file. + Input: req: request object, experiment_id: experimental id + Output: HttpResponse object + """ + checkadmin(req) + try: + experiment_data = Experiment.objects.select_related("booking", "booking__account").get(id=experiment_id) + f = open(experiment_data.log, "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.") + +@csrf_exempt +def reset_device(req): + """Resets the device to fan = 100 and heat = 0 + Takes mid as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + # mid=int(req.POST.get('mid')) + # usb_path=settings.MID_PORT_MAP.get(mid,None) + + # if usb_path is None: + # retVal={"status_code":400,"message":"Invalid MID"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # #trying to connect to device + + # # check if SBHS device is connected + # if not os.path.exists(usb_path): + # retVal={"status_code":500,"message":"Device Not connected to defined USB Port"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # try: + # board = sbhs.Sbhs() + # board.machine_id=mid + # board.boardcon= serial.Serial(port=usb_path, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) #orignal stopbits = 1 + # board.status = 1 + # if board.reset_board(): + # retVal={"status_code":200,"message":board.getTemp()} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # else: + # retVal={"status_code":500,"message":"Could not set the parameters.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # except serial.serialutil.SerialException: + # retVal={"status_code":500,"message":"Could not connect to the device.Try again."}
\ No newline at end of file diff --git a/myadmin/views.py.save.1 b/myadmin/views.py.save.1 new file mode 100644 index 0000000..693c8de --- /dev/null +++ b/myadmin/views.py.save.1 @@ -0,0 +1,666 @@ +from django.shortcuts import render, redirect +from django.http import Http404, HttpResponse +from django.contrib.auth.decorators import login_required +from django.views.decorators.csrf import csrf_exempt +from django.db.models import Count +from django.db import connection +from django.core.exceptions import ObjectDoesNotExist +from sbhs_server.tables.models import Board, Booking, Slot, Experiment, Account, Webcam +from sbhs_server import settings, sbhs +# from sbhs_server import switch_on, switch_off +import class_based_automated_slot_booking +import subprocess, json, serial, os, datetime, requests, zipfile +import sys, inspect +import time +# Create your views here. +from time import gmtime, strftime +import random +import MySQLdb +import datetime + +from sbhs_server import credentials as credentials + +currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) +parentdir = os.path.dirname(currentdir) +sys.path.insert(0,parentdir) + +import switch_onn, switch_off#, check_future_slots +# ser.close() +ser = serial.Serial('/dev/ttyACM0') + + +def checkadmin(req): + """ Checks for valid admin + Raises Http error if: + Requested user is not admin. + Input: s: request object. + Output: HttpResponse + """ + if not req.user.is_admin: + raise Http404 + +@login_required(redirect_field_name=None) +def index(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/index.html', {"boards": boards, "allotment_mode": allotment_mode}) + +@login_required(redirect_field_name=None) +def toggle_allotment_mode(req): + checkadmin(req) + Board.toggle_random_allotment() + return redirect(index) + +@login_required(redirect_field_name=None) +def booking_index(req): + checkadmin(req) + bookings = Booking.objects.order_by('-booking_date','-slot_id').filter(trashed_at__isnull=True).select_related()[:50] + return render(req, 'admin/booking_index.html', {"bookings": bookings}) + +@login_required(redirect_field_name=None) +def webcam_index(req): + checkadmin(req) + boards = Board.objects.filter(online=True) + for board in boards: + Webcam.load_image(board.mid) + return render(req, 'admin/webcam_index.html', {"boards": boards}) + +@login_required(redirect_field_name=None) +def logs_index(req): + checkadmin(req) + date = (datetime.datetime.now()).strftime("%Y-%m-%d") + return render(req, 'admin/user_logs.html', {"nowdate" : date}) + +def zipdir(path, ziph): + # ziph is zipfile handle + for root, dirs, files in os.walk(path): + for file in files: + ziph.write(os.path.join(root,file)) + +@login_required(redirect_field_name=None) +def logs_folder_index(req): + checkadmin(req) + # pass + if os.path.exists('Experiments.zip'): + os.remove('Experiments.zip') + zipf = zipfile.ZipFile('Experiments.zip','w',zipfile.ZIP_DEFLATED) + zipdir('experiments/',zipf) + zipf.close() + zip_file = open('Experiments.zip','r') + response = HttpResponse(zip_file, content_type='application/force-download') + response['Content-Disposition'] = 'attachment; filename="%s"' % 'Experiments.zip' + return response + +@login_required(redirect_field_name=None) +def switch_on_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_onn.switchOnn(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + +@login_required(redirect_field_name=None) +def switch_off_all_boards(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + switch_off.switchOff(sys.argv) + return render(req,'admin/switch_on_all_board.html',{"boards":boards}) + + +@login_required(redirect_field_name=None) +def profile(req, mid): + checkadmin(req) + try: + filename = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(filename, "r") + f.close() + except: + # raise Http404("log does not exist for this profile") + return render(req,'admin/log_does_not_exist.html') + + delta_T = 1000 + data = subprocess.check_output("tail -n %d %s" % (delta_T, filename), shell=True) + data = data.split("\n") + plot = [] + heatcsv = "" + fancsv = "" + tempcsv = "" + + for t in xrange(len(data)): + line = data[t] + entry = line.strip().split(" ") + try: + plot.append([int(i) for i in entry[0:-1] + [float(entry[-1])]]) + heatcsv += "%d,%s\\n" % (t+1, entry[1]) + fancsv += "%d,%s\\n" % (t+1, entry[2]) + tempcsv += "%d,%s\\n" % (t+1, entry[3]) + except: + continue + + plot = zip(*plot) # transpose + + return render(req, "admin/profile.html", { + "mid": mid, + "delta_T": delta_T, + "heat": heatcsv, + "fan": fancsv, + "temp": tempcsv + }) + +@login_required(redirect_field_name=None) +def testing(req): + checkadmin(req) + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + + boards = Board.objects.filter(online=1) + allotment_mode = "Random" if Board.can_do_random_allotment() else "Workshop" + return render(req, 'admin/testexp.html', {"boards": boards, "allotment_mode": allotment_mode, "mids": current_mids}) + +@csrf_exempt +def monitor_experiment(req): + checkadmin(req) + try: + mid = int(req.POST.get("mid")) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + try: + current_booking = Booking.objects.get(slot_id=current_slot_id, + booking_date=datetime.date.today(), + account__board__mid=mid) + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid MID"}), content_type="application/json") + + try: + current_booking_id, current_user = current_booking.id, current_booking.account.username + + logfile = Experiment.objects.filter(booking_id=current_booking_id).order_by('created_at').reverse()[0].log + except: + return HttpResponse(json.dumps({"status_code":417, "message":"Experiment hasn't started"}), content_type="application/json") + + try: + # get last 10 lines from logs + stdin,stdout = os.popen2("tail -n 10 "+logfile) + stdin.close() + logs = stdout.readlines(); stdout.close() + screened_logs = [] + for line in logs: + screened_line = " ".join(line.split()[:4]) + "\n" + screened_logs.append(screened_line) + + logs = "".join(screened_logs) + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":"Some error occured"}), content_type="application/json") + + data = {"user": current_user, "logs": logs} + return HttpResponse(json.dumps({"status_code":200, "message":data}), content_type="application/json") + +@login_required(redirect_field_name=None) +def get_allocated_mids(req): + checkadmin(req) + with connection.cursor() as cursor: + cursor.execute("SELECT tables_board.mid, COUNT(tables_account.id), tables_board.id FROM tables_account RIGHT OUTER JOIN tables_board ON tables_account.board_id = tables_board.id WHERE tables_board.online = 1 GROUP BY tables_board.mid ORDER BY COUNT(tables_account.id)") + mid_count = cursor.fetchall() + + return render(req, 'admin/changeMID.html', {"mid_count" : mid_count}) + +@csrf_exempt +def get_users(req): + checkadmin(req) + try: + users = list(Account.objects.select_related().values_list("username", "board__mid")) + return HttpResponse(json.dumps({"status_code":200, "message":users}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":500, "message":str(e)}), content_type="application/json") + + +@csrf_exempt +def toggle_device_status(req): + checkadmin(req) + + try : + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + now = datetime.datetime.now() + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + try: + brd = Board.objects.get(mid = mid) + brd.temp_offline = not brd.temp_offline + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + +@csrf_exempt +def toggle_power_state(req): + checkadmin(req) + # print 'inside toggle_power_state' + try: + mid = req.POST.get('mid') + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + now = datetime.datetime.now() + # print 'now', now + current_slot_id = Slot.objects.filter(start_hour=now.hour, + start_minute__lt=now.minute, + end_minute__gt=now.minute) + # print 'currnet_slo' + current_slot_id = -1 if not current_slot_id else current_slot_id[0].id + + current_bookings = Booking.objects.filter(slot_id=current_slot_id, + booking_date=datetime.date.today()).select_related() + current_mids = list([-1]) if not current_bookings else [current_booking.account.board.mid for current_booking in current_bookings] + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + + if int(mid) in current_mids: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is in use."}), content_type="application/json") + try: + print 'mid', mid.strip() + brd = Board.objects.get(mid = mid) + brd.power_status = not brd.power_status + print ' brd.power_status ',int(brd.power_status) + # sys.argv = mid + # print 'sys.argv ',sys.argv + # ser = serial.Serial('/dev/ttyACM0') + # print switch_on.switchOn(sys.argv) + + if not brd.power_status: + m = str(mid).zfill(2) + print 'N ',m + time.sleep(2) + ser.write(b'N'+str(m)) + # switch_on.switchOn(m) + else: + m = str(mid).zfill(2) + print 'F ',m + time.sleep(2) + ser.write(b'F'+str(m)) + # switch_off.switchOff(sys.argv) + # ser.close() + brd.save() + + return HttpResponse(json.dumps({"status_code":200, "message":"Toggle successful"}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Unsuccessful"}), content_type="application/json") + +def user_exists(username): + try: + user = Account.objects.get(username=username) + except ObjectDoesNotExist: + return None + return user + +@csrf_exempt +def update_allocated_mid(req): + checkadmin(req) + try: + username = req.POST.get("username") + board_id = req.POST.get("board_id") + except Exception as e: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + user = user_exists(username) + if user is not None: + user.board_id = board_id + user.save() + else: + return HttpResponse(json.dumps({"status_code": 400, "message": "Username does not exist"}), content_type="application/json") + + return HttpResponse(json.dumps({"status_code": 200, "message": "MID changed successfully"}), content_type="application/json") + +@login_required(redirect_field_name=None) +def download_log(req, mid): + checkadmin(req) + try: + global_logfile = settings.SBHS_GLOBAL_LOG_DIR + "/" + mid + ".log" + f = open(global_logfile, "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.") + +@login_required(redirect_field_name=None) +@csrf_exempt +def range_logs(req): + checkadmin(req) + try: + start_date = req.POST.get("start_date") + end_date = req.POST.get("end_date") + start_time = req.POST.get("start_time") + end_time = req.POST.get("end_time") + except: + return HttpResponse(json.dumps({"status_code":400, "message":"Invalid parameters"}), content_type="application/json") + + try: + start = start_date + " " + start_time + end = end_date + " " + end_time + log_files = Experiment.objects.filter(created_at__range=[start, end]).values("id", "log") + + return HttpResponse(json.dumps({"status_code":200, "message":list(log_files)}), content_type="application/json") + except Exception as e: + return HttpResponse(json.dumps({"status_code": 500, "message": "Some error occured" + str(e)}), content_type="application/json") + +@login_required(redirect_field_name=None) +@csrf_exempt +def download_experiment_log(req, experiment_id): + """ Downloads the experimental log file. + Input: req: request object, experiment_id: experimental id + Output: HttpResponse object + """ + checkadmin(req) + try: + experiment_data = Experiment.objects.select_related("booking", "booking__account").get(id=experiment_id) + f = open(experiment_data.log, "r") + data = f.read() + f.close() + return HttpResponse(data, content_type='text/text') + except: + return HttpResponse("Requested log file doesn't exist.") + +@csrf_exempt +def reset_device(req): + """Resets the device to fan = 100 and heat = 0 + Takes mid as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + # mid=int(req.POST.get('mid')) + # usb_path=settings.MID_PORT_MAP.get(mid,None) + + # if usb_path is None: + # retVal={"status_code":400,"message":"Invalid MID"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # #trying to connect to device + + # # check if SBHS device is connected + # if not os.path.exists(usb_path): + # retVal={"status_code":500,"message":"Device Not connected to defined USB Port"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # try: + # board = sbhs.Sbhs() + # board.machine_id=mid + # board.boardcon= serial.Serial(port=usb_path, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) #orignal stopbits = 1 + # board.status = 1 + # if board.reset_board(): + # retVal={"status_code":200,"message":board.getTemp()} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # else: + # retVal={"status_code":500,"message":"Could not set the parameters.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # except serial.serialutil.SerialException: + # retVal={"status_code":500,"message":"Could not connect to the device.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + checkadmin(req) + mid=int(req.POST.get('mid')) + + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/resetdevice" + payload = {"mid":mid} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not reset the device.."} + return HttpResponse(json.dumps(retVal),content_type='application/json') + + +@csrf_exempt +def set_device_params(req): + """Sets the device parameters as per the arguments sent + Takes mid,fan,heat as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + # mid=int(req.POST.get('mid')) + # fan=int(req.POST.get('fan')) + # heat=int(req.POST.get('heat')) + # usb_path=settings.MID_PORT_MAP.get(mid,None) + + # if usb_path is None: + # retVal={"status_code":400,"message":"Invalid MID"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # #trying to connect to device + + # # check if SBHS device is connected + # if not os.path.exists(usb_path): + # retVal={"status_code":500,"message":"Device Not connected to defined USB Port"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # try: + # board = sbhs.Sbhs() + # board.machine_id=mid + # board.boardcon= serial.Serial(port=usb_path, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) #orignal stopbits = 1 + # board.status = 1 + # if board.setFan(fan) and board.setHeat(heat): + # retVal={"status_code":200,"message":board.getTemp()} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # else: + # retVal={"status_code":500,"message":"Could not set the parameters.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # except serial.serialutil.SerialException: + # retVal={"status_code":500,"message":"Could not connect to the device.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + checkadmin(req) + mid=int(req.POST.get('mid')) + fan=int(req.POST.get('fan')) + heat=int(req.POST.get('heat')) + try: + ip = settings.pi_ip_map.get(str(mid)) + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/setdevice" + payload = {"mid":mid, "fan":fan, "heat":heat} + r = requests.post(url , data = payload) + + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not set the device params.."} + return HttpResponse(json.dumps(retVal),content_type='application/json') + + +@csrf_exempt +def get_device_temp(req): + """Sets the device parameters as per the arguments sent + Takes mid,fan,heat as paramter + Returns status_code = 200, data={temp:temp of the device} if succesful + else + status_code = 500 , data={error:errorMessage} + """ + # mid=int(req.POST.get('mid')) + # usb_path=settings.MID_PORT_MAP.get(mid,None) + + # if usb_path is None: + # retVal={"status_code":400,"message":"Invalid MID"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # #trying to connect to device + + # # check if SBHS device is connected + # if not os.path.exists(usb_path): + # retVal={"status_code":500,"message":"Device Not connected to defined USB Port"} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + # try: + # board = sbhs.Sbhs() + # board.machine_id=mid + # board.boardcon= serial.Serial(port=usb_path, baudrate=9600, bytesize=8, parity='N', stopbits=1, timeout=2) #orignal stopbits = 1 + # board.status = 1 + # temp=board.getTemp() + # if temp!=0.0: + # retVal={"status_code":200,"message":temp} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # else: + # retVal={"status_code":500,"message":"Could not set the parameters.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + # except serial.serialutil.SerialException: + # retVal={"status_code":500,"message":"Could not connect to the device.Try again."} + # return HttpResponse(json.dumps(retVal),content_type='application/json') + + checkadmin(req) + print 'inside get_device_temp function' + mid=int(req.POST.get('mid')) + print 'mid',mid + try: + ip = settings.pi_ip_map.get(str(mid)) + print 'ip',ip + if ip is None: + return HttpResponse(json.dumps({"status_code":400, "message":"Board is offline"}), content_type="application/json") + url = "http://" + str(ip) + "/pi/admin/gettemp" + print 'url ', url + payload = {"mid":mid} + print 'payload',payload + r = requests.post(url , data = payload) + print 'r', r + return HttpResponse(r.text, content_type="application/json") + except Exception as e: + retVal={"status_code":500,"message":"Could not get the device temperature.."+str(e)} + return HttpResponse(json.dumps(retVal),content_type='application/json') + + +@login_required(redirect_field_name=None) +def automated_slot_booking(req): + checkadmin(req) + boards = Board.objects.order_by('-online').all() + # db = MySQLdb.connect(host='localhost', ## your host, usually localhost ## + # user='root', ## your username ## + # passwd='fossee@iitb', ## your password ## + # db='sbhs') ## name of the data base ## + auto = class_based_automated_slot_booking.Automated_Slot_Booking() + # cu1 = auto.cu1 + # cu2 = auto.cu2 + # db = auto.db + # cursor5 = auto.cursor5 + # nowDate = auto.nowDate + # nowTime = auto.nowTime + # SplittedTime = auto.SplittedTime + # NowdaTe = auto.NowdaTe + # CurrentAccountIdList = auto.CurrentAccountIdList + # BookedSlotId = auto.BookedMidList + # RequiredMidList = auto.RequiredMidList + # SuperUserMidList = auto.SuperUserMidList + + auto.SuperUserList() + auto.CurrentBookedAccount() + auto.BookedMidList() + auto.BookSlot() + auto.CloseDb() + ## print "Opened database successfully" + + ## Execution of querry + # cursor5=db.cursor() + # cu1=db.cursor() + # querry1='SELECT * FROM tables_booking' + # cu1.execute(querry1) + + # ## Datetime used when script runs + # nowDate=datetime.datetime.now().date() + # nowTime=str(datetime.datetime.now().time()) + # SplittedTime=nowTime.split(":") + # NowdaTe=str(nowDate) + # NowdaTe=NowdaTe.strip() ## To remove extra spaces strip is used## + + + # CurrentAccountIdList=[] + # BookedSlotId=[] + + # for DateTimeInBooking in cu1: + # nn=str(DateTimeInBooking[6]) + # daTe = nn[0:11] + # tiMe=nn[11:13] + # daTe=daTe.strip() + + # if daTe==NowdaTe and int(SplittedTime[0])+1==int(DateTimeInBooking[3]): + # CurrentAccountIdList.append(int(DateTimeInBooking[2])) + # BookedSlotId.append(int(DateTimeInBooking[3])) + # #print BookedSlotId,CurrentAccountIdList + + + # querry2='SELECT *FROM tables_account' + # cu2=db.cursor() + # cu2.execute(querry2) + + + # RequiredMidList=[] + # for AccountIdFromTablesAccnt in cu2: + # var=AccountIdFromTablesAccnt[0] + + # for Id in range(len(CurrentAccountIdList)): + # if long(CurrentAccountIdList[Id])==(AccountIdFromTablesAccnt[0]): + # RequiredMidList.append(int(AccountIdFromTablesAccnt[9])) + + # #print RequiredMidList + + # SuperUserMidList=[Mid for Mid in range(1,41)] + # #print SuperUserMidList + + # MidsTobeBooked=[mId for mId in SuperUserMidList if mId not in RequiredMidList] + # #print MidsTobeBooked + + # for BookMid in range(len(MidsTobeBooked)): + # ToInsert=[int((MidsTobeBooked[BookMid]))+40,int(SplittedTime[0])+1,(datetime.datetime.now()),(datetime.datetime.now()),(nowDate)] + # try: + # cursor5.execute("INSERT INTO tables_booking(account_id,slot_id,created_at,updated_at,booking_date) VALUES(%s,%s,%s,%s,%s)",ToInsert) + # except: + # pass + # db.commit() ## To update the table Changes in database ## + + + + # ## Closing all the object of Cursor + # cu1.close() + # cu2.close() + # cursor5.close() + # db.close() + # ## print "database closed successfully" + + switch_onn.switchOnn(sys.argv) + # check_future_slots.check_future_slots() + # switch_on_all_boards() + return render(req,'admin/index.html',{'boards':boards}) |