Esempio n. 1
0
def levels():
    done = True
    while True:
        print ('sync user levels...')
        if not done:
            done = True
            users = db.session.query(User).order_by(User.points.desc()).limit(10)
            for user in users:
                current_level = db.session.query(Level).filter(user.points >= Level.required_points).order_by(Level.required_points.desc()).first()
                print (current_level)
                user.level = current_level
                db.session.add(user)
            db.session.commit()
            db.session.remove()
        done = False
        socketio.sleep(60)
Esempio n. 2
0
def background_thread():
    """Example of how to send server generated events to clients."""
    socketio.sleep(2)
    count = 0
    with serial.Serial(port=PORT_NAME, baudrate=BAUD_RATE, timeout=0.1) as ser:
        while True:
            socketio.sleep(0.3)
            # count += 1
            # data = realtime_model.get_recent_data()
            # socketio.sleep(10)
            # # print(data)

            try:
                data = {
                    'acc': {
                        'x': 0,
                        'y': 0,
                        'z': 0
                    },
                    'magn': {
                        'x': 0,
                        'y': 0,
                        'z': 0
                    },
                    'gyro': {
                        'x': 0,
                        'y': 0,
                        'z': 0
                    },
                    'gps': {
                        'lat': 0,
                        'lng': 0,
                        'h': 0
                    },
                    'time': ""
                }
                data_stream = ser.readline().decode("utf-8").replace(
                    "\r", "").replace("\n", "")
                # print(data_stream)
                data_stream = data_stream.split(",")
                if len(data_stream) == 13:
                    data['acc']['x'], data['acc']['y'], data['acc']['z'] = \
                        float(data_stream[0]), float(data_stream[1]), float(data_stream[2])
                    data['gyro']['x'], data['gyro']['y'], data['gyro']['z'] = \
                        float(data_stream[3]), float(data_stream[4]), float(data_stream[5])
                    data['magn']['x'], data['magn']['y'], data['magn']['z'] = \
                        float(data_stream[6]), float(data_stream[7]), float(data_stream[8])
                    data['gps']['lat'], data['gps']['lng'], data['gps']['h'] = \
                        float(data_stream[9]), float(data_stream[10]), float(data_stream[11])

                    # self.data['time'] = time.strftime("%Y-%m-%d %H:%M:%S")
                    ms = (start_time.day * 24 * 60 * 60 + start_time.second
                          ) * 1000 + start_time.microsecond / 1000.0 + int(
                              data_stream[12])
                    current_time = datetime.datetime.utcfromtimestamp(
                        ms // 1000).replace(microsecond=int(ms) % 1000 * 1000)

                    data['time'] = str(current_time.year) + "-" + str(
                        current_time.month) + "-" + str(
                            current_time.day) + " " + str(
                                current_time.hour) + ":" + str(
                                    current_time.minute) + ":" + str(
                                        current_time.second) + "." + str(
                                            current_time.microsecond)
                    graph_to_send = json.dumps(({
                        'x': data['time'],
                        'y': data['acc']['x']
                    }, {
                        'x': data['time'],
                        'y': data['acc']['y']
                    }, {
                        'x': data['time'],
                        'y': data['acc']['z']
                    }, {
                        'x': data['time'],
                        'y': data['gyro']['x']
                    }, {
                        'x': data['time'],
                        'y': data['gyro']['y']
                    }, {
                        'x': data['time'],
                        'y': data['gyro']['z']
                    }, {
                        'x': data['time'],
                        'y': data['magn']['x']
                    }, {
                        'x': data['time'],
                        'y': data['magn']['y']
                    }, {
                        'x': data['time'],
                        'y': data['magn']['z']
                    }, {
                        'x': data['time'],
                        'y': data['gps']['lat']
                    }, {
                        'x': data['time'],
                        'y': data['gps']['lng']
                    }, {
                        'x': data['time'],
                        'y': data['gps']['h']
                    }), )
                    socketio.sleep(0)
                    socketio.emit('my_response',
                                  graph_to_send,
                                  namespace='/test')
            except UnicodeDecodeError as udc:
                pass
Esempio n. 3
0
def scores():
    print ('scores servise is working...')
    done = False
    ousers = []
    oldUsers = db.session.query(User).order_by(User.points.desc()).limit(10)
    row = 0
    last_point = 999999999999999
    for user in oldUsers:

        if last_point > user.points:
            row += 1
            last_point = user.points
        if user.level:
            ousers.append({
                "row":row,
                "id":user.id,
                "points":user.points,
                "name":user.username,
                "level":user.level.number,
                "avatar":user.avatar.image.split("'")[1],
            })
            last_point = user.points
    while True:
        nusers = []
        print ('sync user scores...')
        if not done:
            done = True
            socketio.sleep(60)
            newUsers = db.session.query(User).order_by(User.points.desc()).limit(10)
            row = 0
            last_point = 999999999999
            for user in newUsers:
                if last_point > user.points:
                    row += 1
                    last_point = user.points
                if user.level :
                    nusers.append({
                        "row":row,
                        "id":user.id,
                        "points":user.points,
                        "name":user.username,
                        "level":user.level.number,
                        "avatar":user.avatar.image.split("'")[1]
                    })
            scores = []
            for ou in ousers:
                score = {}
                for nu in nusers:
                    if ou['id'] == nu['id']:
                        if nu['points'] > ou['points'] or nu['row'] < ou['row']:
                            score['status'] = "up"
                            break
                        elif nu['points'] < ou['points'] or nu['row'] > ou['row']:
                            score['status'] = "down"
                            break
                        else:
                            score['status'] = "equal"
                            break
                score['userId'] = ou['id']
                score['points'] = ou['points']
                score['row'] = ou['row']
                score['name'] = ou['name']
                score['level'] = ou['level']
                score['avatar'] = ou['avatar']
                scores.append(score)

            socketio.emit("scores",scores, broadcast=True)
            ousers = nusers
            db.session.remove()
        done = False
Esempio n. 4
0
def auction_event_handler():
    print ('auction event handler servise is working...')
    done = False
    while True:
        if not done:
            today = datetime.now() - timedelta(seconds=5)
            auctions = db.session.query(Auction).filter(Auction.start_date > datetime.now() , Auction.updated >= today , Auction.done == False).order_by(Auction.start_date.desc())
            for auction in auctions:
                charity = {}
                if auction.charity:
                    charity ={
                        "icon":auction.charity.icon.split("'")[1],
                        "description":auction.charity.description
                    }

                participants = []
                all_participants = auction.participants.order_by(desc(UserAuctionParticipation.created))
                counter = all_participants.count() + 1
                for participant in all_participants:
                    counter -= 1
                    participants.append({
                        "row":counter,
                        "name":participant.username,
                        "avatar":participant.avatar.image.split("'")[1],
                        "level":participant.level.number,
                    })

                socketio.emit("users",participants,broadcast=True)

                discount = math.ceil(( (auction.item.price - auction.max_price) / auction.item.price )*100)
                images = []
                for image in auction.item.images.split("'"):
                    if len(image) > 5:
                        images.append(image)

                # images.append(auction.item.images.split("'")[1])

                product = {}
                if auction.item.quantity > 0:
                    product = {
                        "price":str(auction.item.price),
                        "discount":str(auction.item.discount),
                        "quantity":auction.item.quantity,
                    }

                status = {}
                remainedTime = auctionMillisecondsDeadline(auction.start_date)
                last_bid = Bid.query.filter_by(auction_id=auction.id).order_by(desc(Bid.created)).first()
                if last_bid :
                    status = {
                        "bidPrice":str(last_bid.bid_price),
                        "name":last_bid.user_plan.user.username,
                        "avatar":last_bid.user_plan.user.avatar.image.split("'")[1],
                        }

                extraBids = {}
                if auction.have_extra_gems:
                    extraBids = {
                        "bids":auction.extra_bids,
                        "gems":auction.required_gems,
                        "target":auction.target_bid,
                    }

                result = {
                    "charity":charity,
                    "auctionId":auction.id,
                    "images":images,
                    "level":auction.level.number,
                    "maxLevel":Level.query.count(),
                    "likeCount":auction.likes.count(),
                    "participants":participants,
                    "maxMembers":auction.max_members,
                    "tag":auction.tag,
                    "title":auction.title,
                    "basePrice":str(auction.base_price),
                    "maxPrice":str(auction.max_price),
                    "remainedTime":remainedTime,
                    "discount":discount,
                    "product":product,
                    "status":status,
                    "done":auction.done,
                    "extraBids":extraBids
                }
                socketio.emit("auction",result, broadcast=True)
            db.session.remove()
        socketio.sleep(4)
    done = False
Esempio n. 5
0
def auctions_states():
    print ('auctions states servise is working...')
    done = False
    while True:
        if not done:
            done = True
            now = datetime.now()
            nextTime = now + timedelta(seconds=180)
            beforeTime = now - timedelta(seconds=10)
            auctions = db.session.query(Auction).filter(Auction.start_date > beforeTime , Auction.start_date < nextTime , Auction.done == False).order_by(Auction.start_date.desc())
            for auction in auctions:
                print(auction.title)
                remained = auctionMillisecondsDeadline(auction.start_date)

                if(remained > 60000):
                    socketio.emit("iceAge",{"state":"iceAge","auctionId":auction.id,"heartbeat":remained},broadcast=True)
                elif(remained <= 60000 and remained > 10000):
                    socketio.emit("holliDay",{"state":"holliDay","auctionId":auction.id,"heartbeat":remained})
                elif(remained <= 10000 and remained > -1000):
                    socketio.emit("hotSpot",{"state":"hotSpot","auctionId":auction.id,"heartbeat":remained})
                elif(remained < -1000 and remained > -3000):
                    socketio.emit("zeroTime",{"state":"zeroTime","auctionId":auction.id,"message":SOCKET['ZERO']})
                else:
                    last_bid = db.session.query(Bid).filter(Bid.auction_id==auction.id).order_by(Bid.created.desc()).first()
                    if last_bid:
                        diff = secondDiff(auction.start_date,last_bid.created)
                        print(diff)
                        if(diff < 10):
                            current_auction = db.session.query(Auction).get(auction.id)
                            current_auction.start_date = now + timedelta(milliseconds=10000)
                            db.session.add(current_auction)
                            db.session.commit()
                            remained = auctionMillisecondsDeadline(auction.start_date)
                            print('Refresh auction time')
                            socketio.emit("reset",{"heartbeat":remained,"auction_id":auction.id})
                        else:
                            print('Auction done ...')
                            last_bid.won=True
                            last_bid.user_plan.user.points += last_bid.user_plan.user.level.points_per_win
                            current_auction = db.session.query(Auction).get(auction.id)
                            current_auction.done=True

                            last_order = Order.query.filter_by(user_id=last_bid.user_plan.user.id,item_id=current_auction.item.id,status=OrderStatus.UNPAID).first()
                            if last_order :
                                last_order.total_cost = current_auction.item.price
                                last_order.discount_status = OrderDiscountStatus.AUCTIONWINNER
                                last_order.total_discount = current_auction.item.price - last_bid.bid_price
                                last_order.total = 1
                                last_order.item = auction.item
                                last_order.status = OrderStatus.UNPAID
                                db.session.add(last_order)
                            else:
                                new_order = Order()
                                new_order.user = last_bid.user_plan.user
                                new_order.item = current_auction.item
                                new_order.total_cost = current_auction.item.price
                                new_order.status = OrderStatus.UNPAID
                                new_order.discount_status = OrderDiscountStatus.AUCTIONWINNER
                                new_order.total = 1
                                new_order.total_discount = current_auction.item.price - last_bid.bid_price
                                db.session.add(new_order)

                            db.session.add(last_bid)
                            db.session.add(current_auction)
                            db.session.commit()

                            winner = {
                                "auctionTitle":current_auction.title,
                                "auctionImage":current_auction.image.split("'")[1],
                                "level":last_bid.user_plan.user.level.number,
                                "name":last_bid.user_plan.user.username,
                                "avatar":last_bid.user_plan.user.avatar.image.split("'")[1],
                                "bidPrice":str(last_bid.bid_price),
                                }
                            socketio.emit("winner",{"winner":winner,"auctionId":current_auction.id})

                            db.session.remove()
                    else:
                        current_auction = db.session.query(Auction).get(auction.id)
                        current_auction.done = True
                        db.session.add(current_auction)
                        db.session.commit()
                        print('feniTto for:',auction.id)
                        socketio.emit("feniTto",{"auctionId":auction.id,"error":{"message":SOCKET['FENITTO']}})

            db.session.remove()
        socketio.sleep(1)
        done = False