Skip to content

Commit

Permalink
[enhancement] #43 网络通信改成异步执行
Browse files Browse the repository at this point in the history
  • Loading branch information
BiologyHazard committed May 16, 2023
1 parent c6cc352 commit c7acd2e
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 32 deletions.
19 changes: 12 additions & 7 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import asyncio
import random
import time
from argparse import ArgumentParser

from playground import playgrounds
from sport_api import FudanAPI, get_routes

if __name__ == '__main__':

async def main():
parser = ArgumentParser()
parser.add_argument('-v', '--view', action='store_true', help="list available routes")
parser.add_argument('-r', '--route', help="set route ID", type=int)
Expand All @@ -15,7 +17,7 @@
args = parser.parse_args()

if args.view:
routes = get_routes()
routes = await get_routes()
supported_routes = filter(lambda r: r.id in playgrounds, routes)
for route in supported_routes:
route.pretty_print()
Expand All @@ -35,7 +37,7 @@
total_time += random.uniform(-10.0, 10.0)

# get routes from server
routes = get_routes()
routes = await get_routes()
for route in routes:
if route.id == args.route:
selected_route = route
Expand All @@ -52,12 +54,15 @@
automator = FudanAPI(selected_route)
playground = playgrounds[args.route]
current_distance = 0
automator.start()
await automator.start()
print(f"START: {selected_route.name}")
while current_distance < distance:
current_distance += distance / total_time
message = automator.update(playground.random_offset(current_distance))
message, _ = await asyncio.gather(
automator.update(playground.random_offset(current_distance)), asyncio.sleep(1))
print(f"UPDATE: {message} ({current_distance}m / {distance}m)")
time.sleep(1)
finish_message = automator.finish(playground.coordinate(distance))
finish_message = await automator.finish(playground.coordinate(distance))
print(f"FINISHED: {finish_message}")

if __name__ == '__main__':
asyncio.run(main())
9 changes: 5 additions & 4 deletions playground.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
from geopy.distance import distance
import random
from math import pi

from geopy.distance import distance
from geopy.point import Point

l = 86.96
r = 36.5
Pi = 3.1415926
c = Pi * r
c = pi * r
d = 400


def rad2ang(rad):
return (rad / Pi) * 180
return (rad / pi) * 180


class Playground:
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ certifi==2022.12.7
geographiclib==2.0
geopy==2.3.0
idna==3.4
requests==2.28.2
aiohttp==3.8.4
41 changes: 21 additions & 20 deletions sport_api.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from geopy.point import Point
import requests
import json
import os

import aiohttp
from geopy.point import Point


def _get_arg_from_env_or_json(arg_name, default=None):
value = os.getenv(arg_name)
Expand All @@ -16,17 +17,17 @@ def _get_arg_from_env_or_json(arg_name, default=None):
return value


def get_routes():
async def get_routes():
route_url = 'https://sport.fudan.edu.cn/sapi/route/list'
params = {'userid': _get_arg_from_env_or_json('USER_ID'),
'token': _get_arg_from_env_or_json('FUDAN_SPORT_TOKEN')}
response = requests.get(route_url, params=params)
data = json.loads(response.text)
async with aiohttp.request('GET', route_url, params=params) as response:
data = await response.json()
try:
route_data_list = filter(lambda route: route['points'] is not None and len(route['points']) == 1,
data['data']['list'])
return [FudanRoute(route_data) for route_data in route_data_list]
except:
except Exception:
print(f"ERROR: {data['message']}")
exit(1)

Expand All @@ -40,7 +41,7 @@ def __init__(self, route):
self.device = _get_arg_from_env_or_json('PLATFORM_DEVICE', 'iPhone|iPhone 13<iPhone14,5>')
self.run_id = None

def start(self):
async def start(self):
start_url = 'https://sport.fudan.edu.cn/sapi/run/start'
params = {'userid': self.user_id,
'token': self.token,
Expand All @@ -50,29 +51,29 @@ def start(self):
'device': self.device,
'lng': self.route.start_point.longitude,
'lat': self.route.start_point.latitude}
response = requests.get(start_url, params=params)
data = json.loads(response.text)
async with aiohttp.request('GET', start_url, params=params) as response:
data = await response.json()
try:
self.run_id = data['data']['run_id']
except:
except Exception:
print(f"ERROR: {data['message']}")
exit(1)

def update(self, point):
async def update(self, point):
update_url = 'https://sport.fudan.edu.cn/sapi/run/point'
params = {'userid': self.user_id,
'token': self.token,
'run_id': self.run_id,
'lng': point.longitude,
'lat': point.latitude}
response = requests.get(update_url, params)
try:
data = json.loads(response.text)
return data['message']
except:
return response.text
async with aiohttp.request('GET', update_url, params=params) as response:
try:
data = await response.json()
return data['message']
except Exception:
return await response.read()

def finish(self, point):
async def finish(self, point):
finish_url = 'https://sport.fudan.edu.cn/sapi/run/finish'
params = {'userid': self.user_id,
'token': self.token,
Expand All @@ -81,8 +82,8 @@ def finish(self, point):
'device': self.device,
'lng': point.longitude,
'lat': point.latitude}
response = requests.get(finish_url, params)
data = json.loads(response.text)
async with aiohttp.request('GET', finish_url, params=params) as response:
data = await response.json()
return data['message']


Expand Down

0 comments on commit c7acd2e

Please sign in to comment.