def upload2Interop(self): s1=s2=s3=s4=s5=s6=s7=s8=s9=None s1=self.text1.get() s2=self.entry2.get() s3=self.entry3.get() s4=self.text4.get() s5=self.text5.get() s6=self.text6.get() s7=self.entry7.get() s8=self.text8.get() s9=self.entry9.get() if s9=="": s9=None s2=eval(s2) s3=eval(s3) target_response=OrderedDict([("id", 1),("user", 1,),("type", s1),("latitude", s2),("longitude", s3),("orientation", s4),("shape",s5),("background_color",s6),("alphanumeric", s7),("alphanumeric_color", s8),("description", s9),("autonomous", False)]) # print target_response json_str=json.dumps(target_response) print (json_str) x=self.gps() print ("Latitude and Longitude : ") with open(str(self.index2)+".json",'w') as outfile: json.dump(target_response,outfile) a=str(self.index2)+".json" b="cp "+a+" mydata/"+a os.system(b) client = interop.Client(url='http://10.10.130.10:80', username='******', password='******') target=interop.Odlc(id=None, user='******', type=s1, latitude=s2, longitude=s3, orientation=s4, shape=s5, background_color=s6, alphanumeric=s7, alphanumeric_color=s8, description=None, autonomous=False) target = client.post_odlc(target) print (str(self.index2)+".jpg") with open(str(self.index2)+".jpg", 'rb') as f: image_data = f.read() client.put_odlc_image(target.id, image_data) self.index2+=1
def proxy_mavlink(device, client): """Receives packets over the device and forwards telemetry via the client. Args: device: A pymavlink device name to forward. client: Interop Client with which to send telemetry packets. """ # Create the MAVLink connection. mav = mavutil.mavlink_connection(device, autoreconnect=True) # Track rates. sent_since_print = 0 last_print = time.time() client = interop.Client(url='http://10.42.0.1:8000', username='******', password='******') # Continuously forward packets. while True: # Get packet. msg = mav.recv_match(type='GLOBAL_POSITION_INT', blocking=True, timeout=10.0) if msg is None: logger.critical( 'Did not receive MAVLink packet for over 10 seconds.') sys.exit(-1) # Convert to telemetry. telemetry = Telemetry(latitude=mavlink_latlon(msg.lat), longitude=mavlink_latlon(msg.lon), altitude_msl=mavlink_alt(msg.alt), uas_heading=mavlink_heading(msg.hdg)) uas_head = mavlink_heading(msg.hdg) lat = mavlink_latlon(msg.lat), longi = mavlink_latlon(msg.lon), alt = mavlink_alt(msg.alt) #print uas_head #print lat #print longi #print alt client.post_telemetry(telemetry) # Forward telemetry. #try: #client.post_telemetry(telemetry) #except: #logger.exception('Failed to post telemetry to interop.') #sys.exit(-1) # Track telemetry rates. print(uas_head, lat, longi, alt) sent_since_print += 1 now = time.time() since_print = now - last_print if since_print > PRINT_PERIOD: logger.info('Telemetry rate: %f', sent_since_print / since_print) sent_since_print = 0 last_print = now
def connect(url, username, password, out): try: #set up the connection to the interop server at the specified #url with the specified username/password client = interop.Client(url=url, username=username, password=password) out.insert(END, "Connected to " + url + " with username '" + username + "' and password '" + password + "'.\n") except: out.insert(END, "Something when wrong when trying to connect\n")
# Module to receive MAVLink packets and forward telemetry via interoperability. # Packet details at http://mavlink.org/messages/common#GLOBAL_POSITION_INT. import sys import time from pymavlink import mavutil import interop from interop import Telemetry usern = 'testuser' passw = 'testpass' youareL = 'http://10.0.0.3:8000' client = interop.Client(url=youareL, username=usern, password=passw) def mavlink_latlon(degrees): """Converts a MAVLink packet lat/lon degree format to decimal degrees.""" return float(degrees) / 1e7 def mavlink_alt(dist): """Converts a MAVLink packet millimeter format to decimal feet.""" return dist * 0.00328084 def mavlink_heading(heading): """Converts a MAVLink packet heading format to decimal degrees.""" return heading / 100.0
def __init__(self, hst, prt, usr, pss): self.util = Utils() self.host = hst self.port = prt self.URIs = {} self.URIs['LOG'] = "/api/login" self.URIs['OBS'] = "/api/obstacles" self.URIs['TEL'] = "/api/telemetry" self.URIs['MIS'] = "/api/missions" self.componentsAvailable = False self.mission_components = {} self.mission_components['OBS'] = {} self.mission_components['WYP'] = {} self.mission_components['STI'] = {} self.mission_components['TAR'] = {} self.mission_components['FLZ'] = {} self.telemetry_buffer = Queue() self.sysTime = None self.username = usr self.password = pss self.logged_in = False try: while not self.logged_in: try: self.client = interop.Client(url=self.host + ":" + self.port, username=self.username, password=self.password) self.logged_in = True except requests.ReadTimeout: self.logged_in = False self.util.log("RETR: Login Competition server") #self.logged_in = True self.util.succLog("Successfully logged into competition server.") self.populateStaticMissionComponents() self.util.log("Starting the mission components process.") #self.procMiss = Process(target=self.populateObstacleComponents, args=()) #self.procMiss.start() thread.start_new_thread(self.populateObstacleComponents, ()) self.util.succLog( "Successfully initiated multiproc mission components.") self.util.log("Starting the telemetry handeler function.") self.procTelem = Process(target=self.postTelemetryHandeler, args=()) self.procTelem.start() #thread.start_new_thread(self.postTelemetryHandeler, ()) self.util.succLog( "Successfully initiated multiproc telemetry handeler.") except interop.exceptions.InteropError: self.util.errLog("ERROR: Invalid login to competition server.") except requests.exceptions.ConnectionError: self.util.errLog( "Connection error with competition server - Are you sure the Server is Running?" ) self.logged_in = False
import interop client = interop.Client(url='http://127.0.0.1:8000', username='******', password='******') # The following shows how to request the mission details and the current position of the obstacles. missions = client.get_missions() print(missions) stationary_obstacles, moving_obstacles = client.get_obstacles() print(stationary_obstacles, moving_obstacles) #The following shows how to upload UAS telemetry. telemetry = interop.Telemetry(latitude=38.145215, longitude=-76.427942, altitude_msl=50, uas_heading=90) client.post_telemetry(telemetry) # The following shows how to upload a object and it's image. odlc = interop.Odlc(type='standard', latitude=38.145215, longitude=-76.427942, orientation='n', shape='square', background_color='green', alphanumeric='A', alphanumeric_color='white')
def main(): ############################################################ ###################### INITIALIZATION ###################### ############################################################ telemetry_open = False client = interop.Client(url='http://127.0.0.1:8000', username='******', password='******') sys_db = database.db_connectt(url='http://127.0.0.1:8000', username='******', password='******') drone = UAV.connect(url='http://127.0.0.1:8000', username='******', password='******') dataRate = 0 ############################################################ ###################### API DEFINITONS ###################### ############################################################ def upload_telemetry(client, out): telemetry = interop.Telemetry(latitude=38.145215, longitude=-76.427942, altitude_msl=50, uas_heading=90) #send that info to the interop server client.post_telemetry(telemetry) out.insert(END,"Telemetry posted\n") def upload_all_targets(client, target_json, sys_db, out): # this is all boilerplate right now, we need to send target info as json # or extract the json info and send it this way. try: #create a target object. we will be building this object #the output of our image classification program, from v$ #stored in our database. targets, confidence = sys_db.get_all_targets() target_count = 0 confirmed_targets = [] for i in range(0,len(targets)): if confidence[i] > 90: confirmed_targets.append(targets[i]) #send the target info to the interop server for i in range(0,confirmed_targets): client.post_target(confirmed_targets[i]) except: out.insert(END, 'Something went wrong when uploading target\n') def view_current_targets(sys_db, out): #do that def upload_mission(client, mission_json, sys_db, out): # this is all boilerplate right now, we need to send mission info as json # or extract the json info and send it this way. try: mission = sys_db.get_mission() #send the mission info to the interop server mission = client.post_target(mission) out.insert(END, "Mission posted\n") except: out.insert(END, 'Something went wrong when uploading mission\n') def view_mission(sys_db, out): #do that def bottle_drop(drone, out): try: drone.bottle_drop() out.insert(END, "Bottle drop signal sent\n") except: out.insert(END, "Error sending bottle drop signal\n") def get_drone_info(drone, out): #do that def drone_start_video(drone, out): #do that def drone_take_picture(drone, out): #do that def connect(url, username, password, out): try: #set up the connection to the interop server at the specified #url with the specified username/password client = interop.Client(url=url, username=username, password=password) out.insert(END, "Connected to " + url + " with username '" + username + "' and password '" + password + "'.\n") except: out.insert(END, "Something when wrong when trying to connect\n") ############################################################ ###################### WINDOW SETUP ######################## ############################################################ window = Tkinter.Tk() window.title("MSUUS") window.geometry("590x560") url = StringVar( window ) url.set('http://127.0.0.1:8000') username = StringVar( window ) username.set('testuser') password = StringVar( window ) password.set('testpass') url_label = Label( window, text="Server URL") url_label.place(x=10,y=10) url_textbox = Entry( window, textvariable=url ) url_textbox.place(x=100, y=10) username_label = Label( window, text="Username:"******"Password:"******"Output" ) output_label.place(x=10, y=190) output_textbox = Text( window, width=79, wrap=WORD ) output_textbox.place(x=10, y=210) output_scrollbar = Scrollbar( window, command=output_textbox.yview ) output_textbox['yscrollcommand'] = output_scrollbar.set output_scrollbar.place(x=570,y=210,height=340) data_rate_label = Label( window, text="Telemetry Data Rate:" ) data_rate_label.place(x=290, y=10) data_rate_field = Entry( window, textvariable=dataRate ) data_rate_field.place(x=430, y=10, width=40) connect_button = Button( window, text="Connect", command = lambda: connect(url.get(),username.get(),password.get(),output_textbox) ) connect_button.place(x=10, y=90) target_upload_button = Button( window, text="Upload Target", command = lambda: upload_target(client, "{'id':1}",output_textbox) ) target_upload_button.place(x=10, y=150) window.after(500, lambda: upload_telemetry(client,output_textbox)) window.mainloop() if __name__ == "__main__": main()
import interop import getpass #this is only for hiding the password; really not needed but I just felt like adding it. ##################### #UNCOMMENT below when actually testing, and COMMENT OUT line 37 (example client setup) #url_input = raw_input('Enter URL of server: ') #username_input = raw_input('Enter username: '******'Enter password: '******'http://localhost:8000', username = '******', password = '******') #Usually the url_input is 'http://some_url:8000', username and password is whatever we're assigned, but for testing they will be 'testuser' and 'testpass' respectively ############################################ #The following code makes several assumptions (Lines 49-84): # # 1. We are using the SQL database to store our target values, and we have our image files somewhere else # 2. The naming convention of our images puts them in the same order as our SQL db. # i.e. "1_red_A_red_circle.png" links this image to the first line in the SQL database. # Similar to the generate_image() code in target_gen.py, this tacks on a simple target id to locate it in the db. ############################################ #Locate directory containing image files imagedir = raw_input('Input Directory storing images: ')
def main(): ############################################################ ######################## DEFINITONS ####################### ############################################################ def upload_telemetry(client, last_telem, out): telemetry = interop.Telemetry(latitude=38.145215, longitude=-76.427942, altitude_msl=50, uas_heading=90) #send that info to the interop server delta = datetime.datetime.now() - last_telem out.set(1 / (delta.total_seconds())) client.post_telemetry(telemetry) def upload_all_targets(client, target_json, sys_db, out): cur = db.cursor() #allows execution of all SQL queries cur.execute("SELECT * FROM targets") #Fetches every row of the table; #Columns are as follows: #1st - target_id, 2 - type, 3 - latitude, 4 - longitude, 5 - orientation, 6 - shape, 7 - background-color, 8 - alphanumeric, 9 - alphanumeric_color # 10 - image path #note: target_id is a long/int, and latitude and longitude are floats/doubles for row in cur.fetchall(): target = interop.Target( type=row[ 1], #indexing starts from 0, data doesn't include target_id latitude=row[2], longitude=row[3], orientation=row[4], shape=row[5], background_color=row[6], alphanumeric=row[7], alphanumeric_color=row[8]) target = client.post_target(target) #send target values to server #open corresponding image file. Assumes the naming convention goes "1_lettercolor_letter_shapecolor_shape.png". Ex. "2_white_B_green_square.png" with open(imagedir + "/" + row[10] + '.png', 'rb') as f: #the 'rb' option reads the file in binary, as opposed to as a text file image_data = f.read() client.put_target_image(target.id, image_data) def view_current_targets(sys_db, out): cur = db.cursor() #allows execution of all SQL queries cur.execute("SELECT * FROM targets") for row in cur.fetchall(): target = interop.Target( type=row[ 1], #indexing starts from 0, data doesn't include target_id latitude=row[2], longitude=row[3], orientation=row[4], shape=row[5], background_color=row[6], alphanumeric=row[7], alphanumeric_color=row[8]) out.insert(END, target) out.insert(END, "\n") out.see(END) def download_mission(client, sys_db, out): try: missions = client.get_missions() out.insert( END, "Mission info downloaded from interoperability server\n") for wp in missions[0].mission_waypoints: insert_stmt = ( "INSERT INTO waypoints (wp_order, latitude, longitude, altitude, type) " "VALUES (%s, %s, %s, %s, %s)") data = (wp.order, wp.latitude, wp.longitude, wp.altitude_msl, "waypoint") cur = db.cursor() print(insert_stmt, data) cur.execute(insert_stmt, data) db.commit() out.insert(END, "Mission info uploaded to database.\n") out.see(END) except: out.insert(END, 'Something went wrong when downloading mission\n') out.see(END) def download_obstacles(client, sys_db, out): try: missions = client.get_missions() out.insert(END, "Obstacle info downloaded from interop\n") for wp in missions[0].mission_waypoints: insert_stmt = ( "INSERT INTO obstacles (wp_order, latitude, longitude, altitude, type) " "VALUES (%s, %s, %s, %s, %s)") data = (wp.order, wp.latitude, wp.longitude, wp.altitude_msl, "waypoint") cur = db.cursor() print(insert_stmt, data) cur.execute(insert_stmt, data) db.commit() out.insert(END, "Obstacle info uploaded to database.\n") out.insert(END, "\n") out.see(END) except: out.insert(END, 'Something went wrong when downloading obstacles\n') out.see(END) def bottle_drop(drone, out): try: drone.bottle_drop() out.insert(END, "Bottle drop signal sent\n") out.see(END) except: out.insert(END, "Error sending bottle drop signal\n") out.see(END) def ping_drone(drone, out): try: info = drone.get_info() out.insert(END, info["message"]) out.insert(END, "\n") out.see(END) except: out.insert(END, "Error pinging drone.\n") out.see(END) def drone_start_video(drone, out): stream = drone.take_picture() return 0 def drone_take_picture(drone, sys_db, out, pic_out): try: picture = drone.take_picture() out.insert(END, "Picture signal sent\n") insert_stmt = ( "INSERT INTO target_images (id, image) VALUES (%s, %s)") data = (picture["id"], picture["image"]) cur = db.cursor() cur.execute(insert_stmt, data) db.commit() im = PIL.Image.open(BytesIO(base64.b64decode(picture["image"]))) im2 = PIL.ImageTk.PhotoImage(im.resize((180, 160)).rotate(180)) pic_out.configure(image=im2) pic_out.image = im2 out.insert( END, "Picture: " + picture["filename"] + " uploaded to database\n") out.see(END) except: out.insert(END, "Error sending take picture signal\n") out.see(END) def interop_connect(url, username, password, out): try: #set up the connection to the interop server at the specified #url with the specified username/password client = interop.Client(url=url, username=username, password=password) out.insert( END, "Connected to " + url + " with username '" + username + "' and password '" + password + "'.\n") out.see(END) except: out.insert(END, "Something when wrong when trying to connect\n") out.see(END) def on_closing(): window.destroy() ############################################################ ###################### INITIALIZATION ###################### ############################################################ telemetry_open = False client = interop.Client(url='http://127.0.0.1:8000', username='******', password='******') datarate = 0 # to store avg datarate last_telem = datetime.datetime.now() imagedir = 'target_images' drone = UAV.UAV('http://192.168.1.31:5000', 'MSUUS', 'Unmanned2017') #Connect to the mySQL database db = MySQLdb.connect(host="localhost", user="******", passwd="password", db="MSUUS") #Use own credentials for actual database ############################################################ ###################### WINDOW SETUP ######################## ############################################################ window = tkinter.Tk() window.protocol("WM_DELETE_WINDOW", on_closing) window.title("MSUUS System Software v0.6") window.geometry("590x560") url = StringVar(window) url.set('http://127.0.0.1:8000') username = StringVar(window) username.set('testuser') password = StringVar(window) password.set('testpass') url_label = Label(window, text="Interop URL") url_label.place(x=10, y=10) url_textbox = Entry(window, textvariable=url) url_textbox.place(x=100, y=10) username_label = Label(window, text="Username:"******"Password:"******"Output") output_label.place(x=10, y=190) output_textbox = Text(window, width=79, wrap=WORD) output_textbox.place(x=10, y=210) output_scrollbar = Scrollbar(window, command=output_textbox.yview) output_textbox['yscrollcommand'] = output_scrollbar.set output_scrollbar.place(x=570, y=210, height=340) data_rate_str = StringVar(window) data_rate_str.set('0') data_rate_label = Label(window, text="Telemetry Data Rate:") data_rate_label.place(x=290, y=10) data_rate_field = Entry(window, textvariable=data_rate_str) data_rate_field.place(x=430, y=10, width=60) last_pic = PIL.ImageTk.PhotoImage(PIL.Image.open('blank.png')) picture_box_label = Label(window, text="Last Image:") picture_box_label.place(x=290, y=40) picture_box_field = Label(window, image=last_pic) picture_box_field.place(x=370, y=40, width=180, height=160) connect_button = Button( window, text="Interop Connect", command=lambda: interop_connect(url.get(), username.get(), password.get(), output_textbox)) connect_button.place(x=10, y=90) ping_button = Button(window, text="Ping Drone", command=lambda: ping_drone(drone, output_textbox)) ping_button.place(x=136, y=90) take_picture_button = Button( window, text="Take Picture", command=lambda: drone_take_picture(drone, db, output_textbox, picture_box_field)) take_picture_button.place(x=10, y=120) auto_picture_button = Button( window, text="Auto Picture", command=lambda: drone_take_picture(drone, db, output_textbox, picture_box_field)) auto_picture_button.place(x=112, y=120) auto_picture_button.configure(state='disable') stream_button = Button( window, text="Start Stream", command=lambda: drone_start_video(drone, db, output_textbox)) stream_button.place(x=214, y=120) stream_button.configure(state='disable') target_upload_button = Button( window, text="Download Mission", command=lambda: download_mission(client, db, output_textbox)) target_upload_button.place(x=10, y=150) ############################################################ ######################## MAIN LOOP ######################### ############################################################ while True: upload_telemetry(client, last_telem, data_rate_str) last_telem = datetime.datetime.now() window.update_idletasks() window.update()