Exemplo n.º 1
0
def checkRequest(stationID, msg):
    print("common check request",stationID," ---- ", msg)
    try:
        for i in range(5):
            reply = None
            timeout = time.time() + 5
            msgToSend = msg
            print("msgToSend cehck request ",msgToSend)
            # response = "Message sent" #try
            response = server.sendMsg("ST"+str(stationID), msgToSend)
            print("response is msg sent ma ",response)
            time.sleep(0.1)
            if(response == "Message sent"):
                print("response is not else",response,"and reply is",reply)
                while reply is None:
                    if time.time() > timeout:  # Handle timeout waiting for client repsonse
                        reply = "Request Timeout"

                    # If there are messages in queue, check them
                    if len(server.receivedMsgList) != 0:
                        reply = server.processReply("ST"+str(stationID))
                        reply = reply.replace(";", "")
                        splitedReply = reply.split(',')
                        print("splitedReply,is", splitedReply)
                        return splitedReply
            else:
                print("response is else",response)
                reply = response
                return reply

        reply = "Requet Timeout"
        return reply
    except Exception as e:
        print(redBright("error checkRequest"))
        print("checkRequest",redBright(e))
Exemplo n.º 2
0
def DeleteBin(stationID, position):
    try:
        with app.app_context():
            result = findPositionBin(int(stationID), int(position))

            if (result != None):
                db.session.query(Bin).filter(
                    Bin.station_id == stationID).filter(
                        Bin.position == position).delete()
                db.session.commit()
            else:
                print(redBright("nothing to delete"))
    except:
        print(redBright("Database DeleteBin Error"))
Exemplo n.º 3
0
def findPositionBin(station_id, position):
    print("station id", station_id, "---", "position", position)
    try:
        with app.app_context():
            bin = Bin.query.filter(
                and_(Bin.station_id == int(station_id),
                     Bin.position == int(position))).first()
            print("bin . name us ", bin.name)
            if (bin != None):
                return bin.name
            else:
                print("selected bin either not found or not in given position")
    except Exception as e:
        print(redBright("Database findPositionBin Error"), redBright(e))
Exemplo n.º 4
0
def weight_demo():
    try:
        data = request.get_json()
        if (data['action'] == "IN"):
            replyAction = "CHARGE IN"
        elif (data['action'] == "OUT"):
            replyAction = "CHARGE OUT"

        msgToSend = "ST," + str(
            data['station_id']
        ) + "," + "W" + "," + data['bin_id'] + "," + data['action'] + ";"
        reply = checkRequest(data['station_id'], msgToSend)
        print("msgToSend", msgToSend)
        if type(reply) is list:
            requestReply = jsonFormat(
                {
                    "weight": reply[5],
                    "bin_id": reply[3],
                    "action": replyAction,
                    "station_id": data['station_id']
                }, "")
        else:
            requestReply = jsonFormat({"station_id": data['station_id']},
                                      reply)
        return requestReply
    except:
        print(redBright("Endpoint Weight Error"))
Exemplo n.º 5
0
def getStationByID(station_id):
    try:
        with app.app_context():
            station = Station.query.get(station_id)
            return station
    except Exception as e:
        print(redBright(e))
Exemplo n.º 6
0
def getStationDirection(id):
    try:
        with app.app_context():
            station = Station.query.filter_by(id=id).first()
            return station.rotation
    except Exception as e:
        print(redBright(e))
Exemplo n.º 7
0
def InsertUpdateBin(name, position, stationID):
    try:
        with app.app_context():
            result = findPositionBin(int(stationID), int(position))
            print("InsertUpdateBin result is", result)
            if (result != None):
                print("INSIDE IF")
                db.session.query(Bin).filter(
                    Bin.station_id == int(stationID)).filter(
                        Bin.position == int(position)).update(
                            {Bin.name: name}, synchronize_session=False)
                # db.session.query(Bin).filter_by(Bin.station_id == int(stationID)).filter_by(Bin.position == int(position)).update({Bin.name : name},synchronize_session = False)
                db.session.commit()
            else:
                print("INSIDE ELSE")
                new_bin = Bin(name=name,
                              station_id=int(stationID),
                              position=int(position),
                              status="AVAILABLE",
                              created_at=datetime.datetime.now(),
                              updated_at=datetime.datetime.now())
                db.session.add(new_bin)
                db.session.commit()
    except:
        print(redBright("Database InsertBin Error"))
Exemplo n.º 8
0
def updateStatus(bin, station):
    try:
        statusReply = jsonFormat({"station_id": int(station), "bins": bin}, "")
        with app.test_request_context('/'):
            socketio.emit("status", statusReply, broadcast=True, namespace='/station')
        print("replied with status")
    except:
        print(redBright("Socket Status Error"))
Exemplo n.º 9
0
def pairSuccess(id):
    try:
        print("broadcasting pairing")
        statusReply = jsonFormat({"station_id": int(id)}, "")
        with app.test_request_context('/'):
            socketio.emit('pairing', statusReply, broadcast=True, namespace='/station')
    except Exception as e:
        print(redBright(e))
Exemplo n.º 10
0
def requestStatus(data):
    try:
        data = request.get_json()
        msgToSend = "ST," + str(data['station_id']) + ",S;"
        reply = server.sendMsg("ST" + str(data['station_id']), msgToSend)
        return "Np problem"
    except:
        print(redBright("Unable to manually request Status"))
Exemplo n.º 11
0
def GetStationListByType():
    try:
        data = request.get_json()
        station = db_station.getStationListByCategory(data['type'])
        # print("station is",station)
        json = jsonFormat({"stations": station}, "")
        return json
    except:
        print(redBright("Endpoint getStationListByCategory Error"))
Exemplo n.º 12
0
def sendMsg(targetName, msg):  #might here
    try:
        targetClient = getClientDetails(targetName)
        targetClient[2].send(msg.encode())
        print(cyanBright("Sent Message: " + msg))
        return "Message sent"
    except Exception as e:
        print(redBright("sendMsg"))
        return "Client is not connected"
Exemplo n.º 13
0
def getStationListByCategory(category):
    try:
        station = list()
        stationList = Station.query.filter_by(category=category).all()
        for s in stationList:
            station.append(s.id)
        # print("station ssss",station)
        return station
    except Exception as e:
        print(redBright(e))
Exemplo n.º 14
0
def GetCurrentStation():
    try:
        data = request.get_json()
        result = db_station.getStationByID(data['station_id'])
        print("direction", result)
        bin = db_bin.findBinByStationId(data['station_id'])
        json = jsonFormat({"bins": bin, "direction": result.rotation}, "")
        return json
    except:
        print(redBright("Endpoint GetCurrentStation Error"))
Exemplo n.º 15
0
def jsonFormat(msg, error):
    try:
        json = {
            "data": msg,
            "error": error

        }
        return json
    except Exception as e:
        print(redBright(e))
Exemplo n.º 16
0
def processReply(name):  #either here
    try:
        targetClient = getClientDetails(name)
        client_to_remove = next(
            c for c in receivedMsgList
            if c[0] == targetClient[0] and c[1] == targetClient[1])

        print(greenBright("process reply,client to remove"), client_to_remove)
        receivedMsgList.remove(client_to_remove)
        return client_to_remove[2]
    except:
        print(redBright("Error, Unable to obtain reply from client"))
Exemplo n.º 17
0
def onClientDisconnected(c, addr):
    try:
        disconnectedClient = getDisconnectDetails(c)
        c.close()
        # disconnectedClient = getClientDetails(threading.currentThread().getName())
        connectionList.remove(disconnectedClient)
        print(
            greenBright("-------  %s Disconnected  --------" %
                        (threading.currentThread().getName())))
        print(greenBright("  IP Address: %s\n  Port: %s " % (addr)))
        print(greenBright("---------------------------------------"))
    except:
        print(redBright('Error in handle disconnected client'))
Exemplo n.º 18
0
def onNewConnection(s, ):
    try:
        while True:
            c, addr = s.accept()
            # get the name from database
            threadName = ""
            print("c and address : ", "C -> ", c, " ", "ADDRESS : ", addr)
            newClient = threading.Thread(target=onNewClient,
                                         args=(c, addr),
                                         name=threadName)
            newClient.start()
    except:
        print(redBright("Connection Error"))
Exemplo n.º 19
0
def startServer():
    try:
        s = socket.socket()
        port = 3700
        s.bind(('0.0.0.0', port))
        s.listen(5)
        print(greenBright("Server Listening"))
        newConnection = threading.Thread(target=onNewConnection,
                                         args=(s, ),
                                         name="NewConnection")
        newConnection.start()
    except:
        print(redBright("Server Error"))
Exemplo n.º 20
0
def updateStation(binName, stationID, position):
    print("update statuin : ", binName, stationID, position)
    try:
        with app.app_context():
            if int(position) == 0:
                InsertUpdateBin(binName, position, stationID)
            elif int(position) == 5:
                DeleteBin(int(stationID), int(position))
            else:
                print("not found position or station id")

            bin = findBinByStationId(int(stationID))
            return bin
    except Exception as e:
        print(redBright(e))
Exemplo n.º 21
0
def findBinByStationId(station_id):
    try:
        with app.app_context():
            result = Bin.query.filter(Bin.station_id == station_id).all()
            for x in result:
                print("the result : ", x.name)

            # Differiate the 6+3 and 6
            bin = [''] * 6

            for i in range(len(bin)):
                for x in result:
                    if (i == x.position):
                        bin[i] = x.name
                        print(str(x.position) + "    -----   " + x.name)
            # print("bin",bin)
            return bin
    except:
        print(redBright("Database findBinByStationID Error"))
Exemplo n.º 22
0
def RequestStation(data):
    print("i am in")
    try:
        if (data['action'] == "drop"):
            action = "D"
        elif (data['action'] == "pick"):
            action = "P"

        msgToSend = "ST," + str(data['station_id']) + ",R," + str(
            data['job_id']) + "," + str(
                data['position']) + "|" + action + "|" + str(
                    data['bin_id']) + ";"
        reply = checkRequest(data['station_id'], msgToSend)
        if type(reply) is list:
            if (reply[2] == 'A'):
                requestReply = jsonFormat(
                    {
                        "station_id": data['station_id'],
                        "job_id": data['job_id'],
                        "status": "true",
                        "message": "Approved"
                    }, "")
            else:
                requestReply = jsonFormat(
                    {
                        "station_id": data['station_id'],
                        "job_id": data['job_id'],
                        "status": "false",
                        "message": "Denied"
                    }, "")
        else:
            requestReply = jsonFormat(
                {
                    "station_id": data['station_id'],
                    "job_id": data['job_id'],
                    "status": "false",
                    "message": "Denied"
                }, reply)
        socketio.emit("request", requestReply, namespace='/station')
        # emit("request", requestReply)
    except Exception as e:
        print(redBright(e))
Exemplo n.º 23
0
def weight():
    try:
        data = request.get_json()
        msgToSend = "ST," + str(
            data['station_id']) + ",W," + data['bin_id'] + ";"
        reply = checkRequest(data['station_id'], msgToSend)

        if type(reply) is list:
            requestReply = jsonFormat(
                {
                    "station_id": data['station_id'],
                    "bin_id": reply[3],
                    "weight": reply[4]
                }, "")
        else:
            requestReply = jsonFormat({"station_id": data['station_id']},
                                      reply)
        return requestReply
    except Exception as e:
        print(redBright(e))
Exemplo n.º 24
0
def updateStation(data):
    try:
        if (data['action'] == "drop"):
            action = 'D'
        elif (data['action'] == "pick" or data['action'] == "Pick"):
            action = 'P'

        msgToSend = "ST," + str(data['station_id']) + ",U," + str(
            data['job_id']) + "," + str(
                data['position']) + "|" + action + "|" + data['bin_id'] + ";"
        reply = checkRequest(data['station_id'], msgToSend)

        if type(reply) is list:
            if (reply[0] == "ACK"):
                splitData = reply[5].split('|')
                bin = db_station.updateStation(splitData[2], reply[2],
                                               splitData[0])
                requestReply = jsonFormat(
                    {
                        "station_id": data['station_id'],
                        "job_id": reply[4],
                        "status": "true",
                        "message": "Station has successfully updated bin."
                    }, "")
                socketio.emit('update', requestReply, namespace='/station')
                # emit('update', requestReply)
                msgToSend = "ST," + str(data['station_id']) + ",S;"
                server.sendMsg("ST" + str(data['station_id']), msgToSend)
        else:
            requestReply = jsonFormat(
                {
                    "station_id": data['station_id'],
                    "job_id": reply[4],
                    "status": "false",
                    "message": "Unable to update bin."
                }, reply)
            # emit('update', requestReply)
            socketio.emit('update', requestReply, namespace='/station')
    except:
        print(redBright("Socket Update Error"))
Exemplo n.º 25
0
def handleConnection():
    try:
        print('A socketio client has connected.')
    except:
        print(redBright("Socketio Connection Error"))
Exemplo n.º 26
0
def handleDisconnect():
    try:
        print('A socketio client has disconnected.')
    except:
        print(redBright("Socketio Disconnect Error"))