Ejemplo n.º 1
0
def select_records_by_opening():
    """
    Query for canteens which are open 16.15-18.00

    """
    query = select([Canteen]).where(
        and_(
            func.time(Canteen.time_open) <= func.time('16:15'),
            func.time(Canteen.time_closed) >= func.time('18:00')))
    execution = session.execute(query)

    # printing out the resulting canteen names
    for canteen in execution:
        print(canteen.Name)
Ejemplo n.º 2
0
 def time_from_secs(cls, value):
     return func.time(value, 'unixepoch')
class Attendance(Base):
    __tablename__="attendance"
    id=Column(Integer,primary_key=True)
    date =  Column(Date,default=func.date(func.now()))
    time =  Column(Time,default=func.time(func.now()))
    roll =  Column(Integer,ForeignKey('users.roll'))
Ejemplo n.º 4
0
def login():
    machineId = request.get_json()['machineId']
    username = request.get_json()['username']
    password = request.get_json()['password']
    resultData = {}
    #calculate the current shift

    TimeObj = datetime.now().time()
    logger.debug(f"Current Time :{str(TimeObj)}")
    query = db.session.query(ShiftData).filter(
        and_(
            func.time(ShiftData.fromTime) <= TimeObj,
            func.time(ShiftData.toTime) >= TimeObj))
    for row in query.all():
        if (row.id == 1):
            logger.info("Shift 1")
            resultData['Shift'] = row.shift
        elif (row.id == 2):
            logger.info("Shift 2")
            resultData['Shift'] = row.shift
        elif (row.id == 3):
            logger.info("Shift 3")
            resultData['Shift'] = row.shift
        else:
            pass

    #check for admin user
    if (username == "admin" and password == "IIotAdmin"):
        return jsonify(
            {"result": {
                "status": 1,
                "admin": True,
                "message": "success"
            }})

    #check for a valid user or no
    loginUrl = "http://" + config.SERVER_IP + config.SERVER_ENDPOINT_START + "/Login"
    headers = config.HEADERS
    try:
        res = req.post(loginUrl,
                       headers=headers,
                       data=json.dumps({
                           "UserID": username,
                           "Password": password,
                           "MachineCode": machineId
                       }),
                       timeout=4)
        componentList = []
        modelList = []
        #operationList = []
        data = res.json()
        logger.debug(f"{data}")
        if (data['Error'] != None):
            debug.error("error")
            return jsonify({
                "result": {
                    "status": 0,
                    "admin": False,
                    "message": "invalid username or password"
                }
            })
        else:
            resultData['FullName'] = data['FullName']
            data1 = data['Components']
            data2 = data['ProductModels']
            #data3 = data['Operations']
            for datas in data1:
                componentList.append(datas['Code'])
            for datas in data2:
                modelObj = {}
                modelObj['code'] = datas['Code']
                modelObj['value'] = datas['Value']
                modelList.append(modelObj)
            #for datas in data3:
            #   operationList.append(datas['Code'])
            resultData['Components'] = componentList
            resultData['Models'] = modelList
            #resultData['Operations']=operationList
            logger.debug(f"{resultData}")
            return jsonify({
                "result": {
                    "status": 1,
                    "admin": False,
                    "message": "success",
                    "data": resultData
                }
            })
    except Exception as e:
        logger.error(f"error while connecting to server for login details {e}")
        return jsonify({
            "result": {
                "status": 0,
                "admin": False,
                "message": "Something Went Wrong, Check Network Connection"
            }
        })
Ejemplo n.º 5
0
def operatorScreen():
    result = request.get_json()
    shift = result['shift']
    username = result['fullName']
    component = result['componentName']
    model = result['modelName']
    operation = result['operationName']
    machineId = result['machineId']
    jobId = result['jobId']
    #calculate the current shift
    TimeObj = datetime.now().time()
    query = db.session.query(ShiftData).filter(
        and_(
            func.time(ShiftData.fromTime) <= TimeObj,
            func.time(ShiftData.toTime) >= TimeObj))
    for row in query.all():
        if (row.id == 4 or row.id == 5):
            pass
        elif (row.id == 1):
            logger.info("Shift 1")
            nowShift = row.shift
        elif (row.id == 2):
            logger.info("Shift 2")
            nowShift = row.shift
        elif (row.id == 3):
            logger.info("Shift 3")
            nowShift = row.shift
        else:
            nowShift = "Second"

    timeObj = datetime.now()
    time1 = timeObj.strftime("%Y/%m/%d %H:%M:%S")
    CurrentDate = datetime.now().date()
    CurrentTime = datetime.now().time()
    #print(type(CurrentTime))
    sihTime = time(6, 59, 59)
    if (CurrentTime <= sihTime):
        date = CurrentDate - timedelta(1)
    else:
        date = CurrentDate
    presentDate = date.strftime("%Y-%m-%d")
    productionObj = production(operatorName=username,
                               jobId=jobId,
                               shift=shift,
                               component=component,
                               modelName=model,
                               operation=operation,
                               cycleTime="5.5",
                               inspectionStatus="0",
                               status="0",
                               timeStamp=time1,
                               machineId=machineId,
                               date=presentDate)
    try:
        db.session.add(productionObj)
        db.session.commit()
        logger.info("inserting into databse")
    except Exception as e:
        logger.error(f"{e}")
    try:
        # print("releasing machine")
        releaseUrl = "http://" + config.LOCALSERVER_IPADDRESS + ":" + config.PORT + "/HoldMachine"
        headers = config.HEADERS
        res = req.post(releaseUrl,
                       headers=headers,
                       data=json.dumps({"State": "Release"}),
                       timeout=2)
        return jsonify({
            "result": {
                "status": 1,
                "message": "job Status Ok , proceed to cycle ",
                "data": {
                    "shift": nowShift
                }
            }
        })
    except:
        return jsonify({
            "result": {
                "status": 0,
                "message":
                "something went wrong please fill details once more",
                "data": {}
            }
        })
Ejemplo n.º 6
0
def operatorScreen():
    global liveSignal
    liveSignal = "Machine Idle"
    print(liveSignal)
    shift = session['Shift']
    username = session['fullname']
    component = session['componentSelected']
    model = session['modelSelected']
    operation = session['operationSelected']
    machineId = session['machineId']
    if (request.form):
        #calculate the current shift
        TimeObj = datetime.now().time()
        print("Current Time :" + str(TimeObj))
        query = db.session.query(ShiftData).filter(
            and_(
                func.time(ShiftData.fromTime) <= TimeObj,
                func.time(ShiftData.toTime) >= TimeObj))
        for row in query.all():
            print("resulted rows : ")
            if (row.id == 4 or row.id == 5):
                pass
            elif (row.id == 1):
                print("Shift 1")
                session['Shift'] = row.shift
            elif (row.id == 2):
                print("Shift 2")
                session['Shift'] = row.shift
            elif (row.id == 3):
                print("Shidt 3")
                session['Shift'] = row.shift
            else:
                session['Shift'] = "Second"

        optNameTemp = request.form.get('user')
        shiftTemp = request.form.get('shift')
        machineIdTemp = request.form.get('machineId')
        componentTemp = request.form.get('component')
        modelNameTemp = request.form.get('modelName')
        operationTemp = request.form.get('operation')
        jobIdTemp = request.form.get('jobId')
        session['jobId'] = jobIdTemp
        print(session['jobId'])
        #print(modelNameTemp)
        timeObj = datetime.now()
        time = timeObj.strftime("%Y/%m/%d %H:%M:%S")

        CurrentDate = datetime.now().date()
        CurrentTime = datetime.now().time()
        sihTime = t(6, 59, 59)
        if (CurrentTime <= sihTime):
            date = CurrentDate - timedelta(1)
        else:
            date = CurrentDate

        presentDate = date.strftime("%Y-%m-%d")
        print(presentDate)

        print(CurrentDate)
        print(CurrentTime)
        print(date)

        productionObj = production(operatorName=username,
                                   jobId=jobIdTemp,
                                   shift=shift,
                                   component=component,
                                   modelName=model,
                                   operation=operation,
                                   cycleTime="5.5",
                                   inspectionStatus="0",
                                   status="0",
                                   timeStamp=time,
                                   machineId=machineId,
                                   date=presentDate)
        try:
            check = session.query(productionObj).order_by(
                productionObj.id.desc()).first()
            if check.jobId == jobIdTemp:
                pass
            else:
                try:
                    db.session.add(productionObj)
                    db.session.commit()
                    print("inserting into databse")
                except exc.IntegrityError:
                    print("Integrity error")
                    db.session.rollback()
                    print("error inserting into db ")
        except Exception as e:
            print(e)

        print("releasing machine")
        releaseUrl = "http://127.0.0.1:3000/HoldMachine"
        headers = {'Content-type': 'application/json'}
        try:
            res = req.post(releaseUrl,
                           headers=headers,
                           data=json.dumps({"State": "Release"}),
                           timeout=2)
            print(res.status_code)
        except:
            print("error..")

        try:

            Count = 0
            CurrentDate = datetime.now().date()
            CurrentTime = datetime.now().time()
            endTime = t(0, 00, 00)
            sihTime = t(6, 59, 00)
            if (CurrentTime >= endTime and CurrentTime <= sihTime):
                filterDate = CurrentDate - timedelta(1)
            else:
                filterDate = CurrentDate
            presentDate = filterDate.strftime("%Y-%m-%d")
            print(presentDate)
            result = db.session.query(production).filter(
                and_(production.status.like("1"),
                     production.operatorName.like(username),
                     production.date.like(presentDate)))

            #  totalJobs=db.session.query(production).filter(and_(production.operatorName.like(username),production.date.like(presentDate)))

            #  detailedproduction=[]
            #  detailedproductionIndObjs={}
            #  totalModelNames=[]
            #  tempModel=totalJobs.modelName[0]
            #  for i in totalJobs:
            #    if i.modelName==tempModel:
            #      pass
            #    else:
            #      totalModelNames.append(i)
            #  print(totalModelNames)
            #  lenofList=len(totalModelNames)
            #  model1={}
            #  model2={}
            #  model3={}
            #  if(lenofList==1):
            #    model1={
            #      "modelName":totalModelNames[0],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,

            #    }
            #  elif(lenofList==2):
            #    model1={
            #      "modelName":totalModelNames[0],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #    }
            #    model2={
            #      "modelName":totalModelNames[1],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #    }
            #  elif(lenofList==3):
            #    model1={
            #      "modelName":totalModelNames[0],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #    }
            #    model2={
            #      "modelName":totalModelNames[1],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #    }
            #    model3={
            #      "modelName":totalModelNames[2],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #    }
            #  else:
            #     model1={
            #       "modelName":totalModelNames[0],
            #      "productionCount":0,
            #      "ncCount":0,
            #      "totalCount":0,
            #     }
            #  #count all the detailed production data
            #  for data in totalJobs:
            #    if(data.modelName==totalModelNames[0]):
            #      totalCount+=1
            #      ncCount+=1
            #      productionCount+=1
            #      model1['modelName']=totalModelNames[0]
            #      model1['productiontotal']=productionCount
            #      model1['totalCount']=totalCount
            #      model1['ncCount']=ncCount

            Count = 0
            for i in result:
                Count += 1
            print(Count)
        except:
            print("error fetching data")
            return render_template('operator.html',
                                   shift=shift,
                                   user=username,
                                   machineId=machineId,
                                   components=component,
                                   models=model,
                                   productionCount=Count,
                                   operations=operation,
                                   snackBar=True,
                                   liveSignalStatus=liveSignal)

    else:
        try:
            Count = 0
            CurrentDate = datetime.now().date()
            CurrentTime = datetime.now().time()
            endTime = t(0, 00, 00)
            sihTime = t(6, 59, 00)
            if (CurrentTime >= endTime and CurrentTime <= sihTime):
                filterDate = CurrentDate - timedelta(1)
            else:
                filterDate = CurrentDate
            presentDate = filterDate.strftime("%Y-%m-%d")
            print(presentDate)
            result = db.session.query(production).filter(
                and_(production.status.like("1"),
                     production.operatorName.like(username),
                     production.date.like(presentDate)))
            Count = 0
            for i in result:
                Count += 1
        except:
            print("error fetching data")

    return render_template('operator.html',
                           shift=shift,
                           user=username,
                           machineId=machineId,
                           components=component,
                           models=model,
                           productionCount=Count,
                           operations=operation,
                           snackBar=False,
                           liveSignalStatus=liveSignal)
Ejemplo n.º 7
0
def login():
    try:
        pinoutObj = pinout.query.filter_by(id=1).first()
        machineId = pinoutObj.machineId

    except:
        machineId = "null"
        print("failed to load")

    #save shift data to databse
    try:
        url = "http://122.166.155.219/Project/SIH/BE/api/iiot/ShiftList"
        res = req.get(url, timeout=2)
        datas = res.json()
        for data in datas:
            idNew = data['ID']
            shiftNew = data['Name']
            fromTimeNew = data['FromTime']
            toTimeNew = data['ToTime']
            fromTimeNew = datetime.strptime(fromTimeNew, "%Y-%m-%dT%H:%M:%S")
            toTimeNew = datetime.strptime(toTimeNew, "%Y-%m-%dT%H:%M:%S")
            shiftObj = ShiftData(id=idNew,
                                 shift=shiftNew,
                                 fromTime=fromTimeNew,
                                 toTime=toTimeNew)
            try:
                result = ShiftData.query.filter_by(id=idNew).scalar()
                if (result):
                    pass

                else:
                    db.session.add(shiftObj)
                    db.session.commit()
                    print("added shift data to datbase")
            except exc.IntegrityError:
                db.session.rollback()
    except:
        print("something went wrong while getting shift data....")

    #calculate the current shift
    TimeObj = datetime.now().time()
    print("Current Time :" + str(TimeObj))
    query = db.session.query(ShiftData).filter(
        and_(
            func.time(ShiftData.fromTime) <= TimeObj,
            func.time(ShiftData.toTime) >= TimeObj))
    for row in query.all():
        if (row.id == 4 or row.id == 5):
            pass
        elif (row.id == 1):
            print("Shift 1")
            session['Shift'] = row.shift

        elif (row.id == 2):
            print("Shift 2")
            session['Shift'] = row.shift
        elif (row.id == 3):
            print("Shidt 3")
            session['Shift'] = row.shift
        else:
            session['Shift'] = "Second"

    if (request.form):

        loginUrl = "http://122.166.155.219/Project/SIH/BE/api/iiot/Login"
        headers = {'Content-type': 'application/json'}
        username = request.form.get('username')
        password = request.form.get('password')

        if (username == "adminGautam" and password == "sih@password"):
            return render_template('homeConf.html')
        else:
            pass

        try:
            res = req.post(loginUrl,
                           headers=headers,
                           data=json.dumps({
                               "UserID": username,
                               "Password": password,
                               "MachineCode": machineId
                           }),
                           timeout=4)
            componentList = []
            modelList = []
            data = res.json()
            if (data['Error'] != None):
                print("error")
                return render_template('login.html',
                                       machineId=machineId,
                                       status=data['Error'])
            else:
                session['fullname'] = data['FullName']
                data1 = data['Components']
                data2 = data['ProductModels']
                #print(data2)
                for datas in data1:
                    componentList.append(datas['Code'])

                for datas in data2:
                    modelObj = {}
                    modelObj['code'] = datas['Code']
                    modelObj['value'] = datas['Value']
                #  modelList.append(modelObj)

                session['component'] = componentList
                session['model'] = modelList
                pinoutObj = pinout.query.filter_by(id=1).first()
                session['machineId'] = machineId
                return redirect(url_for('setOperations'))

        except:
            print("error while connecting to server for login details")
            return render_template('login.html',
                                   machineId=machineId,
                                   status="Server down..please try again")

    else:
        return render_template('login.html',
                               machineId=machineId,
                               status="null")