Skip to content

Commit 55e9b7b

Browse files
committed
reformat the the code base based the linter-revisioned version in ruff-check branch
1 parent f93a0ab commit 55e9b7b

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

71 files changed

+3061
-2133
lines changed

.ruff.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
target-version = "py310"
22
exclude = ["*_pb2.py"]
33

4+
line-length = 100
5+
[format]
6+
indent-style = "space"
7+
quote-style = "double"
8+
49
[lint]
510
select = [
611
"E", # pycodestyle

cnc/protocol/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
# SPDX-FileCopyrightText: 2023 Carnegie Mellon University - Satyalab
22
#
3-
# SPDX-License-Identifier: GPL-2.0-only
3+
# SPDX-License-Identifier: GPL-2.0-only

cnc/server/main.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,33 +13,34 @@
1313
DEFAULT_PORT = 9099
1414
DEFAULT_NUM_TOKENS = 2
1515
INPUT_QUEUE_MAXSIZE = 60
16-
SOURCE = 'cnc'
16+
SOURCE = "cnc"
1717

1818
logging.basicConfig(level=logging.INFO)
1919

2020
logger = logging.getLogger(__name__)
2121

2222

2323
def main():
24-
parser = argparse.ArgumentParser(
25-
formatter_class=argparse.ArgumentDefaultsHelpFormatter
26-
)
24+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
2725
parser.add_argument(
2826
"-t", "--tokens", type=int, default=DEFAULT_NUM_TOKENS, help="number of tokens"
2927
)
30-
31-
parser.add_argument(
32-
"-p", "--port", type=int, default=DEFAULT_PORT, help="Set port number"
33-
)
28+
29+
parser.add_argument("-p", "--port", type=int, default=DEFAULT_PORT, help="Set port number")
3430

3531
parser.add_argument(
3632
"-q", "--queue", type=int, default=INPUT_QUEUE_MAXSIZE, help="Max input queue size"
3733
)
38-
34+
3935
args, _ = parser.parse_known_args()
4036

41-
server_runner.run(websocket_port=args.port, zmq_address='tcp://*:5555', num_tokens=args.tokens,
42-
input_queue_maxsize=args.queue)
37+
server_runner.run(
38+
websocket_port=args.port,
39+
zmq_address="tcp://*:5555",
40+
num_tokens=args.tokens,
41+
input_queue_maxsize=args.queue,
42+
)
43+
4344

4445
if __name__ == "__main__":
4546
main()

cnc/server/swarm_controller.py

Lines changed: 99 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -26,25 +26,25 @@
2626
logger.setLevel(logging.DEBUG)
2727
handler = logging.StreamHandler(sys.stdout)
2828
handler.setLevel(logging.DEBUG)
29-
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
29+
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
3030
handler.setFormatter(formatter)
3131
logger.addHandler(handler)
3232

3333
# Set up the paths and variables for the compiler
34-
compiler_path = '/compiler'
35-
output_path = '/compiler/out/flightplan_'
36-
platform_path = '/compiler/python/project'
34+
compiler_path = "/compiler"
35+
output_path = "/compiler/out/flightplan_"
36+
platform_path = "/compiler/python/project"
3737

3838

3939
def download_script(script_url):
4040
try:
4141
# Get the ZIP file name from the URL
42-
filename = script_url.rsplit(sep='/')[-1]
43-
logger.info(f'Writing {filename} to disk...')
44-
42+
filename = script_url.rsplit(sep="/")[-1]
43+
logger.info(f"Writing {filename} to disk...")
44+
4545
# Download the ZIP file
4646
r = requests.get(script_url, stream=True)
47-
with open(filename, mode='wb') as f:
47+
with open(filename, mode="wb") as f:
4848
for chunk in r.iter_content(chunk_size=8192):
4949
f.write(chunk)
5050

@@ -53,177 +53,209 @@ def download_script(script_url):
5353
kml_file = None
5454

5555
# Extract all contents of the ZIP file and remember .dsl and .kml filenames
56-
with ZipFile(filename, 'r') as z:
56+
with ZipFile(filename, "r") as z:
5757
z.extractall(path=compiler_path)
5858
for file_name in z.namelist():
59-
if file_name.endswith('.dsl'):
59+
if file_name.endswith(".dsl"):
6060
dsl_file = file_name
61-
elif file_name.endswith('.kml'):
61+
elif file_name.endswith(".kml"):
6262
kml_file = file_name
6363

6464
# Log or return the results
6565
logger.info(f"Extracted DSL files: {dsl_file}")
6666
logger.info(f"Extracted KML files: {kml_file}")
67-
67+
6868
return dsl_file, kml_file
6969

7070
except Exception as e:
7171
logger.error(f"Error during download or extraction: {e}")
72-
72+
73+
7374
def compile_mission(dsl_file, kml_file, drone_list, alt, compiler_file):
7475
# Construct the full paths for the DSL and KML files
7576
dsl_file_path = os.path.join(compiler_path, dsl_file)
7677
kml_file_path = os.path.join(compiler_path, kml_file)
7778
jar_path = os.path.join(compiler_path, compiler_file)
7879
altitude = str(alt)
79-
80+
8081
# Define the command and arguments
8182
command = [
8283
"java",
83-
"-jar", jar_path,
84-
"-d", drone_list,
85-
"-s", dsl_file_path,
86-
"-k", kml_file_path,
87-
"-o", output_path,
88-
"-p", platform_path,
89-
"-a", altitude
84+
"-jar",
85+
jar_path,
86+
"-d",
87+
drone_list,
88+
"-s",
89+
dsl_file_path,
90+
"-k",
91+
kml_file_path,
92+
"-o",
93+
output_path,
94+
"-p",
95+
platform_path,
96+
"-a",
97+
altitude,
9098
]
91-
99+
92100
# Run the command
93101
logger.info(f"Running command: {' '.join(command)}")
94102
result = subprocess.run(command, check=True, capture_output=True, text=True)
95-
103+
96104
# Log the output
97105
logger.info(f"Compilation output: {result.stdout}")
98-
106+
99107
# Output the results
100108
logger.info("Compilation successful.")
101-
109+
102110

103111
def send_to_drone(msg, base_url, drone_list, cmd_front_cmdr_sock, redis):
104112
try:
105113
logger.info("Sending request to drone...")
106-
# Send the command to each drone
114+
# Send the command to each drone
107115
for drone_id in drone_list:
108116
# check if the cmd is a mission
109-
if (base_url):
117+
if base_url:
110118
# reconstruct the script url with the correct compiler output path
111119
msg.cmd.script_url = f"{base_url}{output_path}{drone_id}.ms"
112120
logger.info(f"script url: {msg.cmd.script_url}")
113-
121+
114122
# send the command to the drone
115-
cmd_front_cmdr_sock.send_multipart([drone_id.encode('utf-8'), msg.SerializeToString()])
116-
logger.info(f'Delivered request to drone {drone_id}:\n {text_format.MessageToString(msg)}')
117-
123+
cmd_front_cmdr_sock.send_multipart([drone_id.encode("utf-8"), msg.SerializeToString()])
124+
logger.info(
125+
f"Delivered request to drone {drone_id}:\n {text_format.MessageToString(msg)}"
126+
)
127+
118128
# store the record in redis
119129
key = redis.xadd(
120130
"commands",
121-
{"commander": msg.commander_id, "drone": drone_id, "value": text_format.MessageToString(msg),}
131+
{
132+
"commander": msg.commander_id,
133+
"drone": drone_id,
134+
"value": text_format.MessageToString(msg),
135+
},
122136
)
123137
logger.debug(f"Updated redis under stream commands at key {key}")
124138
except Exception as e:
125139
logger.error(f"Error sending request to drone: {e}")
126140

127-
141+
128142
def listen_cmdrs(cmdr_sock, cmd_front_cmdr_sock, redis, alt, compiler_file):
129143
while True:
130-
131144
# Listen for incoming requests from cmdr
132145
req = cmdr_sock.recv()
133146
try:
134147
msg = cnc_pb2.Extras()
135148
msg.ParseFromString(req)
136-
logger.info(f'Request received:\n{text_format.MessageToString(msg)}')
149+
logger.info(f"Request received:\n{text_format.MessageToString(msg)}")
137150
except DecodeError:
138-
cmdr_sock.send(b'Error decoding protobuf. Did you send a cnc_pb2?')
139-
logger.info('Error decoding protobuf. Did you send a cnc_pb2?')
151+
cmdr_sock.send(b"Error decoding protobuf. Did you send a cnc_pb2?")
152+
logger.info("Error decoding protobuf. Did you send a cnc_pb2?")
140153
continue
141-
154+
142155
# get the drone list
143156
try:
144157
drone_list_json = msg.cmd.for_drone_id
145158
drone_list = json.loads(drone_list_json)
146159
logger.info(f"drone list: {drone_list}")
147160
except json.JSONDecodeError:
148-
cmdr_sock.send(b'Error decoding drone list. Did you send a JSON list?')
149-
logger.info('Error decoding drone list. Did you send a JSON list?')
161+
cmdr_sock.send(b"Error decoding drone list. Did you send a JSON list?")
162+
logger.info("Error decoding drone list. Did you send a JSON list?")
150163
continue
151-
164+
152165
# Check if the command contains a mission and compile it if true
153166
base_url = None
154-
if (msg.cmd.script_url):
167+
if msg.cmd.script_url:
155168
# download the script
156169
script_url = msg.cmd.script_url
157170
logger.info(f"script url: {script_url}")
158171
dsl, kml = download_script(script_url)
159-
172+
160173
# compile the mission
161174
drone_list_revised = "&".join(drone_list)
162175
logger.info(f"drone list revised: {drone_list_revised}")
163176
compile_mission(dsl, kml, drone_list_revised, alt, compiler_file)
164-
177+
165178
# get the base url
166179
parsed_url = urlparse(script_url)
167180
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
168181

169-
170182
# send the command to the drone
171183
send_to_drone(msg, base_url, drone_list, cmd_front_cmdr_sock, redis)
172-
173184

174-
175-
cmdr_sock.send(b'ACK')
176-
logger.info('Sent ACK to commander')
185+
cmdr_sock.send(b"ACK")
186+
logger.info("Sent ACK to commander")
187+
177188

178189
def main():
179190
parser = argparse.ArgumentParser()
180-
parser.add_argument('-d', '--droneport', type=int, default=5003, help='Specify port to listen for drone requests [default: 5003]')
181-
parser.add_argument('-c', '--cmdrport', type=int, default=6001, help='Specify port to listen for commander requests [default: 6001]')
182191
parser.add_argument(
183-
"-r", "--redis", type=int, default=6379, help="Set port number for redis connection [default: 6379]"
192+
"-d",
193+
"--droneport",
194+
type=int,
195+
default=5003,
196+
help="Specify port to listen for drone requests [default: 5003]",
184197
)
185198
parser.add_argument(
186-
"-a", "--auth", default="", help="Share key for redis user."
199+
"-c",
200+
"--cmdrport",
201+
type=int,
202+
default=6001,
203+
help="Specify port to listen for commander requests [default: 6001]",
187204
)
205+
parser.add_argument(
206+
"-r",
207+
"--redis",
208+
type=int,
209+
default=6379,
210+
help="Set port number for redis connection [default: 6379]",
211+
)
212+
parser.add_argument("-a", "--auth", default="", help="Share key for redis user.")
188213
parser.add_argument(
189214
"--altitude", type=int, default=15, help="base altitude for the drones mission"
190215
)
191216
parser.add_argument(
192-
"--compiler_file", default='compile-1.5-full.jar', help="compiler file name"
193-
)
217+
"--compiler_file", default="compile-1.5-full.jar", help="compiler file name"
218+
)
194219
args = parser.parse_args()
195-
220+
196221
# Set the altitude
197222
alt = args.altitude
198223
logger.info(f"Starting control plane with altitude {alt}...")
199-
224+
200225
compiler_file = args.compiler_file
201226
logger.info(f"Using compiler file: {compiler_file}")
202-
227+
203228
# Connect to redis
204-
r = redis.Redis(host='redis', port=args.redis, username='steeleagle', password=f'{args.auth}',decode_responses=True)
229+
r = redis.Redis(
230+
host="redis",
231+
port=args.redis,
232+
username="steeleagle",
233+
password=f"{args.auth}",
234+
decode_responses=True,
235+
)
205236
logger.info(f"Connected to redis on port {args.redis}...")
206237

207238
# Set up the commander socket
208239
ctx = zmq.Context()
209240
cmdr_sock = ctx.socket(zmq.REP)
210-
cmdr_sock.bind(f'tcp://*:{args.cmdrport}')
211-
logger.info(f'Listening on tcp://*:{args.cmdrport} for commander requests...')
241+
cmdr_sock.bind(f"tcp://*:{args.cmdrport}")
242+
logger.info(f"Listening on tcp://*:{args.cmdrport} for commander requests...")
212243

213244
# Set up the drone socket
214245
async_ctx = zmq.asyncio.Context()
215246
cmd_front_cmdr_sock = async_ctx.socket(zmq.ROUTER)
216247
cmd_front_cmdr_sock.setsockopt(zmq.ROUTER_HANDOVER, 1)
217-
cmd_front_cmdr_sock.bind(f'tcp://*:{args.droneport}')
218-
logger.info(f'Listening on tcp://*:{args.droneport} for drone requests...')
219-
248+
cmd_front_cmdr_sock.bind(f"tcp://*:{args.droneport}")
249+
logger.info(f"Listening on tcp://*:{args.droneport} for drone requests...")
250+
220251
# Listen for incoming requests from cmdr
221252
try:
222253
listen_cmdrs(cmdr_sock, cmd_front_cmdr_sock, r, alt, compiler_file)
223254
except KeyboardInterrupt:
224-
logger.info('Shutting down...')
255+
logger.info("Shutting down...")
225256
cmdr_sock.close()
226257
cmd_front_cmdr_sock.close()
227258

228-
if __name__ == '__main__':
229-
main()
259+
260+
if __name__ == "__main__":
261+
main()

0 commit comments

Comments
 (0)