def device_state_change(*args, **kwargs): global __devices global __network_status msg = kwargs['d_member'] path = kwargs['d_path'] device = NetworkManager.Device(path) newState = NetworkManager.const('device_state', args[0]) try: if device.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: connectionType = "Ethernet" elif device.DeviceType == NetworkManager.NM_DEVICE_TYPE_WIFI: connectionType = "Wifi" except: # D-Bus likely doesn't know about the device any longer, # this is typically a removable Wifi stick path = kwargs['d_path'] if path in __devices: connectionType = __devices[path]["type"] if newState == "activated": path = kwargs['d_path'] __devices[path] = {"type": connectionType, "active": True} if connectionType == "Ethernet": __network_status.ethernet = True if connectionType == "Wifi": __network_status.wifi = True send_unsent_batch() else: if connectionType == "Ethernet": __network_status.ethernet = False if connectionType == "Wifi": __network_status.wifi = False
def parse_flags(prefix='', *flags): if isinstance(flags, int): flags = [flags] flags = list(set(flags)) flag_list = [] for flag in flags: # parse single number, e.g. 0x02 try: flag_list.append(NetworkManager.const(prefix, flag)) except ValueError: if flag is None: continue else: continue # parse multiple bits, e.g. 0b01010010 bit = 0 while flag: if flag & 0b1: try: flag_list.append(NetworkManager.const(prefix, 1 << bit)) except ValueError: pass flag >>= 1 bit += 1 return [flag for flag in set(flag_list)]
def attacker_mode(victim_ip): arp_thread = threading.Thread(target=listen_data) arp_thread.daemon = True arp_thread.start() response_arp = NetworkManager.SecureArp() packet = ARP(op=ARP.is_at, hwsrc=MY_MAC, psrc=victim_ip, hwdst='cc:cc:cc:cc:cc:cc', pdst="192.168.1.64") response_arp.pkt = packet response_arp.sig = response_arp.sig_size * "A" print("Sending Malicious ARP Update:") response_arp.pkt.show() sock = NetworkManager.Socket('192.168.1.64', NetworkManager.ARP_PORT, server=False) sock.send_message(response_arp.serialize(), ('192.168.1.64', NetworkManager.ARP_PORT)) # NetworkManager.broadcast_packet(response_arp.serialize(), NetworkManager.ARP_PORT) while True: pass '''
def printable_active_connection(): if not len(NetworkManager.NetworkManager.ActiveConnections): return "off" printable = "" firstDevice = NetworkManager.NetworkManager.ActiveConnections[0].Devices[0] if firstDevice.Ip4Config: return "{} {} {}".format(NetworkManager.const("device_type", firstDevice.DeviceType), firstDevice.Interface, firstDevice.Ip4Config.Addresses[0][0]) else: return "{} {} obtaining ipv4...".format(NetworkManager.const("device_type", firstDevice.DeviceType), firstDevice.Interface)
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state), NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'signal': ord(ap.Strength), 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._setOnline(True) elif new_state in [ NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN ]: logger.warn( 'Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason))) eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason) }) # we should probably remove the connection self._activatingConnection.Delete() elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None self._setOnline(False)
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state),NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() if d.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': d.Ip4Address } }) else: ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire(Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._setOnline(True) elif new_state in [NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN]: logger.warn('Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason) ) ) eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason)}) # we should probably remove the connection self._activatingConnection.Delete() elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None #check the global connection status before setting it to false if NetworkManager.NetworkManager.state() != NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(False)
def _on_state_changed(self, nm, state, **kwargs): logger.info("State changed to %d: %s" % (state, NetworkManager.const('STATE', state))) if state >= NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._switch_to_normal_mode() elif state <= NetworkManager.NM_STATE_DISCONNECTED: self._switch_to_provisioning_mode()
def GetInfo(self): print "-"*50 print "Network manager info:" print("%-30s %s" % ("Version:", NetworkManager.NetworkManager.Version)) print("%-30s %s" % ("Hostname:", NetworkManager.Settings.Hostname)) print("%-30s %s" % ("Networking enabled:", NetworkManager.NetworkManager.NetworkingEnabled)) print("%-30s %s" % ("Overall state:", NetworkManager.const('state', NetworkManager.NetworkManager.State))) print "\nAvailable connections:" print("%-30s %s" % ("Name", "Type")) for conn in NetworkManager.Settings.ListConnections(): settings = conn.GetSettings()['connection'] if settings['type'] == 'gsm': print("%-30s %s" % (settings['id'], settings['type'])) print "\nActive connections:" print("%-30s %-20s %-10s %s" % ("Name", "Type", "Default", "Devices")) active_gsm = False for conn in NetworkManager.NetworkManager.ActiveConnections: settings = conn.Connection.GetSettings()['connection'] if settings['type'] == 'gsm': print("%-30s %-20s %-10s %s" % (settings['id'], settings['type'], conn.Default, ", ".join([x.Interface for x in conn.Devices]))) active_gsm = True if active_gsm == False: print "No gsm connections are active!" print "-"*50
def ca_mode(): FILEPATH = "DHCP/state.txt" if not os.path.isfile(FILEPATH): initialize_keys() else: print "File exists" # Key manager key_manager = create_key_manager() monitor = FileMonitor(time.time(), FILEPATH, key_manager) server_thread = threading.Thread(target=monitor.monitor) # Dont exit the server thread when the main thread terminates server_thread.daemon = True server_thread.start() ca_sock = NetworkManager.Socket(CA_IP, NetworkManager.CA_PORT, server=True) my_ip = netifaces.ifaddresses( get_interface())[netifaces.AF_INET][0]['addr'] # Read keys from file and initialize keys object - (pub,priv) keys = read_keys(my_ip) while True: query_size, addr = ca_sock.udp_recv_message(INT_SIZE, wait=True) if query_size: print("[*] Received update from host", str(addr[0])) monitor.mutex.acquire() ca_handle_query(monitor.manager, query_size, ca_sock, keys) # handles query and kills conn monitor.mutex.release()
def shutdown(): global state state = NetworkState.SHUTTING_DOWN netManager = NetworkManager.NetworkManager() netManager.turnOff() netManager.join() state = NetworkState.SHUT_DOWN
def initialise(): global state if state != NetworkState.UNINITIALISED: GeneralLogger().logger.warn( f'Network API already initialised, can\'t initialise now. [State={state}]' ) else: state = NetworkState.INITIALISING networkManager = NetworkManager.NetworkManager() networkManager.initialise()
def setUp(self): self.test_dir = os.path.join(FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data") self.last_result = None url = "https://api.github.com/zen" NetworkManager.InitializeNetworkManager() result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) if result is None: self.skipTest("No active internet connection detected")
def generate_network_manager(self, selected, stock_nr, rank): network_manager = nm.NetworkManager(self, selected, stock_nr, self.run_nr, self.rf_rate, self.soft_label, self.soft_label_percent) stock_result = network_manager.build_networks( number_of_networks=self.number_of_networks, epochs=self.epochs, rank=rank) self.add_to_stock_results(stock_result, network_manager) return stock_result
def globalStateChanged(self, state): #uncomment for debugging only logger.info('Network Global State Changed, new(%s)' % NetworkManager.const('state', state)) if state == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True) elif self._justActivatedConnection and state == NetworkManager.NM_STATE_CONNECTED_LOCAL: #local is a transition state when we have just activated a connection, so do nothing self._justActivatedConnection = False elif state != NetworkManager.NM_STATE_CONNECTING: self._setOnline(False)
def setUp(self): """Set up the test""" self.test_dir = os.path.join(FreeCAD.getHomePath(), "Mod", "AddonManager", "AddonManagerTest", "data") self.saved_mod_directory = Addon.mod_directory self.saved_cache_directory = Addon.cache_directory Addon.mod_directory = os.path.join(tempfile.gettempdir(), "FreeCADTesting", "Mod") Addon.cache_directory = os.path.join(tempfile.gettempdir(), "FreeCADTesting", "Cache") os.makedirs(Addon.mod_directory, mode=0o777, exist_ok=True) os.makedirs(Addon.cache_directory, mode=0o777, exist_ok=True) url = "https://api.github.com/zen" NetworkManager.InitializeNetworkManager() result = NetworkManager.AM_NETWORK_MANAGER.blocking_get(url) if result is None: self.skipTest("No active internet connection detected") self.macro_counter = 0 self.workbench_counter = 0 self.prefpack_counter = 0 self.addon_from_cache_counter = 0 self.macro_from_cache_counter = 0 self.package_cache = {} self.macro_cache = [] self.package_cache_filename = os.path.join(Addon.cache_directory, "packages.json") self.macro_cache_filename = os.path.join(Addon.cache_directory, "macros.json") if not TestWorkersInstallation.addon_list: self._create_addon_list() # Workbench: use the FreeCAD-Help workbench for testing purposes self.help_addon = None for addon in self.addon_list: if addon.name == "Help": self.help_addon = addon break if not self.help_addon: print("Unable to locate the FreeCAD-Help addon to test with") self.skipTest("No active internet connection detected") # Store the user's preference for whether git is enabled or disabled pref = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Addons") self.saved_git_disabled_status = pref.GetBool("disableGit", False)
def fetch_station_index_pages(station_sources): parsed_sources = [] for station_source in station_sources: list_of_stations_html = NetworkManager.fetch(WIKI_LINK, station_source) source_type = None if "dockland" in station_source.lower(): source_type = "dockland" if "underground" in station_source.lower(): source_type = "underground" parsed_sources.append((BeautifulSoup(list_of_stations_html, 'html.parser'), source_type)) return parsed_sources
def check_state(device, timeout=60): """Continue querying network status and printing new values to console. Return when network is ready. """ time_delta = 0.01 state_last = -1 time_0 = time.time() try: while True: state, reason = device.StateReason if state != state_last: state_last = state time_0 = time.time() state_str = NM.const('device_state', state) reason_str = NM.const('device_state_reason', reason) if reason: msg = '{} [{}]'.format(state_str, reason_str) else: msg = '{}'.format(NM.const('device_state', state)) print(msg) if state_str == 'activated': print('connected: {}'.format(current_connection())) return time.sleep(time_delta) if time.time() - time_0 > timeout: return except KeyboardInterrupt: return
def run(self): self._stopped = False self._loop = GLib.MainLoop() self._propertiesListener = NetworkManager.NetworkManager.connect_to_signal( 'PropertiesChanged', self.propertiesChanged) self._stateChangeListener = NetworkManager.NetworkManager.connect_to_signal( 'StateChanged', self.globalStateChanged) self._devicePropertiesListener = None self._monitorActivatingListener = None connectionState = NetworkManager.NetworkManager.State logger.info('Network Manager reports state: *[%s]*' % NetworkManager.const('state', connectionState)) if connectionState == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True) #d = self.getActiveConnectionDevice() #if d: # self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged) # self._currentIpv4Address = d.Ip4Address # self._activeDevice = d # self._online = True # logger.info('Active Connection found at %s (%s)' % (d.IpInterface, d.Ip4Address)) while not self._stopped: try: self._loop.run() except KeyboardInterrupt: #kill the main process too from octoprint import astrobox astrobox.stop() except DBusException as e: #GObject.idle_add( # logger.error, 'Exception during NetworkManagerEvents: %s' % e) logger.error('Exception during NetworkManagerEvents: %s' % e) finally: self.stop()
def get_public_key(sock, ip): ca_sock = NetworkManager.Socket(CA_IP, NetworkManager.CA_PORT) nonce = str(uuid.uuid4()) debug("Generated nonce for CA: " + nonce) query = {QUERY_TYPE: GET_QUERY_TYPE, IP_QUERY: ip, NONCE: nonce} ca_sock.send_message(struct.pack("!I", len(query)), (CA_IP, NetworkManager.CA_PORT)) ca_sock.send_message(str(query), (CA_IP, NetworkManager.CA_PORT)) data, addr = ca_sock.udp_recv_message(INT_SIZE, wait=True) query_size = int(struct.unpack("!I", data)[0]) data, addr = ca_sock.udp_recv_message(query_size, wait=True) debug("Received " + str(len(data)) + " bytes") ca_keys = read_keys(CA_IP) sig = data[:SIG_SIZE] public_key = data[SIG_SIZE:] if not validate_sig(nonce, sig, ca_keys.publicKey.exportKey('DER')): return None debug("Validated Sig from CA") return public_key
def run(self): self._stopped = False self._loop = GLib.MainLoop() self._propertiesListener = NetworkManager.NetworkManager.connect_to_signal('PropertiesChanged', self.propertiesChanged) self._stateChangeListener = NetworkManager.NetworkManager.connect_to_signal('StateChanged', self.globalStateChanged) self._devicePropertiesListener = None self._monitorActivatingListener = None connectionState = NetworkManager.NetworkManager.State logger.info('Network Manager reports state: *[%s]*' % NetworkManager.const('state', connectionState)) if connectionState == NetworkManager.NM_STATE_CONNECTED_GLOBAL: self._setOnline(True) #d = self.getActiveConnectionDevice() #if d: # self._devicePropertiesListener = d.Dhcp4Config.connect_to_signal('PropertiesChanged', self.activeDeviceConfigChanged) # self._currentIpv4Address = d.Ip4Address # self._activeDevice = d # self._online = True # logger.info('Active Connection found at %s (%s)' % (d.IpInterface, d.Ip4Address)) while not self._stopped: try: self._loop.run() except KeyboardInterrupt: #kill the main process too from octoprint import astrobox astrobox.stop() except DBusException as e: #GObject.idle_add(logger.error, 'Exception during NetworkManagerEvents: %s' % e) logger.error('Exception during NetworkManagerEvents: %s' % e) finally: self.stop()
def PingLoggerThread(): pingTime = time.time() + GlobalVals.PING_INTERVAL timeToPing = False while True: with GlobalVals.BREAK_PING_THREAD_MUTEX: if GlobalVals.BREAK_PING_THREAD: break currentTime = time.time() if currentTime >= pingTime: timeToPing = True else: time.sleep(0.2) continue if timeToPing: # change values timeToPing = False pingTime = time.time() + GlobalVals.PING_INTERVAL pingStrings = [] # get list of system IDs systemList = NetworkManager.RequestSystemsList() if len(systemList) == 0: continue # get ping for each system for x in systemList: ping = NetworkManager.PingTarget(x) reportTime = int(time.time()) if ping == -1: pingStrings.append("Time: " + str(reportTime) + ", System " + str(x) + ", ERROR: Invalid system ID.\n") elif ping == -2: pingStrings.append("Time: " + str(reportTime) + ", System " + str(x) + ", ERROR: Ping timed out.\n") else: pingStrings.append("Time: " + str(reportTime) + ", System " + str(x) + ", Ping: " + str(ping) + "\n") # Open log file try: fileObj = open(GlobalVals.PING_LOG_FILE, "a") except Exception as e: print("Ping Logger: Error opening file. Now breaking thread.") print("Ping Logger: Exception: " + str(e.__class__)) with GlobalVals.BREAK_PING_THREAD_MUTEX: GlobalVals.BREAK_PING_THREAD = True break # Write to log file try: for x in pingStrings: fileObj.write(x) except Exception as e: print( "Ping Logger: Error writting to file. Now breaking thread." ) print("Ping Logger: Exception: " + str(e.__class__)) with GlobalVals.BREAK_PING_THREAD_MUTEX: GlobalVals.BREAK_PING_THREAD = True break finally: fileObj.close()
else: lockFile.lock() try: FPSCounter = FPS() FPSCounter.start() cam = cv2.VideoCapture(0) cam.set(3, 640) cam.set(4, 480) # cam.set(cv2.cv.CV_CAP_PROP_BRIGHTNESS, brightness) # cam.set(cv2.cv.CV_CAP_PROP_SATURATION, saturation) # cam.set(cv2.cv.CV_CAP_PROP_EXPOSURE, exposure) # not working on the old camera visionManager = VisionManager(LB, UB, MBR, cam, KH, KW, FL, [RH, RW, RL], TH, CUW, CUWD, HAX, HAY) networkManager = NetworkManager(JAVA_IP, 8080) ################### # The code itself # ################### while True: visionManager.updateImage() visionManager.updateTowerScales() visionManager.updateRobotScales() FPSCounter.update() if visionManager.isObjectDetected: # if an object was detected ######################
i: 255(t) o: 312() nname: 255 n 255(func_name.startswith('magic'))[for func_name, func in locals().items(): ]: i: 239(for) o: 279(t), 312(f) nname: 239 n 239(None)[]: i: 98(loop) o: 255(for), 316(AF) nname: 98 n 98(None)[NM = NetworkManager() ipshell = IPShellEmbed() def _get_device_by_name(dev_name): devs = NM.get_devices() d = filter((lambda dev: dev.get_name() == dev_name), devs) if d == []: raise NameError('No such interface (%s)' % dev_name) return d[0] def _get_network_by_name(dev, essid): nets = dev.get_networks() n = filter((lambda net: net.get_name() == essid), nets) if n == []: raise NameError('No such ESSID (%s)' % net_name) return n[0]
def EKFLoggerSocket(): # set up socket while True: try: socket_logger = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_logger.connect( (GlobalVals.HOST, GlobalVals.EKF_LOGGER_SOCKET)) socket_logger.settimeout(GlobalVals.EKF_LOGGER_SOCKET_TIMEOUT) except Exception as e: if e.args[1] == 'Connection refused': print('Retry connecting to EKF....') time.sleep(1) continue else: print("Exception: " + str(e.__class__)) print( "There was an error starting the EKFlogger socket. This thread will now stop." ) with GlobalVals.BREAK_EKF_LOGGER_THREAD_MUTEX: GlobalVals.BREAK_EKF_LOGGER_THREAD = True return break print('Connected to EKF!!!') # intialize variables bufferRead = 1024 breakMainThread = False while True: # if flag is set break the thread with GlobalVals.BREAK_EKF_LOGGER_THREAD_MUTEX: if GlobalVals.BREAK_EKF_LOGGER_THREAD: break # read the socket while True: try: data_bytes = socket_logger.recv(bufferRead) # print("EKF socket received") break except Exception as e: if e.args[0] == 'timed out': print("EKFLoggerSocket() Receive timed out. Retrying...") time.sleep(0.1) continue else: print("EKFLoggerSocket(): Receive Connection error.") breakMainThread = True break if breakMainThread: break # print("EKF socket received2") # if there is nothing in the socket then it has timed out if len(data_bytes) == 0: continue data_str = data_bytes.decode('utf-8') # print("EKF socket received3") # print(data_str) # print('---') string_list = extract_str_btw_curly_brackets(data_str) if len(string_list) > 0: ekf_list = [] for string in string_list: received, ekf_i = stringToEKF(string) if received: ekf_list.append(ekf_i) idx = 0 # with GlobalVals.EKF_UPDATE_MUTEX: while idx < len(ekf_list): ekf_update(ekf_list[idx]) idx += 1 ekf = copy.deepcopy(GlobalVals.EKF_ALL) EKF_Data = CustMes.MESSAGE_EKF() EKF_Data.Longitude = ekf.lon EKF_Data.Latitude = ekf.lat EKF_Data.Altitude = ekf.alt EKF_Data.Epoch = ekf.epoch EKF_Data.SystemID = ekf.sysID EKF_Data.PosX = ekf.posX EKF_Data.PosY = ekf.posY EKF_Data.P00 = ekf.p00 EKF_Data.P01 = ekf.p01 EKF_Data.P10 = ekf.p10 EKF_Data.P11 = ekf.p11 # add data to the gps buffer # with GlobalVals.EKF_DATA_BUFFER_MUTEX: # GlobalVals.EKF_DATA_BUFFER.append(EKF_Data) # set the flag for the data # with GlobalVals.RECIEVED_EKF_LOCAL_DATA_MUTEX: # GlobalVals.RECIEVED_EKF_LOCAL_DATA = True # send GPS data to other balloons EKF_Packet = CustMes.MESSAGE_FRAME() EKF_Packet.SystemID = GlobalVals.SYSTEM_ID EKF_Packet.MessageID = 5 EKF_Packet.TargetID = 0 EKF_Packet.Payload = EKF_Data.data_to_bytes() NetworkManager.sendPacket(EKF_Packet) # print(EKF_Data.Longitude) # print("***************************") # pause a little bit so the mutexes are not getting called all the time time.sleep(1) socket_logger.close() return
def RSSI_AllocationDistributor(): # print("RSSI ALLOCATION DISTRIBUTOR 1") Distro_Socket = [None]*len(GlobalVals.RSSI_ALLOCATION_DISTRO_SOCKET) Distro_Connection = [None]*len(GlobalVals.RSSI_ALLOCATION_DISTRO_SOCKET) for i in range(len(GlobalVals.RSSI_ALLOCATION_DISTRO_SOCKET)): # start socket Distro_Socket[i] = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Distro_Socket[i].setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) Distro_Socket[i].bind((GlobalVals.HOST, GlobalVals.RSSI_ALLOCATION_DISTRO_SOCKET[i])) Distro_Socket[i].settimeout(GlobalVals.RSSI_LOGGER_SOCKET_TIMEOUT) # Wait for connection on the distro socket try: Distro_Socket[i].listen(1) Distro_Connection[i], addr = Distro_Socket[i].accept() Distro_Connection[i].settimeout(GlobalVals.RSSI_LOGGER_SOCKET_TIMEOUT) print("RSSI Allocation Logger[",i,"] Connected to ", addr) except Exception as e: print("Exception: " + str(e.__class__)) print("Error in the RSSI_Allocation Distributor[",i,"] logger socket. Now closing thread.") with GlobalVals.BREAK_RSSI_ALLOCATION_DISTRO_THREAD_MUTEX: GlobalVals.BREAK_RSSI_ALLOCATION_DISTRO_THREAD = True return 0 breakThread = False nextPair = 1 while True: # print("RSSI ALLOCATION DISTRIBUTOR 2") if breakThread: break with GlobalVals.BREAK_RSSI_ALLOCATION_DISTRO_THREAD_MUTEX: if GlobalVals.BREAK_RSSI_ALLOCATION_DISTRO_THREAD: break # print("RSSI ALLOCATION DISTRIBUTOR 3") if GlobalVals.SYSTEM_ID == 1: with GlobalVals.NEXT_PAIR_MUTEX: nextPair = GlobalVals.NEXT_PAIR else: with GlobalVals.RSSI_DATA_ALLOCATION_BUFFER_MUTEX: if len(GlobalVals.RSSI_DATA_ALLOCATION_BUFFER) > 0: RSSI_DataAllocation = GlobalVals.RSSI_DATA_ALLOCATION_BUFFER.pop(0) nextPair = RSSI_DataAllocation messageStr = "{'pair': " + str(nextPair) +";}" messageStr_bytes = messageStr.encode('utf-8') # print("Send Pair Num to RFD900") # print('Allocated pair: '+messageStr) # send the message for i in range(len(GlobalVals.RSSI_ALLOCATION_DISTRO_SOCKET)): try: Distro_Connection[i].sendall(messageStr_bytes) except Exception as e: print("Exception: " + str(e.__class__)) print("Error when sending to RSSI Allocation Distro_Connection[",i,"]. Now closing thread.") breakThread = True time.sleep(1) break # Send via RFD900 network if GlobalVals.SYSTEM_ID == 1: RSSI_Allocation = CustMes.MESSAGE_RSSI_ALLOCATION() RSSI_Allocation.Pair = GlobalVals.NEXT_PAIR RSSI_AllocationPacket = CustMes.MESSAGE_FRAME() RSSI_AllocationPacket.SystemID = GlobalVals.SYSTEM_ID RSSI_AllocationPacket.MessageID = 8 RSSI_AllocationPacket.TargetID = 0 RSSI_AllocationPacket.Payload = RSSI_Allocation.data_to_bytes() NetworkManager.sendPacket(RSSI_AllocationPacket) # print("sending RSSI ALLOCATOR (pair: ",RSSI_Allocation.Pair,") from 1...") time.sleep(0.5) # while True: # print("Closing RSSI Allocation Distro !!!!!!!!!") # time.sleep(0.5) for i in range(GlobalVals.N_RSSI_NODE_PUBLISH): Distro_Connection[i].close()
def RSSI_LoggerSocket(host,port,index): # set up socket while True: try: socket_logger = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_logger.connect((host,port)) socket_logger.settimeout(GlobalVals.RSSI_LOGGER_SOCKET_TIMEOUT) except Exception as e: if e.args[1] == 'Connection refused': print('Retry connecting to RSSI....') time.sleep(1) continue else: print("Exception: " + str(e.__class__)) print("There was an error starting the RSSI Logger socket. This thread will now stop.") with GlobalVals.BREAK_RSSI_LOGGER_THREAD_MUTEX[index]: GlobalVals.BREAK_RSSI_LOGGER_THREAD[index] = True return break print('Connected to RSSI[',index,'], Port: ',port,'!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!') # intialize variables bufferRead = 1024 breakMainThread = False while True: # if flag is set break the thread with GlobalVals.BREAK_RSSI_LOGGER_THREAD_MUTEX[index]: if GlobalVals.BREAK_RSSI_LOGGER_THREAD[index]: break # read the socket while True: try: data_bytes = socket_logger.recv(bufferRead) # print("data received[",index,"]") break except Exception as e: if e.args[0] == 'timed out': print("RSSI_LoggerSocket Receive Time Out for Index [",index,"]. Retrying ...") time.sleep(0.1) continue else: print("RSSI_LoggerSocket Connection error.") breakMainThread = True break if breakMainThread: break # if there is nothing in the socket then it has timed out if len(data_bytes) == 0: continue data_str = data_bytes.decode('utf-8') string_list = extract_str_btw_curly_brackets(data_str) if len(string_list) > 0: # print("len string: ", len(string_list)) rssi_list = [] for string in string_list: received, rssi_i = stringToRSSI(string) if received: rssi_list.append(rssi_i) idx = 0 # print("check lenstring 1") with GlobalVals.RSSI_UPDATE_MUTEX[index]: while idx < len(rssi_list): # print("len rssi_list: ",len(rssi_list), "idx: ",idx) rssi_update(rssi_list[idx]) idx += 1 # with GlobalVals.RSSI_UPDATE_MUTEX[index]: rssi_i = copy.deepcopy(GlobalVals.RSSI_ALL) # print(rssi_i) # print("check lenstring 2") RSSI_Data = CustMes.MESSAGE_RSSI() RSSI_Data.FilteredRSSI = rssi_i.rssi_filtered RSSI_Data.Distance = rssi_i.distance RSSI_Data.Epoch = rssi_i.epoch RSSI_Data.SystemID = GlobalVals.SYSTEM_ID RSSI_Data.TargetPayloadID = int(findTargetPayloadID(index)) # print("check lenstring 3") # add data to the gps buffer with GlobalVals.RSSI_DATA_BUFFER_MUTEX: GlobalVals.RSSI_DATA_BUFFER.append(RSSI_Data) # print("check lenstring 4") # # set the flag for the data with GlobalVals.RECIEVED_RSSI_LOCAL_DATA_MUTEX: # 2 nodes? GlobalVals.RECIEVED_RSSI_LOCAL_DATA = True # print("check lenstring 5") with GlobalVals.RSSI_ALLOCATION_MUTEX: # print("UPDATE RSSI ALLOCATION MATRIX LOCALLYYYY") # print(GlobalVals.RSSI_ALLOCATION) GlobalVals.RSSI_ALLOCATION[GlobalVals.SYSTEM_ID-1][RSSI_Data.TargetPayloadID-1] = True # print("check lenstring 6") # send GPS data to other balloons RSSI_Packet = CustMes.MESSAGE_FRAME() RSSI_Packet.SystemID = GlobalVals.SYSTEM_ID RSSI_Packet.MessageID = 7 RSSI_Packet.TargetID = 0 RSSI_Packet.Payload = RSSI_Data.data_to_bytes() NetworkManager.sendPacket(RSSI_Packet) # print(RSSI_Data) # print(RSSI_Packet.Payload) print("SENDING RSSI TO RFD900: "+", RSSI Distance:" + str(RSSI_Data.Distance) + ", Filtered RSSI: " + str(RSSI_Data.FilteredRSSI) + ", TargetPayloadID: " + str(RSSI_Data.TargetPayloadID) + ", SysID: " + str(RSSI_Data.SystemID)) # print("check lenstring 5") # print(index) # print(RSSI_Data) # print("***************************") # pause a little bit so the mutexes are not getting called all the time time.sleep(0.1) # while True: # print("RSSI TO RFD900 SOCKET CLOSE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!") # time.sleep(0.5) socket_logger.close() return
def GPSLoggerSocket(): # set up socket try: socket_logger = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_logger.connect((GlobalVals.HOST, GlobalVals.GPS_LOGGER_SOCKET)) socket_logger.settimeout(GlobalVals.GPS_LOGGER_SOCKET_TIMEOUT) except Exception as e: print("Exception: " + str(e.__class__)) print("There was an error starting the GPSLoggerSocket logger socket. This thread will now stop.") print("GPS_PORT: ",GlobalVals.GPS_LOGGER_SOCKET) print("GPS_TIMEOUT: ",GlobalVals.GPS_LOGGER_SOCKET_TIMEOUT ) with GlobalVals.BREAK_GPS_LOGGER_THREAD_MUTEX: GlobalVals.BREAK_GPS_LOGGER_THREAD = True return # intialize variables synced = False syncA = False syncB = False bufferRead = 1 breakMainThread = False while True: # if flag is set break the thread with GlobalVals.BREAK_GPS_LOGGER_THREAD_MUTEX: if GlobalVals.BREAK_GPS_LOGGER_THREAD: break # reset buffer read when not synced if not synced: bufferRead = 1 # read the socket while True: try: data_bytes = socket_logger.recv(bufferRead) break except Exception as e: if e.args[0] == 'timed out': print("GPSLoggerSocket receive timed out. Retrying ...") time.sleep(0.1) continue else: print("GPSLoggerSocket: Receive Connection error.") breakMainThread = True break if breakMainThread: break # if there is nothing in the socket then it has timed out if len(data_bytes) == 0: continue # for the sync bytes (0xAA 0x55) if not synced: if data_bytes[0] == 0xAA and not syncA: syncA = True bufferRead = 1 continue elif data_bytes[0] == 0x55 and syncA: syncB = True bufferRead = 32 else: syncA = False syncB = False bufferRead = 1 continue # if both bytes have been found in order then the socket buffer is synced if syncA and syncB: synced = True syncA = False syncB = False continue # once it is scyned read the rest of the data if synced and bufferRead == 32: # convert payload values back to double LongitudeTuple = struct.unpack('!d',data_bytes[0:8]) LatitudeTuple = struct.unpack('!d',data_bytes[8:16]) AltitudeTuple = struct.unpack('!d',data_bytes[16:24]) GPSTimeTuple = struct.unpack('!d',data_bytes[24:32]) # store converted values Longitude = LongitudeTuple[0] Latitude = LatitudeTuple[0] Altitude = AltitudeTuple[0] GPSTime = GPSTimeTuple[0] # Debug message #print(str(GPSTime) + "," + str(Longitude) + "," + str(Latitude) + "," + str(Altitude) + "\n") # use GPS message payload to store value GPSData = CustMes.MESSAGE_GPS() GPSData.Longitude = Longitude GPSData.Latitude = Latitude GPSData.Altitude = Altitude GPSData.GPSTime = GPSTime GPSData.SystemID = GlobalVals.SYSTEM_ID # add data to the gps buffer with GlobalVals.GPS_DATA_BUFFER_MUTEX: GlobalVals.GPS_DATA_BUFFER.append(GPSData) # set the flag for the data with GlobalVals.RECIEVED_GPS_LOCAL_DATA_MUTEX: GlobalVals.RECIEVED_GPS_LOCAL_DATA = True # send GPS data to other balloons GPSPacket = CustMes.MESSAGE_FRAME() GPSPacket.SystemID = GlobalVals.SYSTEM_ID GPSPacket.MessageID = 2 GPSPacket.TargetID = 0 GPSPacket.Payload = GPSData.data_to_bytes() NetworkManager.sendPacket(GPSPacket) # print("SEND GPS TO RFD900!!!!!!") # reset synced = False # pause a little bit so the mutexes are not getting called all the time time.sleep(0.01) socket_logger.close() return
if lockFile.is_locked(): raise ValueError("Lock File Locked!") else: lockFile.lock() args = parse_arguments() try: vision_manager = VisionManager() except ValueError, ex: logger.error("Failed initializing VisionManager: %s", ex.message) raise if args.enable_network: try: network_manager = NetworkManager(args.host, args.port) except Exception, ex: logger.error("Unhandled Exception:\n" + traceback.format_exc()) raise else: network_manager = None FPSCounter = FPS() FPSCounter.start() try: read_frames = 0 # the number of frames read so far while True: if args.dump_image and (read_frames % 30 == 0): save_frame_path = "current.png"
def initialize(self): self.__device=NetworkManager.const('device_type', 2) self._status=NetworkManager.const('state', 40) self._dospeed, self._upspeed = self.speed_test()
def main(): recievedPackets = False sendTime = int(time.time() + 1) # this loop will wait for packets and then process them while True: curTime = int(time.time()) # send dummy GPS data once a second if curTime >= sendTime: sendTime = curTime + 1 GPSpacket = CustMes.MESSAGE_FRAME() GPSdata = CustMes.MESSAGE_GPS() # set up GPS packet GPSpacket.MessageID = 0x02 GPSpacket.TargetID = 0 GPSpacket.SystemID = GlobalVals.SYSTEM_ID # load dummy GPS data GPSdata.Longitude = 77.77 GPSdata.Latitude = 88.88 GPSdata.Altitude = 99.99 GPSdata.GPSTime = 100.01 # send dummy GPS packet GPSpacket.Payload = GPSdata.data_to_bytes() NetworkManager.sendPacket(GPSpacket) # check if packets have been recived with GlobalVals.RECIEVED_PACKETS_MUTEX: if GlobalVals.RECIEVED_PACKETS: recievedPackets = True # if no packets have been recived then sleep and loop if not recievedPackets: continue else: recievedPackets = False # go through all the packets in the buffer with GlobalVals.PACKET_BUFFER_IN_MUTEX: while len(GlobalVals.PACKET_BUFFER_IN) > 0: recievedPacket = GlobalVals.PACKET_BUFFER_IN.pop(0) # if the packet is a ping if recievedPacket.MessageID == 1: NetworkManager.PingRespond(recievedPacket.SystemID, recievedPacket.Timestamp) # if the packet is a GPS data packet if recievedPacket.MessageID == 2: # get the GPS data recData = CustMes.MESSAGE_GPS() error = recData.bytes_to_data(recievedPacket.Payload) if error != 0: print("Dummy Radio 1: GPS data error " + str(error) + ".\n") continue print("GPS Data from " + str(recievedPacket.SystemID) + ":") print("Lon:" + str(recData.Longitude) + ", Lat:" + str(recData.Latitude) + ", Alt:" + str(recData.Altitude) + ", Time:" + str(recData.GPSTime) + "\n") continue # if the packet is string message if recievedPacket.MessageID == 3: # get the string StrData = CustMes.MESSAGE_STR() error = StrData.bytes_to_data(recievedPacket.Payload) if error != 0: print("Dummy Radio 2: Message error " + str(error) + ".\n") continue # print string print(StrData.MessageStr) continue
def monitorActivatingConnection(self, new_state, old_state, reason): logger.info('Activating State Change %s -> %s' % (NetworkManager.const('device_state', old_state), NetworkManager.const('device_state', new_state))) if self._activatingConnection: if new_state == NetworkManager.NM_DEVICE_STATE_ACTIVATED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None d = self.getActiveConnectionDevice() if d.DeviceType == NetworkManager.NM_DEVICE_TYPE_ETHERNET: eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'ethernet', 'ip': d.Ip4Address } }) else: ap = d.SpecificDevice().ActiveAccessPoint eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'connected', 'info': { 'type': 'wifi', 'signal': ap.Strength, 'name': ap.Ssid, 'ip': d.Ip4Address } }) self._activatingConnection = None self._justActivatedConnection = True self._setOnline(True) elif new_state in [ NetworkManager.NM_DEVICE_STATE_FAILED, NetworkManager.NM_DEVICE_STATE_UNKNOWN ]: logger.warn( 'Connection reached state %s, reason: %s' % (NetworkManager.const('device_state', new_state), NetworkManager.const('device_state_reason', reason))) #It has reached and end state. self._activatingConnection = None if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire( Events.INTERNET_CONNECTING_STATUS, { 'status': 'failed', 'reason': NetworkManager.const('device_state_reason', reason) }) elif new_state == NetworkManager.NM_DEVICE_STATE_DISCONNECTED: if self._monitorActivatingListener: self._monitorActivatingListener.remove() self._monitorActivatingListener = None eventManager.fire(Events.INTERNET_CONNECTING_STATUS, {'status': 'disconnected'}) self._activatingConnection = None
def statechange(nm, interface, signal, state): out("State changed to %s" % NetworkManager.const('STATE', state))
if wireless_device is not None: # Get the currently active VPN connection. # If you're running some kind of weird, three active VPNs scenario, then... # Change this code to work in your use-case. active = NetworkManager.NetworkManager.ActiveConnections for a in active: if "vpn" in a.Type: current_vpn = a # Choose a random one to connect to. We use the far more secure random method, with a larger seed, # to try and prevent the random generation from being a predictable pattern (well, to try to make # it far less predictable with our sample, at least). rand = random.SystemRandom(os.urandom(99999999)) random_int = rand.randint(0, (vpns.__len__() - 1)) random_vpn = vpns.__getitem__(random_int) new_connection = NetworkManager.Connection(random_vpn) # Validate that we have a current VPN connection to disconnect from before we do. if current_vpn is not None: # Disconnect the old & busted. NetworkManager.NetworkManager.DeactivateConnection(current_vpn) # To prevent collision in NetworkManager, we allow background clean-up before reconnecting. time.sleep(10) # Connect the new hotness. print("Connecting to: {}".format(random_vpn)) NetworkManager.NetworkManager.ActivateConnection(new_connection, wireless_device, "/") # No wireless interfaces were found, so let's abort.
def __device_class_patch(typ): try: return NM.device_class_orig(typ) except KeyError: return NM.Generic
def __init__(self): self.running = True self.waitingQueue = deque() self.networkManager = NetworkManager(self) self.battles = []
def main(): recievedPackets = False # sendTime = int(time.time() + 1) # this loop will wait for packets and then process them while True: # check if packets have been recived with GlobalVals.RECIEVED_PACKETS_MUTEX: if GlobalVals.RECIEVED_PACKETS: recievedPackets = True # if no packets have been recived then sleep and loop if not recievedPackets: time.sleep(0.1) continue else: recievedPackets = False # go through all the packets in the buffer recievedPacket = CustMes.MESSAGE_FRAME() with GlobalVals.PACKET_BUFFER_IN_MUTEX: while len(GlobalVals.PACKET_BUFFER_IN) > 0: recievedPacket = GlobalVals.PACKET_BUFFER_IN.pop(0) # if the packet is a ping if recievedPacket.MessageID == 1: NetworkManager.PingRespond(recievedPacket.SystemID, recievedPacket.Timestamp) # if the packet is a GPS data packet if recievedPacket.MessageID == 2: # get the GPS data GPSdata = CustMes.MESSAGE_GPS() error = GPSdata.bytes_to_data(recievedPacket.Payload) if error != 0: print("Radio Network Main: GPS data error " + str(error)) continue # print("GPS Data from " + str(recievedPacket.SystemID) + ":") # print("Lon:" + str(round(GPSdata.Longitude,3)) + ", Lat:" + str(round(GPSdata.Latitude,3)) + ", Alt:" + str(round(GPSdata.Altitude,2)) + ", Time:" + str(GPSdata.GPSTime) + "\n") # set the system id for the GPS data GPSdata.SystemID = recievedPacket.SystemID if not GPSHandler.GPS_FormatCheck(GPSdata): print( "GPS message via RFD900 was broken. Discard it...") continue # print("GPS Data from " + str(recievedPacket.SystemID) + ":") # print("Lon:" + str(round(GPSdata.Longitude,3)) + ", Lat:" + str(round(GPSdata.Latitude,3)) + ", Alt:" + str(round(GPSdata.Altitude,2)) + ", Time:" + str(GPSdata.GPSTime) + "\n") # update GPS_Log with GlobalVals.GPS_LOG_MUTEX: update_GPS_Log(GPSdata) distance = distanceMatrixCalculation( GlobalVals.GPS_ALL, 0) print( "--------------------------------------------------------------------------------------------------" ) print("GPS GPS GPS " + str(recievedPacket.SystemID) + str(recievedPacket.SystemID) + str(recievedPacket.SystemID) + ":" + " Lon:" + str(round(GPSdata.Longitude, 3)) + ", Lat:" + str(round(GPSdata.Latitude, 3)) + ", Alt:" + str(round(GPSdata.Altitude, 1)) + ", Time:" + str(round(GPSdata.GPSTime, 1))) print('Distance from GPS [m]:\n', distance) # put data into the buffer # with GlobalVals.GPS_DATA_BUFFER_MUTEX: # GlobalVals.GPS_DATA_BUFFER.append(GPSdata) # set the flags for the buffer # with GlobalVals.RECIEVED_GPS_RADIO_DATA_MUTEX: # GlobalVals.RECIEVED_GPS_RADIO_DATA = True continue # if the packet is string message if recievedPacket.MessageID == 3: # get the string StrData = CustMes.MESSAGE_STR() error = StrData.bytes_to_data(recievedPacket.Payload) if error != 0: print("Packet error, packet will be discarded.\n") continue # print string print(StrData.MessageStr) continue # if the packet is an EKF GPS data packet if recievedPacket.MessageID == 5: # get the GPS data EKF_Data = CustMes.MESSAGE_EKF() error = EKF_Data.bytes_to_data(recievedPacket.Payload) if error != 0: print("Radio Network Main: EKF data error " + str(error)) continue # set the system id for the GPS data EKF_Data.SystemID = recievedPacket.SystemID if not EKFHandler.EKF_FormatCheck(EKF_Data): print( "EKF message via RFD900 was broken. Discard it...") continue # update GPS_Log with GlobalVals.EKF_LOG_MUTEX: update_EKF_Log(EKF_Data) distance = distanceEKF_MatrixCalculation( GlobalVals.GPS_ALL, 0, ) print( "==================================================================================================" ) print("EKF EKF EKF " + str(recievedPacket.SystemID) + str(recievedPacket.SystemID) + str(recievedPacket.SystemID) + ":" + " Lon:" + str(round(EKF_Data.Longitude, 3)) + ", Lat:" + str(round(EKF_Data.Latitude, 3)) + ", Alt:" + str(round(EKF_Data.Altitude, 1)) + ", Time:" + str(round(EKF_Data.Epoch, 1))) print('Distance from EKF [m]:\n', distance) continue # if the packet is an temperature data packet # Temperature if recievedPacket.MessageID == 6: # get the RSSI data temperatureData = CustMes.MESSAGE_TEMP() error = temperatureData.bytes_to_data( recievedPacket.Payload) if error != 0: print("Radio Network Main: temperature data error " + str(error)) continue # set the system id for the GPS data temperatureData.SystemID = recievedPacket.SystemID if not TemperatureHandler.temperatureFormatCheck( temperatureData): print( "Temperature message via RFD900 was broken. Discard it..." ) continue tempur = TEMPERATURE(temperatureData.SystemID, temperatureData.Temperature, temperatureData.Epoch) with GlobalVals.TEMPERATURE_UPDATE_MUTEX: update_temperature(tempur) # print(" Temperature Data from " + str(recievedPacket.SystemID) + ":" + "Temperature:" + str(round(temperatureData.Temperature,1))) # RSSI if recievedPacket.MessageID == 7: # get the RSSI data RSSI_Data = CustMes.MESSAGE_RSSI() error = RSSI_Data.bytes_to_data(recievedPacket.Payload) if error != 0: print("Radio Network Main: RSSI data error " + str(error)) continue # set the system id for the GPS data RSSI_Data.SystemID = recievedPacket.SystemID # print(RSSI_Data.SystemID) # print(RSSI_Data.TargetPayloadID) # print(GlobalVals.RSSI_ALLOCATION) # Check if the message was sent correctly via the RFD900 if not RSSI_Handler.RSSI_FormatCheck(RSSI_Data): print( "RSSI message via RFD900 was broken. Discard it..." ) continue print("RSSI Data from " + str(recievedPacket.SystemID) + ": " + "RSSI Distance:" + str(round(RSSI_Data.Distance, 1)) + ", Filtered RSSI: " + str(round(RSSI_Data.FilteredRSSI, 1)) + ", TargetPayloadID: " + str(RSSI_Data.TargetPayloadID) + ", Time: " + str(RSSI_Data.Epoch) + ", SysID: " + str(RSSI_Data.SystemID)) if GlobalVals.SYSTEM_ID == 1: with GlobalVals.RSSI_ALLOCATION_MUTEX: # print("UPDATE RSSI ALLOCATION FROM RADIO [",RSSI_Data.SystemID,"] !!!!") # print(GlobalVals.RSSI_ALLOCATION) GlobalVals.RSSI_ALLOCATION[RSSI_Data.SystemID - 1][ int(RSSI_Data.TargetPayloadID) - 1] = True # print("check 32") # print(GlobalVals.RSSI_ALLOCATION) RSSI_Handler.getPairAllocation() # put data into the buffer with GlobalVals.RSSI_DATA_BUFFER_MUTEX: GlobalVals.RSSI_DATA_BUFFER.append(RSSI_Data) # set the flags for the buffer with GlobalVals.RECIEVED_RSSI_RADIO_DATA_MUTEX: GlobalVals.RECIEVED_RSSI_RADIO_DATA = True continue if recievedPacket.MessageID == 8: # get the RSSI data RSSI_AllocationData = CustMes.MESSAGE_RSSI_ALLOCATION() error = RSSI_AllocationData.bytes_to_data( recievedPacket.Payload) if error != 0: print( "Radio Network Main: RSSI Allocation data error " + str(error)) continue # set the system id for the GPS data RSSI_AllocationData.SystemID = recievedPacket.SystemID if not RSSI_Handler.RSSI_AllocationFormatCheck( RSSI_AllocationData): print( "RSSI Allocation message via RFD900 was broken. Discard it..." ) continue print("RSSI Allocation Data from " + str(recievedPacket.SystemID) + ":" + "Pair:" + str(int(RSSI_AllocationData.Pair))) # put data into the buffer with GlobalVals.RSSI_DATA_ALLOCATION_BUFFER_MUTEX: # if len(GlobalVals.RSSI_DATA_ALLOCATION_BUFFER)>5: # GlobalVals.RSSI_DATA_ALLOCATION_BUFFER.pop(0) GlobalVals.RSSI_DATA_ALLOCATION_BUFFER.append( int(RSSI_AllocationData.Pair)) # set the flags for the buffer with GlobalVals.RECIEVED_RSSI_ALLOCATION_RADIO_DATA_MUTEX: GlobalVals.RECIEVED_RSSI_ALLOCATION_RADIO_DATA = True continue with GlobalVals.PACKET_STATS_LOG_MUTEX: packetStatsLogTmp = copy.deepcopy(GlobalVals.PACKET_STATS_LOG) with GlobalVals.PACKET_STATS_AWS_MUTEX: GlobalVals.PACKET_STATS_AWS = packetStatsLogTmp # if radio GPS data has been recived record it if GlobalVals.RECIEVED_GPS_RADIO_DATA: logString = "" with GlobalVals.GPS_DATA_BUFFER_MUTEX: while len(GlobalVals.GPS_DATA_BUFFER) > 0: # get the GPS data GPSData = GlobalVals.GPS_DATA_BUFFER.pop(0) Longitude = GPSData.Longitude Latitude = GPSData.Latitude Altitude = GPSData.Altitude GPSTime = int(GPSData.GPSTime) SystemID = GPSData.SystemID # create message string logString = logString + str(GPSTime) + "," + str( SystemID) + "," + str(Longitude) + "," + str( Latitude) + "," + str(Altitude) + "\n" # write the log string to file try: fileObj = open(GlobalVals.GROUND_STATION_LOG_FILE, "a") fileObj.write(logString) fileObj.close() except Exception as e: print("Exception: " + str(e.__class__)) print(e) print("Error using GPS data log file")
else: lockFile.lock() try: FPSCounter = FPS() FPSCounter.start() cam = cv2.VideoCapture(0) cam.set(3,640) cam.set(4,480) #cam.set(cv2.cv.CV_CAP_PROP_BRIGHTNESS, brightness) #cam.set(cv2.cv.CV_CAP_PROP_SATURATION, saturation) #cam.set(cv2.cv.CV_CAP_PROP_EXPOSURE, exposure) # not working on the old camera visionManager = VisionManager(LB, UB, MBR, cam, KH, KW, FL, [RH,RW,RL], TH, CUW, CUWD, HAX, HAY) networkManager = NetworkManager(JAVA_IP,8080) ################### # The code itself # ################### while True: visionManager.updateImage() visionManager.updateTowerScales() visionManager.updateRobotScales() FPSCounter.update() if visionManager.isObjectDetected: # if an object was detected ######################
pass #addConnection(container, "(ethernet)") def setupModem(container, dev): for connection in dev.AvailableConnections: connId = connection.GetSettings()["connection"]["id"] connected = not dbusNull(dev.ActiveConnection) and dev.ActiveConnection.Id == connId addModemConnection(container, connId, connected, dev, connection) def setupGenericDevice(container, dev): addConnection(container, "(generic)") root = Tk() root.wm_title("xnm") for i, dev in enumerate(NetworkManager.NetworkManager.GetDevices()): deviceHeader = " %s (%s) " % (dev.Interface, NetworkManager.const("device_state", dev.State)) ifLabel = LabelFrame(root, text=deviceHeader, bg=bgColor, fg=midColor, font=headFont) #ifToggle = Checkbutton(ifLabel, bg=bgColor, fg=midColor, font=bodyFont, bd=0, highlightthickness=0, compound=RIGHT, activebackground=fgColor, activeforeground=bgColor) #ifToggle.pack(fill="both") #if (NetworkManager.const("device_state", dev.State) == "disconnected"): # ifToggle.config(text="Enable", command=lambda: enableDevice(dev)) #else: # ifToggle.config(text="Disable", command=lambda: disableDevice(dev)) #ifDisconnect = Button(ifLabel, text="Disconnect", bg=bgColor, fg=midColor, font=bodyFont, bd=0, highlightthickness=0, compound=RIGHT, activebackground=fgColor, activeforeground=bgColor) #ifDisconnect.pack(fill="both") if (isinstance(dev.SpecificDevice(), NetworkManager.Wireless)): setupWifi(ifLabel, dev) elif (isinstance(dev.SpecificDevice(), NetworkManager.Wired)):