We have this code, but can’t figure out why it doesn’t work.
import wpilib
import networktables
from networktables import NetworkTable
class Vision():
def init(self):
# NetworkTable.setIPAddress(“10.26.5.73”)
# NetworkTable.setServerMode()
self.table = NetworkTable.getTable(‘GRIP/myContoursReport’)
The first thing that I would recommend is using table viewer to ensure that the value is actually available. And, even if it’s not available, the retrieveValue API doesn’t have functionality to set a default value, so you should do one of two things:
Set a default value when your program starts up
Surround the retrieveValue() call with a try…except block
Finally, I tested the functionality, and you can use pynetworktables to retrieve a NumberArray. However, the retrieveValue function returns None, not an array. Therefore, the code you have above won’t work – but remove the assignment, and it should be fine:
table = NetworkTable.getTable('/GRIP/myContoursReport')
na = NumberArray()
...
try:
table.retrieveValue('centerX', na)
except KeyError:
# do something else here...
else:
print(na)
Oh, I didn’t see that quirk in the code (kids- always format your code in code blocks)
retrieveValue works like alot of C functions where it requests a pointer to put data into rather than returning the data itself (for reasons). The first argument is the name of the key (similar to how youd use getNumber(key,default)). The second argument isnt the argument but rather the variable that the return value will be placed into.
I now have the problem of connecting to GRIP. GRIP seems to be the server and in order to access the variables, you need to use the ClientMode. The problem with that is you need the IP of the server. GRIP is going to be running on our Driver Station and the IP will not stay the same.
How am I supposed to connect to GRIP?
Here is the working code(Just using GRIP locally by setting both to 127.0.0.1):
import sys
import time
from networktables import NetworkTable
import networktables
ip = "127.0.0.1"
NetworkTable.setIPAddress(ip)
NetworkTable.setClientMode()
NetworkTable.initialize()
table = NetworkTable.getTable('/GRIP/myContoursReport')
default = networktables.NumberArray()
while True:
try:
table.retrieveValue('centerX', default)
except KeyError:
pass
else:
print default
time.sleep(1)