def main():
    NetworkTable.setTeam(5587)  # TODO set your team number
    NetworkTable.setClientMode()
    # TODO switch to RIO IP, or IP of laptop running OutlineViewer for setup
    NetworkTable.setIPAddress('10.55.87.2')
    NetworkTable.initialize()

    # TODO find what v4l2-ctl settings you need. Pass each commandline option
    # through this array. REQUIRES v4l2-utils to be installed.
    call([
        "v4l2-ctl", "--set-ctrl=exposure_auto=1",
        "--set-ctrl=exposure_absolute=9",
        "--set-ctrl=white_balance_temperature_auto=0"
    ],
         shell=False)

    cap = cv2.VideoCapture(0)
    pipeline = GripPipeline()
    while True:
        ret, frame = cap.read()
        if ret:
            # TODO add extra parameters if the pipeline takes more than just a
            # single image
            pipeline.process(frame)
            extra_processing(pipeline)
    def __init__( self, capture, log, settings ):
        # port="",filters="", hsv=False, original=True, in_file="", out_file="", display=True
        self.limits = {}
        # Pass the log object
        self.log = log
        log.init( "initializing saber_track Tracker" )
        self.settings = settings
        # If the port tag is True, set the
        if settings["port"] != "":
            logging.basicConfig( level=logging.DEBUG )
            NetworkTable.setIPAddress( settings["port"] )
            NetworkTable.setClientMode( )
            NetworkTable.initialize( )
            self.smt_dash = NetworkTable.getTable( "SmartDashboard" )

        # initialize the filters. If the filter is the default: "", it will not create trackbars for it.
        self.init_filters( settings["filters"] )

        # Deal with inputs and outputs
        self.settings["out_file"] = str( self.settings["out_file"] ) # set the file that will be written on saved

        if settings["in_file"] != "":
            self.log.init( "Reading trackfile: " + settings["in_file"] + ".json" )
            fs = open( name + ".json", "r" ) # open the file under a .json extention
            data = json.loads( fs.read() )
            self.limits.update( data )
            fs.close( )


        # Localize the caputure object
        self.capture = capture
        # if there are any color limits (Upper and Lower hsv values to track) make the tracking code runs
        self.track = len( self.limits ) > 0

        self.log.info( "Tracking: " + str(self.track) )
Exemple #3
0
    def __init__(self, fakerobot):
        try:
            if fakerobot:
                NetworkTable.setIPAddress("localhost")
            else:
                NetworkTable.setIPAddress("roboRIO-4915-FRC")
            NetworkTable.setClientMode()
            NetworkTable.initialize()

            self.sd = NetworkTable.getTable("SmartDashboard")
            self.visTable = self.sd.getSubTable("Vision")
            self.connectionListener = ConnectionListener()
            self.visTable.addConnectionListener(self.connectionListener)
            self.visTable.addTableListener(self.visValueChanged)
            self.targetState = targetState.TargetState(self.visTable)
            self.targetHigh = True
            self.autoAimEnabled = False
            self.imuHeading = 0
            self.fpsHistory = []
            self.lastUpdate = time.time()

        except:
            xcpt = sys.exc_info()
            print("ERROR initializing network tables", xcpt[0])
            traceback.print_tb(xcpt[2])
def main():
    cap = cv2.VideoCapture(1)
    
    #Network Tables Setup
    logging.basicConfig(level=logging.DEBUG)
    NetworkTable.setIPAddress('10.32.56.2')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    nt = NetworkTable.getTable('SmartDashboard')

    while cap.isOpened():

        _,frame=cap.read()
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        #Range for green light reflected off of the tape. Need to tune.
        lower_green = np.array(constants.LOWER_GREEN, dtype=np.uint8)
        upper_green = np.array(constants.UPPER_GREEN, dtype=np.uint8)

        #Threshold the HSV image to only get the green color.
        mask = cv2.inRange(hsv, lower_green, upper_green)
        #Gets contours of the thresholded image.
        _,contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        #Draw the contours around detected object
        cv2.drawContours(frame, contours, -1, (0,0,255), 3)

        #Get centroid of tracked object.
        #Check to see if contours were found.
        if len(contours)>0:
            #find largest contour
            cnt = max(contours, key=cv2.contourArea)
            #get center
            center = get_center(cnt)
            cv2.circle(frame, center, 3, (0,0,255), 2)
            if(center[0] != 0 and center[1]!=0):
                center_str_x = "x = "+str(center[0])
                center_str_y = "y = "+str(center[1])
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(frame, "Center", constants.TEXT_COORDINATE_1, font, 0.7, (0,0,255), 2)
                cv2.putText(frame, center_str_x, constants.TEXT_COORDINATE_2, font, 0.7, (0,0,255), 2)
                cv2.putText(frame, center_str_y, constants.TEXT_COORDINATE_3, font, 0.7, (0,0,255), 2)
                angle, direction = get_offset_angle(center[0], center[1])
                cv2.putText(frame, "Angle: "+str(angle),constants.TEXT_COORDINATE_4, font, 0.7, (0,0,255), 2)
                nt.putNumber('CameraAngle', angle)
                cv2.putText(frame, "Turn "+direction, constants.TEXT_COORDINATE_5, font, 0.7, (0,0,255), 2)
                if direction == right:
                    nt.putNumber('Direction', 0)
                else:
                    nt.putNumber('Direction', 1)

        #show image
        cv2.imshow('frame',frame)
        cv2.imshow('mask', mask)
        cv2.imshow('HSV', hsv)

        #close if delay in camera feed is too long
        k = cv2.waitKey(1) & 0xFF
        if k == 27:
            break

    cv2.destroyAllWindows()
Exemple #5
0
def init_networktables(ipaddr):

    logger.info("Connecting to networktables at %s" % ipaddr)
    NetworkTable.setIPAddress(ipaddr)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    logger.info("Networktables Initialized")
Exemple #6
0
def setupNetworkTable(table, address):
	# To see messages from networktables, you must setup logging
	logging.basicConfig(level=logging.DEBUG)
	NetworkTable.setIPAddress(address)
	NetworkTable.setClientMode()
	NetworkTable.initialize()
	return NetworkTable.getTable(table)
def init_networktables(ipaddr):
    logger.info("Connecting to robot %s" % ipaddr)
    Networktable.setIPAddress(ipaddr)
    Networktable.setClientMode()
    Networktable.initialize()
    logger.info("Initialized networktables")
    logger.info("Waiting...")
def init_networktables(ipaddr):

    logger.info("Connecting to networktables at %s" % ipaddr)
    NetworkTable.setIPAddress(ipaddr)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    logger.info("Networktables Initialized")
def initNetworktables():
    logging.basicConfig(level=logging.DEBUG)         # to see messages from networktables
    NetworkTable.setIPAddress('127.0.0.1')
    # NetworkTable.setIPAddress('roborio-5260.local')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    return NetworkTable.getTable('Pi')
Exemple #10
0
def main():
    print('Initializing NetworkTables')
    NetworkTable.setIPAddress("10.52.55.98")
    NetworkTable.setClientMode()
    NetworkTable.initialize()

    print('Creating video capture')
    cap = cv2.VideoCapture("http://10.52.55.3/mjpg/video.mjpg")
    print("here")

    bytes = ''
    first = False

    print('Creating pipeline')
    pipeline = GripPipeline()

    print('Running pipeline')

    while cap.isOpened():
        have_frame, frame = cap.read()
        if have_frame:
            pipeline.process(frame)
            extra_processing(pipeline)

    print('Capture closed')
Exemple #11
0
    def __init__(self, receiverIP):
        try:
            # IPAddress can be static ip ("10.49.15.2" or name:"roboRIO-4915-FRC"/"localhost")
            NetworkTable.setUpdateRate(.01)  # default is .05 (50ms/20Hz), .01 (10ms/100Hz)
            NetworkTable.setIPAddress(receiverIP)
            NetworkTable.setClientMode()
            NetworkTable.initialize()

            self.sd = NetworkTable.getTable("SmartDashboard")

            # we communcate target to robot via VisionTarget table
            self.targetTable = self.sd.getSubTable("VisionTarget")
            
            # robot communicates to us via fields within the VisionControl SubTable
            # we opt for a different table to ensure we to receive callbacks from our
            # own writes.
            self.controlTable = self.sd.getSubTable("VisionControl")
            self.controlTable.addConnectionListener(self.connectionListener)
            self.controlTable.addTableListener(self.visionControlEvent)

            self.control = Control()
            self.target = Target()

            self.fpsHistory = []
            self.lastUpdate = time.time()
            theComm = self

        except:
            xcpt = sys.exc_info()
            print("ERROR initializing network tables", xcpt[0])
            traceback.print_tb(xcpt[2])
Exemple #12
0
 def __init__(self):
     print "Initializing NetworkTables..."
     NetworkTable.setClientMode()
     NetworkTable.setIPAddress("roborio-4761-frc.local")
     NetworkTable.initialize()
     self.table = NetworkTable.getTable("vision")
     print "NetworkTables initialized!"
 def __init__(self, ip, name):
     NetworkTable.setIPAddress(ip)
     NetworkTable.setClientMode()
     NetworkTable.initialize()
     self.visionNetworkTable = NetworkTable.getTable(name)
     if constants.SENDTOSMARTDASHBOARD:
         constants.smartDashboard = NetworkTable.getTable("SmartDashboard")
Exemple #14
0
    def __init__(self, fakerobot):
        try:
            if fakerobot:
                NetworkTable.setIPAddress("localhost")
            else:
                NetworkTable.setIPAddress("roboRIO-4915-FRC")
            NetworkTable.setClientMode()
            NetworkTable.initialize()

            self.sd = NetworkTable.getTable("SmartDashboard")
            self.visTable = self.sd.getSubTable("Vision")
            self.connectionListener = ConnectionListener()
            self.visTable.addConnectionListener(self.connectionListener)
            self.visTable.addTableListener(self.visValueChanged)
            self.targetState = targetState.TargetState(self.visTable)
            self.targetHigh = True
            self.autoAimEnabled = False
            self.imuHeading = 0
            self.fpsHistory = []
            self.lastUpdate = time.time()

        except:
            xcpt = sys.exc_info()
            print("ERROR initializing network tables", xcpt[0])
            traceback.print_tb(xcpt[2])
Exemple #15
0
def setupVisionTable():
	global visionTable
	NetworkTable.setIPAddress("10.46.69.21")
	NetworkTable.setClientMode()
	NetworkTable.initialize()
	visionTable = NetworkTable.getTable("vision")
	setRunVision(False)
	turnOffLight()
Exemple #16
0
def init_network_tables(ip='127.0.0.1'):
    """Initialize NetworkTables as a client to receive and send values
    :param ip: ip address or hostname of the server
    """
    NetworkTable.setIPAddress(ip)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    LOG.info('Network Tables connected as client to {}'.format(ip))
Exemple #17
0
def main():

    ip = "10.24.81.2"
    NetworkTable.setIPAddress(ip)
    NetworkTable.setClientMode()

    #print "Initializing Network Tables"
    NetworkTable.initialize()

    goalFinder = GoalFinder()

    stream = urllib.urlopen('http://10.24.81.11/mjpg/video.mjpg')
    bytes = ''

    #print "Start Target Search Loop..."
    #turn true for single picture debuging
    first = False

    beagle = NetworkTable.getTable("GRIP")
    goals_table = beagle.getSubTable("aGoalContours")

    while True:

        #TODO: Fetch image from camera.
        # img = cv2.imread("0.jpg")
        bytes += stream.read(16384)
        b = bytes.rfind('\xff\xd9')
        a = bytes.rfind('\xff\xd8', 0, b - 1)
        if a != -1 and b != -1:
            jpg = bytes[a:b + 2]
            bytes = bytes[b + 2:]
            img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
                               cv2.CV_LOAD_IMAGE_COLOR)
            goalFinder.process_image(img)

            goals_table.putValue("centerX",
                                 NumberArray.from_list(goalFinder.targetXs))
            goals_table.putValue("centerY",
                                 NumberArray.from_list(goalFinder.targetYs))
            goals_table.putValue(
                "width", NumberArray.from_list(goalFinder.targetWidths))
            goals_table.putValue(
                "height", NumberArray.from_list(goalFinder.targetHeights))
            goals_table.putValue("area",
                                 NumberArray.from_list(goalFinder.targetAreas))

            #if len(goalFinder.targetAreas) > 0:
            #    print goalFinder.targetAreas

            #Use if you want to the save the image and retrieve it later.
            if first:
                first = False
                cv2.imwrite("test.jpg", img)

        goals_table.putNumber("OwlCounter",
                              goals_table.getNumber("OwlCounter", 0) + 1)

        sleep(.01)
Exemple #18
0
def init_networktables():
	#TODO: Check to see if NetworkTables is already initialized
	if not using_networktables:
		raise Exception("Attempted to initialize NetworkTables while NetworkTables is disabled!")
	NetworkTable.setIPAddress(args.networktables_ip)
	NetworkTable.setClientMode()
	NetworkTable.initialize()
	global table
	table = NetworkTable.getTable("vision")
	log.info("Initialized NetworkTables")
def init_ntable():
    global ntable
    NetworkTable.setIPAddress(config.server["rioAddress"])
    NetworkTable.setClientMode()

    NetworkTable.initialize()

    ntable = NetworkTable.getTable('vision');

    ntable.addTableListener(onValueChanged)
def initNetworktables(options):
    if options.dashboard:
        logger.info("Connecting to networktables in Dashboard mode")
        NetworkTable.setDashboardMode()
    else:
        logger.info("Connecting to networktables at %s", options.robot)
        NetworkTable.setIPAddress(options.robot)
        NetworkTable.setClientMode()

    NetworkTable.initialize()
    logger.info("Networktables Initialized")
def init_networktables(options):

    if options.dashboard:
        logger.info("Connecting to networktables in Dashboard mode")
        NetworkTable.setDashboardMode()
    else:
        logger.info("Connecting to networktables at %s", options.robot)
        NetworkTable.setIPAddress(options.robot)
        NetworkTable.setClientMode()
    
    NetworkTable.initialize()
    logger.info("Networktables Initialized")
def setup(robot_ip, table_id, connection_listener_class=None):
    print("Connecting to NetworkTable '{}' on Robot at '{}'".format(table_id, robot_ip))
    NetworkTable.setIPAddress(robot_ip)
    NetworkTable.setClientMode()
    NetworkTable.initialize()

    table = NetworkTable.getTable(table_id)

    if connection_listener_class:
        table.addConnectionListener(connection_listener_class())

    return table
Exemple #23
0
def init_filter():
    '''Function called by mjpg-streamer to initialize the filter'''
    
    # Connect to the robot
    NetworkTable.setIPAddress('127.0.0.1')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    
    #os.system("v4l2-ctl -d /dev/video1 -c exposure_auto=1 -c exposure_absolute=20")
    #os.system("v4l2-ctl -d /dev/video2 -c exposure_auto=1 -c exposure_absolute=10")
    
    filter = TargetFinder()
    return filter.quad_normals
Exemple #24
0
def main():

    ip = "10.24.81.2"
    NetworkTable.setIPAddress(ip)
    NetworkTable.setClientMode()

    # print "Initializing Network Tables"
    NetworkTable.initialize()

    goalFinder = GoalFinder()

    stream = urllib.urlopen("http://10.24.81.11/mjpg/video.mjpg")
    bytes = ""

    # print "Start Target Search Loop..."
    # turn true for single picture debuging
    first = False

    beagle = NetworkTable.getTable("GRIP")
    goals_table = beagle.getSubTable("aGoalContours")

    while True:

        # TODO: Fetch image from camera.
        # img = cv2.imread("0.jpg")
        bytes += stream.read(16384)
        b = bytes.rfind("\xff\xd9")
        a = bytes.rfind("\xff\xd8", 0, b - 1)
        if a != -1 and b != -1:
            jpg = bytes[a : b + 2]
            bytes = bytes[b + 2 :]
            img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
            goalFinder.process_image(img)

            goals_table.putValue("centerX", NumberArray.from_list(goalFinder.targetXs))
            goals_table.putValue("centerY", NumberArray.from_list(goalFinder.targetYs))
            goals_table.putValue("width", NumberArray.from_list(goalFinder.targetWidths))
            goals_table.putValue("height", NumberArray.from_list(goalFinder.targetHeights))
            goals_table.putValue("area", NumberArray.from_list(goalFinder.targetAreas))

            # if len(goalFinder.targetAreas) > 0:
            #    print goalFinder.targetAreas

            # Use if you want to the save the image and retrieve it later.
            if first:
                first = False
                cv2.imwrite("test.jpg", img)

        goals_table.putNumber("OwlCounter", goals_table.getNumber("OwlCounter", 0) + 1)

        sleep(0.01)
Exemple #25
0
    def __init__(self, options):
        NetworkTable.setIPAddress(options.ip)
        NetworkTable.setClientMode()
        NetworkTable.initialize()
        logger.debug('Networktables Initialized')

        self.current_session = None

        self.sd = NetworkTable.getTable('/')
        self.sd.addConnectionListener(self)

        with open(options.config) as config_file:
            self.config = json.load(config_file)

        self.run()
Exemple #26
0
def main():
	prev = 0
	current = 0
	owlMissingCounter = 0
	robotMissingCounter = 0
	prevRobotMissing = 0
	currentRobotMissing = 0

	ip = "roboRIO-2481-FRC.local"
	NetworkTable.setIPAddress(ip)
    	NetworkTable.setClientMode()
	
	print "Bird Watcher: Initializing Network Tables"
	NetworkTable.initialize()
	
	time.sleep(2)
	
	while True:
		beagle = NetworkTable.getTable("GRIP")
        	goals_table = beagle.getSubTable("aGoalContours")
		current = goals_table.getNumber("OwlCounter", 0)
		currentRobotMissing = goals_table.getNumber("RobotCounter", 0)
		if current == prev:
			owlMissingCounter += 1
		else:
			owlMissingCounter = 0
		
		#print owlMissingCounter
		
		prev = current
		
		if owlMissingCounter > 10:
			print "Bird Watcher: Restarting Owl Service"
			os.system("systemctl restart Camera")
			time.sleep(5)
		else:
			time.sleep(1)

		if currentRobotMissing == prevRobotMissing:
			robotMissingCounter += 1
		else:
			robotMissingCounter = 0
		prevRobotMissing = currentRobotMissing

		if robotMissingCounter > 10:
			print "Robot Watcher: Restarting Owl Service"
			os.system("systemctl restart Camera")
			time.sleep(5)
    def __init__(self):
        self.socketio = None
        self.value_cache = {
            'tracking_enabled': True
        }

        NetworkTable.setIPAddress(config.ROBOT_IP_ADDRESS)
        NetworkTable.setClientMode()
        NetworkTable.initialize()

        self.sd = NetworkTable.getTable('SmartDashboard')
        self.sd.addTableListener(self.on_value_changed)

        self.c_listener = NetworkTablesConnectionListener(
            self.on_connection_changed)
        self.sd.addConnectionListener(self.c_listener)
def main():
    NetworkTable.setIPAddress('10.19.37.2')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    sd = NetworkTable.getTable('SmartDashboard')
    #ms_list = []
    while True:
            time.sleep(0.1)
            start_time = datetime.now()

            # returns the elapsed milliseconds since the start of the program
            vision(sd)
            dt = datetime.now() - start_time
            ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
            print ms
            cv2.destroyAllWindows()
def main():
    NetworkTable.setIPAddress('10.19.37.2')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    sd = NetworkTable.getTable('SmartDashboard')
    #ms_list = []
    while True:
        time.sleep(0.1)
        start_time = datetime.now()

        # returns the elapsed milliseconds since the start of the program
        vision(sd)
        dt = datetime.now() - start_time
        ms = (dt.days * 24 * 60 * 60 +
              dt.seconds) * 1000 + dt.microseconds / 1000.0
        print ms
        cv2.destroyAllWindows()
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,"Robot",size=(265,300))
        self.frame=wx.Panel(self)
        self.front_left=wx.TextCtrl(self.frame,-1,pos=(100,25),size=(150,40),style=wx.NO_BORDER|wx.TE_READONLY)
        distance_words=wx.StaticText(self.frame,-1,"Distance",pos=(10,25))
        velocity_words=wx.StaticText(self.frame,-1,"Velocity",pos=(10,125))
        speed_words=wx.StaticText(self.frame,-1,"Speed",pos=(10,175))
        self.front_left.SetBackgroundColour("green")

        self.speed_stuff=wx.TextCtrl(self.frame,-1,pos=(100,175),size=(150,40),style=wx.NO_BORDER|wx.TE_READONLY)
        self.velocity_stuff=wx.TextCtrl(self.frame,-1,pos=(100,125),size=(150,40),style=wx.NO_BORDER|wx.TE_READONLY)

        self.camera_stuff=wx.TextCtrl(self.frame,-1,pos=(100,75),size=(150,40),style=wx.NO_BORDER|wx.TE_READONLY)
        vision_words=wx.StaticText(self.frame,-1,"Vision",pos=(10,75))
        self.camera_stuff.SetBackgroundColour("green")

        self.user_font=wx.Font(18, wx.DEFAULT ,wx.NORMAL, wx.NORMAL)
        distance_words.SetFont(self.user_font)
        self.front_left.SetFont(self.user_font)
        self.camera_stuff.SetFont(self.user_font)
        speed_words.SetFont(self.user_font)
        velocity_words.SetFont(self.user_font)
        vision_words.SetFont(self.user_font)
        self.velocity_stuff.SetFont(self.user_font)
        self.speed_stuff.SetFont(self.user_font)

        self.camera=wx.Button(self.frame,label="Camera",pos=(50,220),size=(150,40))
        self.Bind(wx.EVT_BUTTON, self.camera_link,self.camera)


        self.Bind(wx.EVT_CLOSE, self.close_window)
        #Pynetwork tables stuff
        NetworkTable.setIPAddress("127.0.0.1")#Temp for testing
        NetworkTable.setClientMode()
        NetworkTable.initialize()
        
        self.smrt = NetworkTable.getTable("SmartDashboard")
        self.distance = self.smrt.getAutoUpdateValue('Distance', 0)
        self.vision = self.smrt.getAutoUpdateValue('Vision', 0)
        self.velocity = self.smrt.getAutoUpdateValue('Velocity', 0)
        self.speed = self.smrt.getAutoUpdateValue('Speed', 0)
        threader=threading.Thread(target=self.threading)
        self.keep_open=True
        threader.setDaemon(1)
        threader.start()
Exemple #31
0
class TCDash(App):
    NetworkTable.setIPAddress(
        "127.0.0.1")  #for robot will be 10.2.17.2 aka ip of rio
    NetworkTable.setClientMode()
    NetworkTable.initialize()

    sd = NetworkTable.getTable("SmartDashboard")

    def build(self):
        return main()
Exemple #32
0
def main():
    print('Initializing NetworkTables')
    NetworkTable.setClientMode()
    NetworkTable.setIPAddress('localhost')
    NetworkTable.initialize()

    print('Creating Video Capture')
    cap = cv2.VideoCapture(1)

    print('Creating Pipeline')
    pipeline = GripPipeline()

    print('Running Pipeline')
    while cap.isOpened():
        have_frame, frame = cap.read()
        if have_frame:
            pipeline.process(frame)
            extra_processing(pipeline)

    print('Capture Closed')
    def __init__(self, fakerobot):
        try:
            if fakerobot:
                NetworkTable.setIPAddress("localhost")
            else:
                NetworkTable.setIPAddress("roboRIO-4915-FRC")
            NetworkTable.setClientMode()
            NetworkTable.initialize()

            self.smartDashboard = NetworkTable.getTable("SmartDashboard")
            self.connectionListener = ConnectionListener()
            self.smartDashboard.addConnectionListener(self.connectionListener)
            self.visTable = self.smartDashboard.getSubTable("vision")
            self.visTable.addTableListener(self.visValueChanged)
            self.targetState = targetState.TargetState(self.visTable)

        except:
            xcpt = sys.exc_info()
            print("ERROR initializing network tables", xcpt[0])
            traceback.print_tb(xcpt[2])
    def __init__(self):

        client = False

        if len(sys.argv) > 1:
            client = True
            NetworkTable.setIPAddress(sys.argv[1])
            NetworkTable.setClientMode()
            NetworkTable.initialize()

        # Default write flush is 0.05, could adjust for less latency
        #NetworkTable.setWriteFlushPeriod(0.01)

        self.nt = NetworkTable.getTable('/benchmark')
        self.updates = 0

        if client:
            self.nt.addTableListener(self.on_update)
            self.recv_benchmark()
        else:
            self.send_benchmark()
 def __init__(self):
     
     client = False
     
     if len(sys.argv) > 1:
         client = True
         NetworkTable.setIPAddress(sys.argv[1])
         NetworkTable.setClientMode()
         NetworkTable.initialize()
      
     # Default write flush is 0.05, could adjust for less latency   
     #NetworkTable.setWriteFlushPeriod(0.01)
     
     
     self.nt = NetworkTable.getTable('/benchmark')
     self.updates = 0
     
     if client:
         self.nt.addTableListener(self.on_update)
         self.recv_benchmark()
     else:
         self.send_benchmark()
Exemple #36
0
class test:
    ip = 'roborio-2643-frc.local'
    ip2 = '10.26.43.20'
    NetworkTable.setIPAddress(ip2)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    table = NetworkTable.getTable("Vision")
    x = 0

    def sendVal(val):
        self.table.putNumber("Hello", val)

    while 1:
        table.putNumber("Hello", x)
        print(table.getNumber("Hello", 0))
        x += 1
import math
import random
from networktables import NetworkTable
import socket

logfile = open('log.txt', 'w')

addr = "10.45.34.12"
try:
    hostname = "roborio-4534-frc.local"
    addr = socket.gethostbyname(hostname)
    logfile.write(addr)
except:
    pass

NetworkTable.setIPAddress(addr)
NetworkTable.setClientMode()
NetworkTable.initialize()

logfile.write("Initialized")

table = NetworkTable.getTable('vision')

### GLOBALS ###

displayThreshold = False
### END GLOBALS ###
### CONSTANTS ###
# Camera's physical height (inches) above ground
boilerCameraAltitude = 24
gearCameraAltitude = 5
Exemple #38
0
    else:
        can.configure(image=can_off)

    num_totes = int(elevator.getNumber('tote_count', 0))
    for tote in totes:
        tote.configure(image=tote_off)

    for index in range(num_totes):
        totes[4 - index].configure(image=tote_on)

    if elevator.getBoolean('has_game_piece', False):
        totes[-1].configure(image=tote_on)

    root.after(100, update)


if __name__ == "__main__":
    can = Label(root, image=can_off)
    can.grid(row=0)
    totes = []
    for i in range(6):
        totes.append(Label(root, image=tote_off))
        totes[i].grid(row=i + 1)

    NetworkTable.setIPAddress("roborio-865.local")
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    elevator = NetworkTable.getTable("Elevator")
    update()
    root.mainloop()
Exemple #39
0
now = datetime.datetime.now()
print("Vision Log for " + str(now.day) + "/" + str(now.month) + "/" +
      str(now.year) + "  ~    " + str(now.hour) + ":" + str(now.minute) + ":" +
      str(now.second))
print("OpenCV version: " + str(cv2.__version__))
print("Starting Vision...")

bytes = ''
version = int(cv2.__version__[:1])
streamRunning = True
pipeline = GripPipeline()

try:
    NetworkTable.setTeam(2551)
    NetworkTable.setIPAddress("roborio-2551-frc.local")
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    print("Initializing Network Tables...")
except:
    print("Network Tables already initialized")
    pass

#NetworkTable.setTeam(2551)
#NetworkTable.setIPAddress("roborio-2551-frc.local")
#NetworkTable.setClientMode()
#NetworkTable.initialize()

#print("Initializing Network Tables...")

sd = NetworkTable.getTable('GRIP/myContoursReport')
        default='/mnt/',
        help='specify directory in which to log data')
    parser.add_argument(
        '--output-dir', metavar='ODIR',
        default='/opt/',
        help='specify directory in which to deposit structure.jpg')
    parser.add_argument(
        '--robot', metavar='IP', dest='robot',
        default='roborio-3223-frc.local',
        help='specify ip address of robot')
    return parser

parser = setup_options_parser()
args = parser.parse_args()

NetworkTable.setIPAddress(args.robot)
NetworkTable.setClientMode()
NetworkTable.initialize()

file_name = os.path.join(args.output_dir, "structure.jpg")
tmp_name = os.path.join(args.output_dir, "structure.tmp.jpg")
vision = Vision()
vision.mode = 5
vision.setup_mode_listener()

logger = DataLogger(args.log_dir)

now = time.time()

with vision:
    while True:
Exemple #41
0
#client code what would be on driver station
#send whatever you want to the table
#here is where one can make a cli interface or read from a file
import sys
import time
from networktables import NetworkTable
import logging
from PythonApplication1 import logging
logging.basicConfig(level=logging.DEBUG)

NetworkTable.setIPAddress(
    "127.0.0.1")  #for robot will be 10.2.17.2 aka ip of rio
NetworkTable.setClientMode()
NetworkTable.initialize()

sd = NetworkTable.getTable("SmartDashboard")

value = 217

while True:
    print('Sending... ', value)
    sd.putNumber('VALUE', value)
    time.sleep(1)
#

import sys
import time
from networktables import NetworkTable

# To see messages from networktables, you must setup logging
import logging
logging.basicConfig(level=logging.DEBUG)

if len(sys.argv) != 2:
    print("Error: specify an IP to connect to!")
    exit(0)

ip = sys.argv[1]

NetworkTable.setIPAddress(ip)
NetworkTable.setClientMode()
NetworkTable.initialize()


def valueChanged(key, value, isNew):
    print("valueChanged: key: '%s'; value: %s; isNew: %s" %
          (key, value, isNew))


NetworkTable.addGlobalListener(valueChanged)

while True:
    time.sleep(1)
Exemple #43
0
 def __init__(self, ip="roboRIO-3242-FRC.local"):
   NetworkTable.setIPAddress(ip)
   NetworkTable.setClientMode()
   NetworkTable.initialize()
   self.table = NetworkTable.getTable("rpi")
frame_0 = directory + 'Raw/'
frame_p = directory + 'Processed/'
filename = directory + 'imageValues.npz'
url = 'http://10.5.1.11/axis-cgi/mjpg/video.cgi?resolution=640x480'

freqFramesCam = 20 # how often we're sampling the camera to save files 
freqFramesNT = 10 # how often we're sending to network tables

validCount = 0 # initialize how many validUpdates we've had
#############################################################################
from networktables import NetworkTable
import logging

if NetworkTable._staticProvider is None:
    logging.basicConfig(level=logging.DEBUG)
    NetworkTable.setIPAddress('10.5.1.2')
    NetworkTable.setClientMode()
    NetworkTable.initialize()

sd = NetworkTable.getTable("Camera")
##############################################################################

cap = cv2.VideoCapture(url) # capture camera, 0 is laptop cam, numbers after that are cameras attached

 # Check to make sure cap was initialized in capture
if cap.isOpened():
    print 'Cap succesfully opened'
    print cap.grab()
else:
    print 'Cap initialization failed'
from networktables import NetworkTable
import time

NetworkTable.setIPAddress("10.32.42.20")
NetworkTable.setClientMode()
NetworkTable.initialize()
table = NetworkTable.getTable("rpi")

import time
from networktables import NetworkTable

# import colorama
# from colorama import Fore, Back, Style

# colorama.init()

# AUTHOR: Robbie Selwyn

IP = "roborio-8-frc.local"

NetworkTable.setIPAddress(IP)
NetworkTable.setClientMode()
NetworkTable.initialize()

table = NetworkTable.getTable("data_table")

recording = False
f = None

time.sleep(1)
print "Started Listening"

while True:

    if table.getString("start", "") == "true" and not recording:
        print "Received Start"
        recording = True
        f = open("can-data.csv", "w")
import sys
import time
from networktables import NetworkTable
from networktables.util import ChooserControl

# To see messages from networktables, you must setup logging
import logging
logging.basicConfig(level=logging.DEBUG)

if len(sys.argv) != 2:
    print("Error: specify an IP to connect to!")
    exit(0)

ip = sys.argv[1]

NetworkTable.setIPAddress(ip)
NetworkTable.setClientMode()
NetworkTable.initialize()


def on_choices(value):
    print('OnChoices', value)

def on_selected(value):
    print('OnSelected', value)


cc = ChooserControl('Autonomous Mode',
                    on_choices,
                    on_selected)
def main():

    # brightness adjusted, used to be 30, now is 70
    os.system("v4l2-ctl -d /dev/video0 "
              "-c brightness=70 "
              "-c contrast=10 "
              "-c saturation=100 "
              "-c white_balance_temperature_auto=0 "
              "-c power_line_frequency=2 "
              "-c white_balance_temperature=4500 "
              "-c sharpness=25 "
              "-c backlight_compensation=0 "
              "-c exposure_auto=1 "
              "-c exposure_absolute=5 "
              "-c pan_absolute=0 "
              "-c tilt_absolute=0 "
              "-c zoom_absolute=0")

    NetworkTable.setIPAddress("roboRIO-687-FRC.local")
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    table = NetworkTable.getTable("NerdyVision")
    print("NetworkTables initialized")

    angle_to_turn = 0

    while 687:

        aligned = False
        previous_angle_to_turn = angle_to_turn

        ret, frame = cap.read()
        capture_time = time.time()

        # blur = cv2.GaussianBlur(frame, (11, 11), 0)
        kernel = np.ones((5, 5), np.uint8)
        erosion = cv2.erode(frame, kernel, iterations=1)
        dilation = cv2.dilate(erosion, kernel, iterations=1)
        res, mask = NerdyFunctions.mask(NerdyConstants.LOWER_GREEN, NerdyConstants.UPPER_GREEN, dilation)

        _, cnts, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)

        if len(cnts) > 0:
            c = max(cnts, key=cv2.contourArea)
            area = cv2.contourArea(c)

            if area > NerdyConstants.MIN_GOAL_AREA:
                goal = NerdyFunctions.polygon(c, 0.025)

                if len(goal) == 4:
                    cv2.drawContours(res, [goal], 0, (255, 0, 0), 5)
                    M = cv2.moments(goal)

                    if M['m00'] > 0:
                        cx, cy = NerdyFunctions.calc_center(M)
                        center = (cx, cy)
                        cv2.circle(res, center, 5, (255, 0, 0), -1)

                        error = cx - NerdyConstants.FRAME_CX
                        angle_to_turn = NerdyFunctions.calc_horiz_angle(error)
                        print("ANGLE_TO_TURN: " + str(angle_to_turn))
                        aligned = NerdyFunctions.is_aligned(angle_to_turn)
                        print("IS_ALIGNED: " + str(aligned))

                        processed_time = time.time()
                        delta_time = processed_time - capture_time
                        print("PROCESSED_TIME: " + str(delta_time))

        # Has to be commented out because ssh doesn't allow opencv windows open
        # NerdyFunctions.draw_static(res)
        # cv2.imshow("NerdyVision", res)
        try:
            table.putBoolean('IS_ALIGNED', aligned)
            if previous_angle_to_turn != angle_to_turn:
                table.putNumber('ANGLE_TO_TURN', angle_to_turn)
                table.putNumber('PROCESSED_TIME', delta_time)
            else :
                table.putNumber('ANGLE_TO_TURN', 0)
                table.putNumber('PROCESSED_TIME', 0)
            table.putBoolean('VISION_ON', True)
        except:
            print("DATA NOT SENDING...")
            table.putBoolean('IS_ALINGED', False)
            table.putNumber('ANGLE_TO_TURN', 0)
            table.putNumber('PROCESSED_TIME', 0)
            table.putBoolean('VISION_ON', False)

        cv2.waitKey(1)

    cap.release()
    cv2.destroyAllWindows()
sig = as_array(ic)
back = as_array(ia)

vc.on_time = 1250000 * 8 # units are nanoseconds. 
vc.led_enabled = False
# frame time is 30 milliseconds, so make it smaller than that.

import cv2, threading
import cPickle as pickle
from pylab import plot, ion
ion()
from cv2 import cv
from time import time
from networktables import NetworkTable
try:
        NetworkTable.setIPAddress("roboRIO-2228-FRC.local")
        NetworkTable.setClientMode()
        NetworkTable.initialize()
except:
        print("ERROR in creating network tables: " + str(sys.exc_info()[0]))

sd = NetworkTable.getTable("SmartDashboard")

class Struct:
        #useful one liner for creating struct like variables
        #see declaration of Utils.show
        def __init__(self, **entries): self.__dict__.update(entries)

class Utils:
        #class containing various extrenuous functions
        #including those for displaying images
Exemple #50
0
 def __init__(self):
     NetworkTable.setIPAddress('127.0.0.1')
     NetworkTable.setClientMode()
     NetworkTable.initialize()
     self.nt = NetworkTable.getTable("vision")
import logging
from networktables import NetworkTable
import subprocess
import time

logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()

log.debug("Initializing NetworkTables...")
NetworkTable.setIPAddress("roborio-4761-frc.local")
NetworkTable.setClientMode()
NetworkTable.initialize()
table = NetworkTable.getTable("control_daemon")
log.debug("NetworkTables intitialized!")

def reset_flags():
	log.debug("Setting default values for flags...")
	table.putBoolean("shutdown_flag", False)
	table.putBoolean("reboot_flag", False)
	log.debug("Default flag values set!")

reset_flags()

log.debug("Entering main loop...")

while True:
	table.putNumber("last_updated", time.time())
	if table.getBoolean("reboot_flag", False):
		reset_flags()
		log.info("Reboot flag is true! Rebooting...")
		subprocess.Popen(["reboot"])
Exemple #52
0
directory = 'C:/Users/Ithier/Documents/FIRST/2017/Off Season/'
filename = directory + 'imageValues.npz'  # folder npz file is in. NPZ file contains hsv values and brightness value
url = 0
debug = 1
validCount = 0  # how many valid targets we've found
n = 0
freqFramesNT = 10  # how often we're sending to network tables

#############################################################################
from networktables import NetworkTable
import logging

#if NetworkTable._staticProvider is None:
try:
    logging.basicConfig(level=logging.DEBUG)
    NetworkTable.setIPAddress('10.5.1.2')
    NetworkTable.setClientMode()
    NetworkTable.initialize()
except:
    if debug == 1:
        print("Network tables has already been initialized")

sd = NetworkTable.getTable("Camera")
#############################################################################
cap = cv2.VideoCapture(
    url
)  # capture camera, 0 is laptop cam, numbers after that are cameras attached
time.sleep(2)
# Check to make sure cap was initialized in capture
if debug:
    if cap.isOpened():
Exemple #53
0
from __future__ import print_function

from networktables import NetworkTable
from networktables.util import ChooserControl

import sys
import time

import logging
logging.basicConfig(level=logging.DEBUG)

NetworkTable.setIPAddress("127.0.0.1")
NetworkTable.setClientMode()
NetworkTable.initialize()

def foo(value):
    print("foo", value)

def bar(value):
    print("bar", value)

def valueChanged(key, value, isNew):
    print("valueChanged: %s = %s" % (key, value) )

NetworkTable.addGlobalListener(valueChanged)

cc = ChooserControl("control_preset",
                    foo,
                    bar)
sd = NetworkTable.getTable("SmartDashboard")
Exemple #54
0
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n",
                "--num-frames",
                type=int,
                default=100,
                help="# of frames to loop over for FPS test")
ap.add_argument("-d",
                "--display",
                type=int,
                default=-1,
                help="Whether or not frames should be displayed")
args = vars(ap.parse_args())

NetworkTable.setIPAddress(
    "roborio-2609-frc.local")  #Change the address to your own
NetworkTable.setClientMode()
NetworkTable.initialize()
sd = NetworkTable.getTable("RaspberryPi")

# grab a pointer to the video stream and initialize the FPS counter
print("[INFO] sampling frames from webcam...")
stream = cv2.VideoCapture(0)
fps = FPS().start()

# loop over some frames
while fps._numFrames < args["num_frames"]:
    # grab the frame from the stream and resize it to have a maximum
    # width of 640 pixels
    (grabbed, frame) = stream.read()
    frame = imutils.resize(frame, width=640)
Exemple #55
0
from networktables import NetworkTable

NetworkTable.setIPAddress("10.0.0.2")
NetworkTable.setClientMode()
NetworkTable.initialize()

table = NetworkTable.getTable("rpi")

table.putNumber("visionX", 2)
table.putNumber("visionY", 4)

print("done")
Exemple #56
0
def init_network_tables(ipAddress, table):
    NetworkTable.setIPAddress(ipAddress)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    vp = NetworkTable.getTable(table)
    return vp
Exemple #57
0
def main():

    # brightness adjusted, used to be 30, now is 70
    os.system("v4l2-ctl -d /dev/video0 "
              "-c brightness=70 "
              "-c contrast=10 "
              "-c saturation=100 "
              "-c white_balance_temperature_auto=0 "
              "-c power_line_frequency=2 "
              "-c white_balance_temperature=4500 "
              "-c sharpness=25 "
              "-c backlight_compensation=0 "
              "-c exposure_auto=1 "
              "-c exposure_absolute=5 "
              "-c pan_absolute=0 "
              "-c tilt_absolute=0 "
              "-c zoom_absolute=0")

    NetworkTable.setIPAddress("roboRIO-687-FRC.local")
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    table = NetworkTable.getTable("NerdyVision")
    print("NetworkTables initialized")

    angle_to_turn = 0

    while 687:

        aligned = False
        previous_angle_to_turn = angle_to_turn

        ret, frame = cap.read()
        capture_time = time.time()

        # blur = cv2.GaussianBlur(frame, (11, 11), 0)
        kernel = np.ones((5, 5), np.uint8)
        erosion = cv2.erode(frame, kernel, iterations=1)
        dilation = cv2.dilate(erosion, kernel, iterations=1)
        res, mask = NerdyFunctions.mask(NerdyConstants.LOWER_GREEN, NerdyConstants.UPPER_GREEN, dilation)

        _, cnts, _ = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
        center = None

        if len(cnts) > 1:
            centers_x = [0]
            centers_y = [0]

            for i in range(len(cnts)):
                c = cnts[i]
                area = cv2.contourArea(c)
#                if NerdyConstants.MIN_GEAR_AREA < area < NerdyConstants.MAX_GEAR_AREA:

                x, y, w, h = cv2.boundingRect(c)
                aspect_ratio = float(w) / h
                if NerdyConstants.MIN_GEAR_ASPECT < aspect_ratio < NerdyConstants.MAX_GEAR_ASPECT:

                    goal = NerdyFunctions.polygon(c, 0.02)
                    cv2.drawContours(res, [goal], 0, (255, 0, 0), 5)

                    M = cv2.moments(goal)
                    if M['m00'] > 0:
                        cx = int(M['m10'] / M['m00'])
                        cy = int(M['m01'] / M['m00'])
                        center = (cx, cy)

                        cv2.circle(res, center, 5, (255, 0, 0), -1)

                        centers_x.append(cx)
                        centers_y.append(cy)

            if len(centers_x) == 3 and len(centers_y) == 3:
                target_x = (centers_x[1] + centers_x[2])/2
                target_y = (centers_y[1] + centers_y[2])/2
                target = (target_x, target_y)
                cv2.circle(res, target, 5, (0, 255, 0), -1)
                print(target_x)
                print(target_y)

                error = target_x - NerdyConstants.FRAME_CX
                angle_to_turn = NerdyFunctions.calc_horiz_angle(error)
                print("ANGLE_TO_TURN: " + str(angle_to_turn))
                aligned = NerdyFunctions.is_aligned(angle_to_turn)
                print("IS_ALIGNED: " + str(aligned))

                processed_time = time.time()
                delta_time = processed_time - capture_time
                print("PROCESSED_TIME: " + str(delta_time))

        # NerdyFunctions.draw_static(res)
        # cv2.imshow("NerdyVision", res)
        try:
            table.putBoolean('IS_ALIGNED', aligned)
            if previous_angle_to_turn != angle_to_turn:
                table.putNumber('ANGLE_TO_TURN', angle_to_turn)
                table.putNumber('PROCESSED_TIME', delta_time)
            else :
                table.putNumber('ANGLE_TO_TURN', 0)
                table.putNumber('PROCESSED_TIME', 0)
            table.putBoolean('VISION_ON', True)
        except:
            print("DATA NOT SENDING...")
            table.putBoolean('IS_ALINGED', False)
            table.putNumber('ANGLE_TO_TURN', 0)
            table.putNumber('PROCESSED_TIME', 0)
            table.putBoolean('VISION_ON', False)

        cv2.waitKey(1)

    cap.release()
    cv2.destroyAllWindows()
Exemple #58
0
def makeNetworkTable(IP):
    NetworkTable.setIPAddress(IP)
    NetworkTable.setClientMode()
    NetworkTable.initialize()
    return NetworkTable.getTable("vision")
Exemple #59
0
- lscpu Max 900MHz
- Raspbian Jessie 4.1.17-v7+ #838 (2016/02/09)
Including all OpenCV and NetworkTable processing this averages:
- 7 FPS with Microsoft LifeCam HD 3000 (-vw 640 -vh 480)
- 28 FPS with Microsoft LifeCam HD 3000 (-vw 320 -vh 240)
'''

import copy
import math
import time

from networktables import NetworkTable
import logging

logging.basicConfig(level=logging.DEBUG)  # for pynetworktables
NetworkTable.setIPAddress("roboRIO-226-FRC.local")
NetworkTable.setClientMode()
NetworkTable.initialize()
table = NetworkTable.getTable("SharkCV")

FOV_DIAGONAL = 68.5  # Microsoft LifeCam HD 3000
DISTANCE_SIZE = [20, 14]  # 20x14in target


def Stronghold226(frame):
    orig = copy.deepcopy(frame)

    # THRESHOLD
    frame.color_hsv()
    mask = frame.threshold([75, 155, 55], [100, 255, 255])