예제 #1
0
    def init_on_track(self, root, config, dataset_yaml):
        print("[1/3] Loading tracks in %s." % os.path.basename(config["tracks_csv"]))
        tracks = np.genfromtxt(self.config["tracks_csv"])

        # check that all features start at the same timestamp, if not, discard features that occur later
        first_len_tracks = len(tracks)
        valid_ids, tracks = filter_first_tracks(tracks, filter_too_short=True)

        if len(tracks) < first_len_tracks:
            print("WARNING: This package only supports evaluation of tracks which have been initialized at the same"
                  " time. All tracks except the first have been discarded.")

        tracks_dict = {i: tracks[tracks[:, 0] == i, 1:] for i in valid_ids}

        print("[2/3] Loading frame dataset to find positions of initial tracks.")
        frame_dataset = Dataset(root, dataset_yaml, dataset_type="frames")

        # find dataset indices for each start
        tracks_init = {}
        print("[3/3] Initializing tracks")
        for track_id, track in tracks_dict.items():
            frame_dataset.set_to_first_after(track[0,0])
            t_dataset, _ = frame_dataset.current()

            x_interp = np.interp(t_dataset, track[:, 0], track[:, 1])
            y_interp = np.interp(t_dataset, track[:, 0], track[:, 2])

            tracks_init[track_id] = np.array([[t_dataset, x_interp, y_interp]])

        tracks_obj = Tracks(tracks_init)

        return tracks_obj, {"frame_dataset": frame_dataset, "reference_track": tracks}
예제 #2
0
    def init_by_reprojection(self, root, config, dataset_yaml):
        """
        inits tracks by extracting corners on image and then backprojecting them for a given pose.
        """
        print("[1/3] Loading tracks in %s" %
              os.path.basename(config["tracks_csv"]))
        tracks = np.genfromtxt(config["tracks_csv"])
        first_len_tracks = len(tracks)
        valid_ids, tracks = filter_first_tracks(tracks, filter_too_short=True)

        if len(tracks) < first_len_tracks:
            print(
                "WARNING: This package only supports evaluation of tracks which have been initialized at the same"
                " time. All tracks except the first have been discarded.")

        tracks_dict = {i: tracks[tracks[:, 0] == i, 1:] for i in valid_ids}
        features = np.stack([tracks_dict[i][0]
                             for i in valid_ids]).reshape(-1, 1, 3)

        print("[2/3] Loading depths, poses, frames and camera info")
        depth_dataset = Dataset(root, dataset_yaml, dataset_type="depth")
        pose_dataset = Dataset(root, dataset_yaml, dataset_type="poses")
        camera_info_dataset = Dataset(root,
                                      dataset_yaml,
                                      dataset_type="camera_info")

        K = camera_info_dataset.K
        img_size = camera_info_dataset.img_size

        # find poses and depths at features
        print("[3/3] Backprojecting first feature positions")
        depth_maps_interp = depth_dataset.get_interpolated(features[:, 0, 0])
        depths = grid_sample(features[:, 0, 1:], depth_maps_interp)

        poses = pose_dataset.get_interpolated(features[:, 0, 0])
        landmarks = backProjectFeatures(K, features[:, :, 1:], depths, poses)

        t_min = np.min(features[:, 0, 0])
        pose_dataset.set_to_first_after(t_min)

        # parse
        landmarks_dict = {i: landmarks[j] for j, i in enumerate(valid_ids)}
        features_dict = {i: features[j] for j, i in enumerate(valid_ids)}

        # create dict of features
        tracks_obj = Tracks(features_dict)

        # params for tracker
        tracker_params = {
            "landmarks": landmarks_dict,
            "pose_dataset": pose_dataset,
            "img_size": img_size,
            "K": K,
            "reference_track": tracks
        }

        return tracks_obj, tracker_params
예제 #3
0
파일: test.py 프로젝트: mark-ankit/kismon
def networks():
	try:
		from .config import Config
		from .networks import Networks
		from .tracks import Tracks
	except SystemError:
		from config import Config
		from networks import Networks
		from tracks import Tracks

	def dummy(bla):
		return
	test_data = get_client_test_data()[2]
	test_config = Config(None).default_config

	networks = Networks(test_config)
	networks.notify_add_list["map"] = dummy
	networks.notify_add_list["network_list"] = dummy
	networks.notify_remove_list["map"] = dummy
	networks.notify_remove_list["network_list"] = dummy
	for x in range(2):
		for data in test_data:
			if data is not None and data[0] == "bssid":
				networks.add_bssid_data(data[1], 0)
				data[1]["lasttime"] = data[1]["lasttime"] + 1
		for data in test_data:
			if data is not None and data[0] == "ssid":
				networks.add_ssid_data(data[1])
				data[1]["lasttime"] = data[1]["lasttime"] + 1
	
	tmp_csv_file = "%s%stest-%s.csv" % (tempfile.gettempdir(), os.sep, int(time.time()))
	tmp_csv = open(tmp_csv_file, "w")
	tmp_csv.write("""Network;NetType;ESSID;BSSID;Info;Channel;Cloaked;Encryption;Decrypted;MaxRate;MaxSeenRate;Beacon;LLC;Data;Crypt;Weak;Total;Carrier;Encoding;FirstTime;LastTime;BestQuality;BestSignal;BestNoise;GPSMinLat;GPSMinLon;GPSMinAlt;GPSMinSpd;GPSMaxLat;GPSMaxLon;GPSMaxAlt;GPSMaxSpd;GPSBestLat;GPSBestLon;GPSBestAlt;DataSize;IPType;IP;
1;infrastructure;asd;11:22:33:44:55:66;;3;No;WEP,WPA,PSK,AES-CCM;No;18.0;1000;25600;148;0;0;0;148;IEEE 802.11g;;Thu Jan 22 05:48:23 2009;Thu Jan 22 05:51:46 2009;0;65;-98;52.123456;13.123456;120.120003;0.000000;52.123456;13.123456;120.120003;2.934490;0.000000;0.000000;0.000000;0;None;0.0.0.0;""")
	tmp_csv.close()
	for x in range(2):
		networks.import_networks("csv", tmp_csv_file)
	networks.import_networks("netxml", "")

	tmp_tracks_file = "%s%stest-tracks-%s.json" % (tempfile.gettempdir(), os.sep, int(time.time()))
	test_tracks = Tracks(tmp_tracks_file)

	networks_file = "%s%snetworks-%s.json" % (tempfile.gettempdir(), os.sep, int(time.time()))
	networks.save(networks_file)
	networks.load(networks_file)
	networks.import_networks("networks",networks_file)
	networks.apply_filters()
	networks.save(networks_file)
	networks.export_networks_netxml(tempfile.gettempdir() + os.sep + "test.netxml", networks.networks)
	networks.import_networks("netxml", tempfile.gettempdir() + os.sep + "test.netxml")
	networks.export_networks_kmz(tempfile.gettempdir() + os.sep + "test.kmz", networks.networks, tracks=test_tracks, filtered=False)
	networks.export_networks_kmz(tempfile.gettempdir() + os.sep + "test.kmz", networks.networks, tracks=test_tracks, filtered=True)

	return networks
예제 #4
0
def track_page():
    tras = Tracks(app.config['dsn'])
    if request.method == 'GET':
        now = datetime.datetime.now()
        tlist = tras.get_tracklist()
        return render_template('tracks.html', TrackList = tlist, current_time = now.ctime())
    elif 'tracks_to_delete' in request.form:
        ids = request.form.getlist('tracks_to_delete') 
        for id in ids:
            tras.delete_track(id)
        return redirect(url_for('track_page'))
    elif 'tracks_to_add' in request.form:
        tras.add_track(request.form['title'])
        return redirect(url_for('track_page'))
    elif 'tracks_to_update' in request.form:
        tras.update_track(request.form['id'], request.form['title'])
        return redirect(url_for('track_page'))
예제 #5
0
    def init_on_track(self, root, config, dataset_yaml):
        print("[1/3] Loading tracks in %s." %
              os.path.basename(config["tracks_csv"]))
        tracks = np.genfromtxt(self.config["tracks_csv"])

        # check that all features start at the same timestamp, if not, discard features that occur later
        first_len_tracks = len(
            tracks)  #~ total number of features. (line number).
        valid_ids, tracks = filter_first_tracks(tracks, filter_too_short=True)

        if len(tracks
               ) < first_len_tracks:  # 意味着筛掉了一些id,所以提示:非初始时刻的feature,都没有保留。
            print(
                "WARNING: This package only supports evaluation of tracks which have been initialized at the same"
                " time. All tracks except the first have been discarded.")

        tracks_dict = {i: tracks[tracks[:, 0] == i, 1:]
                       for i in valid_ids
                       }  # 提取出每个 id 的所有track结果,保存在一个dict中。一共有 n 个dict,n即总的id数。

        print(
            "[2/3] Loading frame dataset to find positions of initial tracks.")
        frame_dataset = Dataset(root, dataset_yaml, dataset_type="frames")

        # find dataset indices for each start
        tracks_init = {}
        print("[3/3] Initializing tracks")
        for track_id, track in tracks_dict.items():
            frame_dataset.set_to_first_after(
                track[0, 0])  # 找到 第一个feature之后的第一个frame图
            t_dataset, _ = frame_dataset.current()

            x_interp = np.interp(t_dataset, track[:, 0],
                                 track[:,
                                       1])  # 根据frame图的时间戳,和前后两次跟踪的结果,插值等到位置。
            y_interp = np.interp(t_dataset, track[:, 0], track[:, 2])

            tracks_init[track_id] = np.array([[t_dataset, x_interp, y_interp]])

        tracks_obj = Tracks(tracks_init)  # 打包成 Tracks类型

        return tracks_obj, {
            "frame_dataset": frame_dataset,
            "reference_track": tracks
        }
예제 #6
0
    def init_by_reprojection(self, root, config, dataset_yaml):
        """
        inits tracks by extracting corners on image and then backprojecting them for a given pose.
        """
        print("[1/3] Loading tracks in %s" % os.path.basename(config["tracks_csv"]))
        tracks = np.genfromtxt(config["tracks_csv"])
        ids = np.unique(tracks[:, 0]).astype(int)
        tracks_dict = {i: tracks[tracks[:, 0] == i, 1:] for i in ids}
        features = np.stack([tracks_dict[i][0] for i in ids]).reshape(-1, 1, 3)

        print("[2/3] Loading depths, poses, frames and camera info")
        depth_dataset = Dataset(root, dataset_yaml, dataset_type="depth")
        pose_dataset = Dataset(root, dataset_yaml, dataset_type="poses")
        camera_info_dataset = Dataset(root, dataset_yaml, dataset_type="camera_info")

        K = camera_info_dataset.K
        img_size = camera_info_dataset.img_size

        # find poses and depths at features
        print("[3/3] Backprojecting first feature positions")
        depth_maps_interp = depth_dataset.get_interpolated(features[:, 0, 0])
        depths = grid_sample(features[:,0,1:], depth_maps_interp)

        poses = pose_dataset.get_interpolated(features[:, 0, 0])
        landmarks = backProjectFeatures(K, features[:, :, 1:], depths, poses)

        t_min = np.min(features[:, 0, 0])
        pose_dataset.set_to_first_after(t_min)

        # parse
        landmarks_dict = {i: landmarks[j] for j,i in enumerate(ids)}
        features_dict = {i: features[j] for j,i in enumerate(ids)}

        # create dict of features
        tracks_obj = Tracks(features_dict)

        # params for tracker
        tracker_params = {"landmarks": landmarks_dict,
                          "pose_dataset": pose_dataset, "img_size": img_size, "K": K, "reference_track": tracks}

        return tracks_obj, tracker_params
예제 #7
0
    def init_on_track(self, root, config, dataset_yaml):
        print("[1/3] Loading tracks in %s." % os.path.basename(config["tracks_csv"]))
        tracks = np.genfromtxt(self.config["tracks_csv"])
        ids = np.unique(tracks[:, 0]).astype(int)
        tracks_dict = {i: tracks[tracks[:, 0] == i, 1:] for i in ids}

        print("[2/3] Loading frame dataset to find positions of initial tracks.")
        frame_dataset = Dataset(root, dataset_yaml, dataset_type="frames")

        # find dataset indices for each start
        tracks_init = {}
        print("[3/3] Initializing tracks")
        for track_id, track in tracks_dict.items():
            frame_dataset.set_to_first_after(track[0,0])
            t_dataset, _ = frame_dataset.current()

            x_interp = np.interp(t_dataset, track[:, 0], track[:, 1])
            y_interp = np.interp(t_dataset, track[:, 0], track[:, 2])

            tracks_init[track_id] = np.array([[t_dataset, x_interp, y_interp]])

        tracks_obj = Tracks(tracks_init)

        return tracks_obj, {"frame_dataset": frame_dataset, "reference_track": tracks}
예제 #8
0
파일: core.py 프로젝트: mark-ankit/kismon
    def __init__(self):
        user_dir = "%s%s.kismon%s" % (os.path.expanduser("~"), os.sep, os.sep)
        if not os.path.isdir(user_dir):
            print("Creating Kismon user directory %s" % user_dir)
            os.mkdir(user_dir)
        config_file = "%skismon.conf" % user_dir
        self.config_handler = Config(config_file)
        self.config_handler.read()
        self.config = self.config_handler.config

        self.sources = {}
        self.crypt_cache = {}
        self.networks = Networks(self.config)
        self.client_threads = {}
        self.init_client_threads()
        self.tracks = Tracks("%stracks.json" % user_dir)
        self.tracks.load()

        if "--disable-map" in sys.argv:
            self.map_error = "--disable-map used"
        else:
            self.map_error = check_osmgpsmap()

        if self.map_error is not None:
            self.map_error = "%s\nMap disabled" % self.map_error
            print(self.map_error, "\n")

        self.init_map()

        self.main_window = MainWindow(self.config, self.client_start,
                                      self.client_stop, self.map,
                                      self.networks, self.sources, self.tracks,
                                      self.client_threads)
        self.main_window.log_list.add("Kismon", "started")
        if self.map_error is not None:
            self.main_window.log_list.add("Kismon", self.map_error)

        self.networks_file = "%snetworks.json" % user_dir
        if os.path.isfile(self.networks_file):
            try:
                self.networks.load(self.networks_file)
            except:
                error = sys.exc_info()[1]
                print(error)
                dialog_message = "Could not read the networks file '%s':\n%s\n\nDo you want to continue?" % (
                    self.networks_file, error)
                dialog = Gtk.MessageDialog(self.main_window.gtkwin,
                                           Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                           Gtk.MessageType.ERROR,
                                           Gtk.ButtonsType.YES_NO,
                                           dialog_message)

                def dialog_response(dialog, response_id):
                    self.dialog_response = response_id

                dialog.connect("response", dialog_response)
                dialog.run()
                dialog.destroy()
                if self.dialog_response == -9:
                    print("exit")
                    self.clients_stop()
                    self.main_window.gtkwin = None
                    return
        self.networks.set_autosave(self.config["networks"]["autosave"],
                                   self.networks_file,
                                   self.main_window.log_list.add)

        if self.map is not None:
            self.networks.notify_add_list["map"] = self.add_network_to_map
            self.networks.notify_remove_list["map"] = self.map.remove_marker
            GLib.timeout_add(100, self.map.set_last_from_config)

        self.main_window.network_list.crypt_cache = self.crypt_cache

        GLib.timeout_add(500, self.queues_handler)
        GLib.timeout_add(300, self.queues_handler_networks)
        GLib.idle_add(self.networks.apply_filters)
예제 #9
0
파일: core.py 프로젝트: mark-ankit/kismon
class Core:
    def __init__(self):
        user_dir = "%s%s.kismon%s" % (os.path.expanduser("~"), os.sep, os.sep)
        if not os.path.isdir(user_dir):
            print("Creating Kismon user directory %s" % user_dir)
            os.mkdir(user_dir)
        config_file = "%skismon.conf" % user_dir
        self.config_handler = Config(config_file)
        self.config_handler.read()
        self.config = self.config_handler.config

        self.sources = {}
        self.crypt_cache = {}
        self.networks = Networks(self.config)
        self.client_threads = {}
        self.init_client_threads()
        self.tracks = Tracks("%stracks.json" % user_dir)
        self.tracks.load()

        if "--disable-map" in sys.argv:
            self.map_error = "--disable-map used"
        else:
            self.map_error = check_osmgpsmap()

        if self.map_error is not None:
            self.map_error = "%s\nMap disabled" % self.map_error
            print(self.map_error, "\n")

        self.init_map()

        self.main_window = MainWindow(self.config, self.client_start,
                                      self.client_stop, self.map,
                                      self.networks, self.sources, self.tracks,
                                      self.client_threads)
        self.main_window.log_list.add("Kismon", "started")
        if self.map_error is not None:
            self.main_window.log_list.add("Kismon", self.map_error)

        self.networks_file = "%snetworks.json" % user_dir
        if os.path.isfile(self.networks_file):
            try:
                self.networks.load(self.networks_file)
            except:
                error = sys.exc_info()[1]
                print(error)
                dialog_message = "Could not read the networks file '%s':\n%s\n\nDo you want to continue?" % (
                    self.networks_file, error)
                dialog = Gtk.MessageDialog(self.main_window.gtkwin,
                                           Gtk.DialogFlags.DESTROY_WITH_PARENT,
                                           Gtk.MessageType.ERROR,
                                           Gtk.ButtonsType.YES_NO,
                                           dialog_message)

                def dialog_response(dialog, response_id):
                    self.dialog_response = response_id

                dialog.connect("response", dialog_response)
                dialog.run()
                dialog.destroy()
                if self.dialog_response == -9:
                    print("exit")
                    self.clients_stop()
                    self.main_window.gtkwin = None
                    return
        self.networks.set_autosave(self.config["networks"]["autosave"],
                                   self.networks_file,
                                   self.main_window.log_list.add)

        if self.map is not None:
            self.networks.notify_add_list["map"] = self.add_network_to_map
            self.networks.notify_remove_list["map"] = self.map.remove_marker
            GLib.timeout_add(100, self.map.set_last_from_config)

        self.main_window.network_list.crypt_cache = self.crypt_cache

        GLib.timeout_add(500, self.queues_handler)
        GLib.timeout_add(300, self.queues_handler_networks)
        GLib.idle_add(self.networks.apply_filters)

    def init_map(self):
        if self.map_error is not None:
            self.map = None
        else:
            try:
                from .map import Map
            except SystemError:
                from map import Map
            user_agent = 'kismon/%s' % utils.get_version()
            self.map = Map(self.config["map"], user_agent=user_agent)
            self.map.set_last_from_config()

    def init_client_thread(self, server_id):
        server = self.config["kismet"]["servers"][server_id]
        self.client_threads[server_id] = ClientThread(server)
        self.client_threads[server_id].client.set_capabilities(
            ('status', 'source', 'info', 'gps', 'bssid', 'bssidsrc', 'ssid'))
        if "--create-kismet-dump" in sys.argv:
            self.client_threads[server_id].client.enable_dump()

    def init_client_threads(self):
        server_id = 0
        for server in self.config["kismet"]["servers"]:
            self.init_client_thread(server_id)
            server_id += 1

    def client_start(self, server_id):
        if server_id in self.client_threads and self.client_threads[
                server_id].is_running:
            self.client_stop(server_id)
        self.sources[server_id] = {}
        self.init_client_thread(server_id)
        if "--load-kismet-dump" in sys.argv:
            self.client_threads[server_id].client.load_dump(sys.argv[2])
        self.client_threads[server_id].start()

    def client_stop(self, server_id):
        if self.client_threads[server_id].client.connecting:
            # kill connecting sockets, don't wait for the timeout
            try:
                self.client_threads[server_id].client.s.shutdown(
                    socket.SHUT_RDWR)
            except OSError:
                pass
        self.client_threads[server_id].stop()

    def clients_stop(self):
        for server_id in self.client_threads:
            self.client_stop(server_id)
        return True

    def queue_handler(self, server_id):
        server_name = self.config['kismet']['servers'][server_id]
        if self.main_window.gtkwin is None:
            return False

        thread = self.client_threads[server_id]
        if len(thread.client.error) > 0:
            for error in thread.client.error:
                self.main_window.log_list.add(server_name, error)
            thread.client.error = []
            self.main_window.server_tabs[server_id].server_switch.set_active(
                False)
            page_num = self.main_window.notebook.page_num(
                self.main_window.log_list.widget)
            self.main_window.notebook.set_current_page(page_num)

        #gps
        gps = None
        fix = None
        gps_queue = thread.get_queue("gps")
        while True:
            try:
                data = gps_queue.pop()
                if gps is None:
                    gps = data
                if data["fix"] > 1:
                    fix = (data["lat"], data["lon"])
                    if self.config['tracks']['store'] == True:
                        self.tracks.add_point_to_track(server_name,
                                                       data['lat'],
                                                       data['lon'],
                                                       data['alt'])
                    break
            except IndexError:
                break
        if gps is not None:
            self.main_window.server_tabs[server_id].update_gps_table(gps)
            if fix is not None and self.map is not None:
                server = "server%s" % (server_id + 1)
                if server_id == 0:
                    self.map.set_position(fix[0], fix[1])
                else:
                    self.map.add_marker(server, server, fix[0], fix[1])
                self.map.add_track(fix[0], fix[1], server_id)

        #status
        for data in thread.get_queue("status"):
            self.main_window.log_list.add(server_name, data["text"])

        #info
        info_queue = thread.get_queue("info")
        try:
            data = info_queue.pop()
            self.main_window.server_tabs[server_id].update_info_table(data)
        except IndexError:
            pass

        #source
        update = False
        for data in thread.get_queue("source"):
            uuid = data["uuid"]
            if uuid == "00000000-0000-0000-0000-000000000000":
                continue
            self.sources[server_id][uuid] = data

            update = True
        if update is True:
            self.main_window.server_tabs[server_id].update_sources_table(
                self.sources[server_id])

    def queues_handler(self):
        for server_id in self.client_threads:
            self.queue_handler(server_id)
        return True

    def queue_handler_networks(self, server_id):
        thread = self.client_threads[server_id]

        #ssid
        for data in thread.get_queue("ssid"):
            self.networks.add_ssid_data(data)

        #bssid
        bssids = {}
        for data in thread.get_queue("bssid"):
            mac = data["bssid"]
            self.networks.add_bssid_data(data, server_id)
            if mac in self.main_window.signal_graphs and "signal_dbm" not in thread.client.capabilities[
                    "bssidsrc"]:
                self.main_window.signal_graphs[mac].add_value(
                    None, None, data["signal_dbm"], server_id)

            bssids[mac] = True

        #bssidsrc
        for data in thread.get_queue("bssidsrc"):
            if "signal_dbm" not in data or data["uuid"] not in self.sources[
                    server_id]:
                continue

            mac = data["bssid"]
            if mac in self.main_window.signal_graphs:
                self.main_window.signal_graphs[mac].add_value(
                    self.sources[server_id][data["uuid"]], data,
                    data["signal_dbm"], server_id)

        if len(self.networks.notify_add_queue) > 0:
            self.networks.start_queue()
            if len(self.networks.notify_add_queue) > 500:
                self.networks.disable_refresh()
                self.main_window.networks_queue_progress()

        self.main_window.update_statusbar()

    def queues_handler_networks(self):
        for server_id in self.client_threads:
            self.queue_handler_networks(server_id)
        return True

    def quit(self):
        self.clients_stop()

        if self.map is not None:
            lat = self.map.osm.get_property("latitude")
            lon = self.map.osm.get_property("longitude")
            self.config["map"]["last_position"] = "%.6f/%.6f" % (lat, lon)

        while None in self.config['kismet']['servers']:
            self.config['kismet']['servers'].remove(None)
        self.config_handler.write()
        self.networks.save(self.networks_file, force=True)
        if self.config['tracks']['store'] == True:
            self.tracks.save()

    def add_network_to_map(self, mac):
        network = self.networks.get_network(mac)

        try:
            crypt = self.crypt_cache[network["cryptset"]]
        except KeyError:
            crypt = decode_cryptset(network["cryptset"], True)
            self.crypt_cache[network["cryptset"]] = crypt

        if "AES_CCM" in crypt or "AES_OCB" in crypt:
            color = "red"
        elif "WPA" in crypt:
            color = "orange"
        elif "WEP" in crypt:
            color = "yellow"
        else:
            color = "green"

        self.map.add_marker(mac, color, network["lat"], network["lon"])
예제 #10
0
# Imports for Flask
from flask import Flask, render_template, flash, redirect, request, jsonify
from werkzeug.utils import secure_filename

# Import of own classes
from tracks import Tracks
from playlist import Playlist
from hardware import Hardware
from lighting import Lighting, Section
try:
    from led import Leds
except:
    from led_nohw import Leds

# Initializations
tracks = Tracks("tracks")
playlist = Playlist()
hardware = Hardware(tracks, playlist)
ledHw = Leds(64)
ledConfig = Lighting(ledHw)

event_start = threading.Event()
event_stop = threading.Event()
event_shutdown = threading.Event()

# Creating the web server
app = Flask(__name__, template_folder=".", static_folder="assets")
app.config.from_object('config.Config')
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
예제 #11
0
    def __init__(self):
        # Ett test av rich:s felhantering konsollmanipulering
        install()
        # En inställning för att justera inställningar rätt
        # Hämtar de tillgängliga inställningarna.
        self.settings = Settings(in_car=True)
        # Hämtar all tillgänglig ban-info.
        self.tracks = Tracks(self)
        # Console
        console = Console()
        # Flag för testning av programmet.
        self.counting = False
        self.update_counter = 0
        self.gps_active = False
        # Kommandon som bilen ska läsa.

        self.command_list = {
            'rpm': 'RPM',
            'kmh': 'SPEED',
            'throttle': 'THROTTLE_POS',
            'water': 'COOLANT_TEMP',
            'oiltemp': 'OIL_TEMP',
            'load': 'ENGINE_LOAD',
            'fuel': 'FUEL_LEVEL'
        }

        self.measurements_dict = {}

        # Allmän info om mätarna. Ifall det ska multipliceras med något, lägg in det
        # i gauges - klassen. Typ if unit == '%': value *= 100.
        self.gauges_info = {
            'rpm': {
                'unit': None,
                'upper_limit': 8000
            },
            'kmh': {
                'unit': None,
                'upper_limit': None
            },
            'throttle': {
                'unit': '%',
                'upper_limit': None
            },
            'water': {
                'unit': '°',
                'upper_limit': 110
            },
            'oiltemp': {
                'unit': '°',
                'upper_limit': 180
            },
            'load': {
                'unit': 'hp',
                'upper_limit': None
            },
            'fuel': {
                'unit': '%',
                'upper_limit': None
            }
        }
        #try: Detta måste fungera, annars ska det krascha.
        self.obd_instance = OBDII(self.settings.OBD_port)
        self.settings.obd_active = True
        # Använder Tkiner för att ställa in
        # skärmen och startförhållanden.
        self._init_screen()
        try:
            requests.put(self.settings.base_url + "location/gps", {
                "lat": 0,
                "lon": 0
            })
            requests.put(
                self.settings.base_url + "location/gps", {
                    'rpm': 0,
                    'kmh': 0,
                    'throttle': 0,
                    'water': 0,
                    'oiltemp': 0,
                    'load': 0
                })
        except:
            console.print("[bold red]Ingen anslutning.")
        else:
            console.print("[bold green]Ansluten!")
예제 #12
0
파일: k9d.py 프로젝트: aaaler/k9
class K9dApp:
    #Compile RE for iwconfig ouput parsing
    brre = re.compile (r"Bit Rate=([\d.]+ \S+)",re.M)
    lqre = re.compile (r"Link Quality=(\d+/\d+)  Signal level=(-\d+ dBm)",re.M)

    def __init__ (self):
        #Kind a config here
        #arduino tracks bridge pinout
        self.tracks = Tracks (pin.port.PB5, pin.port.PB6, 28, pin.port.PB7, pin.port.PB10, 29, 20)
        #ip
        self.addr = "192.168.0.22"
        self.UDP_IP = "0.0.0.0"
        self.UDP_PORT = 9999
        #sonar
        self.sonaron = True
        self.sonarfailsafe = 0.
        #mjpg_streamer related
        self.videomode = 'OFF'
       
        #init
        self.faststate = {}
        self.faststate["proxalert"] = False
        self.sonardist = 0
        self.sonarfailsafe_active = False
        self.festivalup = False
        self.log_init()
        #==============UDP INIT====================
        self.log.info ("spinal interface daemon for K-9 starting");
        self.servsock = socket.socket(socket.AF_INET, # Internet
                              socket.SOCK_DGRAM) # UDP
        self.servsock.bind((self.UDP_IP, self.UDP_PORT))
        self.respsock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
        #============SERIAL INIT===================
        try:
          self.spinal = serial.Serial('/dev/ttyS2', 115200, timeout=0.5)
          self.spinal_enabled = True
        except:
          self.spinal_enabled = False
          self.log.info("Could not open port for arduino -- connection disabled ")                
        
        try:
          self.sonar = serial.Serial('/dev/ttyS1', 9600, timeout=0.5)
          self.sonar_enabled = True
        except:
          self.log.error("Could not open port for sonar -- sonar disabled")
          self.sonar_enabled = False
        
        #===========THREADING INIT=================
        
        self.faststate['S1']=-1
        self.faststate['S2']=-1
        self.faststate['A1']=-1
        self.faststate['A2']=-1
        self.faststate['A3']=-1

        if self.spinal_enabled:
            self.tSerialRead = threading.Thread(target=self.sreader)
            self.tSerialRead.setDaemon (1)
            self.tSerialRead.start()
        
        self.tTrackWatchdog = threading.Thread(target=self.cmdtimeout)
        self.tTrackWatchdog.setDaemon (1)
        self.tTrackWatchdog.start()
        
        self.tStateUpload = threading.Thread(target=self.tstateup)
        self.tStateUpload.setDaemon (1)
        self.tStateUpload.start()
    
        if self.sonar_enabled:        
            self.tSonar = threading.Thread(target=self.tsonar)
            self.tSonar.setDaemon (1)
            self.tSonar.start()

        
        self.log.info ("ready to play");

    def __del__ (self):
        self.log.info("Shutting down daemon")
        self.gsens.__del__()
        self.gsens = None

    def gsens_update (self):
        if hasattr(self.gsens,'yaw'):
            self.faststate['yaw'] = self.gsens.yaw
            self.faststate['pitch'] = self.gsens.pitch
            self.faststate['roll'] = self.gsens.roll
            self.faststate['ax'] = self.gsens.ax
            self.faststate['ay'] = self.gsens.ay
            self.faststate['az'] = self.gsens.az
            self.stateupload()

    def log_init(self):
         
        if hasattr(self, 'log'):
            self.log.removeHandler(self.stdoutloghandler)
            self.log.removeHandler(self.udploghandler)
    	else:
            self.log = logging.getLogger('k9d')

        self.stdoutloghandler = logging.StreamHandler(sys.stdout)
        self.stdoutloghandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s#%(levelname)s]: %(message)s"))
        self.stdoutloghandler.setLevel(logging.DEBUG)
        self.udploghandler = logging.handlers.DatagramHandler(self.addr, self.UDP_PORT)
        self.udploghandler.setFormatter(logging.Formatter("%(asctime)s [%(name)s#%(levelname)s]: %(message)s"))
        self.udploghandler.setLevel(logging.DEBUG)

        self.log.setLevel(logging.DEBUG)
        self.log.addHandler(self.stdoutloghandler)
        self.log.addHandler(self.udploghandler)
 

    def mainloop (self):          
        while True:
            data,(addr,self.port) = self.servsock.recvfrom(1024) # buffer size is 1024 bytes   
            if addr != self.addr:
              self.log.warn ("New client ip: {}".format(addr))
              self.addr = addr
              self.log_init()
            out = "{}>{} &".format(str(self.addr),data)
  
            request = data.split(' ');
            CMD = request.pop(0) 
            CMD = CMD.strip("\n")
            if CMD == "STOP":
              self.tracks.neutral()
              self.faststate['trackr'] = self.tracks.trackr
              self.faststate['trackl'] = self.tracks.trackl
              self.stateupload()
              self.log.debug ("Tracks vector set to neutral")
            elif CMD == "SPINAL":
              emsg = ' '.join(request)
              self.log.info ("Sending user packet to spinal: {}".format(emsg))
              self.spinal_write (emsg)
            elif CMD == "PING":
              self.log.info ("PING {} got".format(request[0]))
              self.send ("PONG {} {}".format(time.time(),request[0]),self.addr)
            elif CMD == "TRACKS":
              self.tracks.vector (request[0],request[1]);
              self.log.debug ("Tracks vector set to {},{}".format(request[0],request[1]))
              self.faststate['trackr'] = self.tracks.trackr
              self.faststate['trackl'] = self.tracks.trackl
              self.stateupload()
            elif CMD == "SERVO":
              self.servo (request[0],request[1]);
            elif CMD == "SON":
              if request[0] == 'Failsafe':
                self.sonaron = True
                if request[1] == 'off': self.sonarfailsafe = 0
                else: self.sonarfailsafe = float(request[1])
              elif request[0] == 'Sonar' and request[1] == 'off' :
                self.sonaron = False
                self.sonarfailsafe = 0
            elif CMD == "CAM":
              if request[0] == 'RES':
                if hasattr(self, 'pmjpg'):
                  if self.pmjpg.poll() == None:
                    pid = self.pmjpg.pid
                    self.pmjpg.kill()
                    self.videomode = "OFF"
                    t = threading.Timer(2.0,self.run_mjpg,[request[1]])
                    t.start() 
                    self.log.info ("Killed mjpg with pid {} and deferred run with {}".format(pid,request[1]))
                  else: 
                    self.run_mjpg(request[1])
                else: 
                  self.run_mjpg(request[1])
              elif request[0] == 'OFF':
                if hasattr(self, 'pmjpg') and self.pmjpg.poll() == None:
                    self.pmjpg.kill()
                self.videomode = "OFF" 
                self.log.info ("Killed mjpg.")                
              elif request[0] == 'ZOOM' and request[1] == 'OFF' :
                status = subprocess.call(["/usr/bin/v4l2-ctl", "--set-ctrl=zoom_absolute=1"])  
                self.log.info ("Zoom OFF")
              elif request[0] == 'ZOOM' and request[1] == 'ON' :
                status = subprocess.call(["/usr/bin/v4l2-ctl", "--set-ctrl=zoom_absolute=5"])
                self.log.info ("Zoom ON")
            elif CMD == "FESTIVAL":
                if request[0] == 'ON':
                    if hasattr(self, 'pfestival'):
                        if self.pfestival.poll() == None:
                            pid = self.pfestival.pid
                            self.pfestival.kill()
                            self.festivalup = False
                            t = threading.Timer(2.0,self.run_festival)
                            t.start() 
                            self.log.info ("Killed festival with pid {} and deferred run".format(pid))
                        else: 
                            self.run_festival()
                    else: 
                        self.run_festival()
                elif request[0] == 'OFF':
                    if hasattr(self, 'pfestival') and self.pfestival.poll() == None:
                        self.pfestival.kill()
                    self.festivalup = False
                    self.log.info ("Killed festival")
            elif CMD == "SAY":
                tts = cPickle.loads(data[4:])
                if self.festivalup:
                    self.pfestival.stdin.write ("(SayText \"{}\")".format( tts.encode("utf-8")))
                    self.pfestival.stdin.flush()
                    self.log.info ("Pronouncing '{}'".format(tts.encode("utf-8")))
                else:
                    self.log.err ("Can't SAY, festival down")
            elif CMD == 'EVAL':
                ecmd = " ".join(request)
                try:
                    output = eval("pprint.pformat({})".format(ecmd))
                    self.log.info ("{} = {}".format(ecmd, output))
                except Exception, e:
                    self.log.error("eval \"{}\" raised {} Exception: {}".format(ecmd,type(e).__name__ ,e))

            elif CMD == "GSENSOR":
                if request[0] == 'ON':
                    self.gsens = GSens (0, self.gsens_update, self.log.error, self.log.info, self.log.debug)
                elif request[0] == 'OFF':
                    self.gsens.__del__()
                    self.gsens = None

            else: 
예제 #13
0
파일: test.py 프로젝트: mark-ankit/kismon
	def test_gui_main_window(self):
		from gi.repository import Gtk
		try:
			from .config import Config
			from .map import Map
			from .gui import MainWindow
			from .client import ClientThread
			from .tracks import Tracks
		except SystemError:
			from config import Config
			from map import Map
			from gui import MainWindow
			from client import ClientThread
			from tracks import Tracks
		def dummy(server_id):
			return

		test_widget = TestWidget()

		test_config = Config(None).default_config
		test_map = Map(test_config["map"])
		test_networks =  networks()
		test_client_threads = {0: ClientThread()}
		tmp_tracks_file = "%s%stest-tracks-%s.json" % (tempfile.gettempdir(), os.sep, int(time.time()))
		test_tracks = Tracks(tmp_tracks_file)
		main_window = MainWindow(test_config, dummy, dummy, test_map, test_networks, test_tracks, {0: None, 1: None}, test_client_threads)
		main_window.network_list.crypt_cache = {}

		main_window.log_list.add("Kismon", "test")
		main_window.network_list.add_network('11:22:33:44:55:66')
		main_window.network_list.network_selected = '11:22:33:44:55:66'
		main_window.network_list.add_network('00:12:2A:03:B9:12')
		main_window.network_list.add_network('00:12:2A:03:B9:12')
		main_window.network_list.column_selected = 2
		main_window.network_list.on_copy_field(None)
		main_window.network_list.on_copy_network(None)
		main_window.network_list.on_comment_editing_done(test_widget)
		main_window.network_list.remove_network('00:12:2A:03:B9:12')
		main_window.server_tabs[0].update_info_table({"networks":100, "packets":200} )
		main_window.server_tabs[0].update_gps_table({"fix": 3, "lat": 52.0, "lon": 13.0})
		sources = {"1": {"uuid": "1", "username": "******", "type": "bla",
			"channel": 11, "packets": 100}}
		main_window.server_tabs[0].update_sources_table(sources)
		main_window.on_configure_event(None, None)
		main_window.on_config_window(None)
		main_window.on_config_window(None)
		main_window.on_signal_graph(None)
		main_window.on_signal_graph_destroy(None, "11:22:33:44:55:66")
		main_window.fullscreen()
		main_window.fullscreen()
		main_window.on_map_window(None, True)
		main_window.on_map_window(None, False)
		main_window.on_map_widget(None, True)
		main_window.on_map_widget(None, False)
		#main_window.on_server_disconnect(None, 0)
		test_event = TestEvent()
		main_window.on_window_state(None, test_event)
		
		config_window = main_window.config_window
		
		main_window.on_file_import(None)
		
		test_widget.text = "Infrastructure"
		main_window.on_network_filter_type(test_widget)
		main_window.on_network_filter_networks(test_widget, "map", "all")
예제 #14
0
파일: core.py 프로젝트: Kismon/kismon
	def __init__(self):
		user_dir = "%s%s.kismon%s" % (os.path.expanduser("~"), os.sep, os.sep)
		if not os.path.isdir(user_dir):
			print("Creating Kismon user directory %s" % user_dir)
			os.mkdir(user_dir)
		config_file = "%skismon.conf" % user_dir
		self.config_handler = Config(config_file)
		self.config_handler.read()
		self.config = self.config_handler.config

		self.sources = {}
		self.crypt_cache = {}
		self.networks = Networks(self.config)
		self.client_threads = {}
		self.init_client_threads()
		self.tracks = Tracks("%stracks.json" % user_dir)
		self.tracks.load()

		if "--disable-map" in sys.argv:
			self.map_error = "--disable-map used"
		else:
			self.map_error = check_osmgpsmap()
		
		if self.map_error is not None:
			self.map_error =  "%s\nMap disabled" % self.map_error
			print(self.map_error, "\n")
		
		self.init_map()
		
		self.main_window = MainWindow(self.config,
			self.client_start,
			self.client_stop,
			self.map,
			self.networks,
			self.sources,
			self.tracks,
			self.client_threads)
		self.main_window.log_list.add("Kismon", "started")
		if self.map_error is not None:
			self.main_window.log_list.add("Kismon", self.map_error)
		
		self.networks_file = "%snetworks.json" % user_dir
		if os.path.isfile(self.networks_file):
			try:
				self.networks.load(self.networks_file)
			except:
				error = sys.exc_info()[1]
				print(error)
				dialog_message = "Could not read the networks file '%s':\n%s\n\nDo you want to continue?" % (self.networks_file, error)
				dialog = Gtk.MessageDialog(self.main_window.gtkwin, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.YES_NO, dialog_message)
				def dialog_response(dialog, response_id):
					self.dialog_response = response_id
				dialog.connect("response", dialog_response)
				dialog.run()
				dialog.destroy()
				if self.dialog_response == -9:
					print("exit")
					self.clients_stop()
					self.main_window.gtkwin = None
					return
		self.networks.set_autosave(self.config["networks"]["autosave"], self.networks_file, self.main_window.log_list.add)
		
		if self.map is not None:
			self.networks.notify_add_list["map"] = self.add_network_to_map
			self.networks.notify_remove_list["map"] = self.map.remove_marker
			GLib.timeout_add(100, self.map.set_last_from_config)
		
		self.main_window.network_list.crypt_cache = self.crypt_cache
		
		GLib.timeout_add(500, self.queues_handler)
		GLib.timeout_add(300, self.queues_handler_networks)
		GLib.idle_add(self.networks.apply_filters)
예제 #15
0
파일: core.py 프로젝트: Kismon/kismon
class Core:
	def __init__(self):
		user_dir = "%s%s.kismon%s" % (os.path.expanduser("~"), os.sep, os.sep)
		if not os.path.isdir(user_dir):
			print("Creating Kismon user directory %s" % user_dir)
			os.mkdir(user_dir)
		config_file = "%skismon.conf" % user_dir
		self.config_handler = Config(config_file)
		self.config_handler.read()
		self.config = self.config_handler.config

		self.sources = {}
		self.crypt_cache = {}
		self.networks = Networks(self.config)
		self.client_threads = {}
		self.init_client_threads()
		self.tracks = Tracks("%stracks.json" % user_dir)
		self.tracks.load()

		if "--disable-map" in sys.argv:
			self.map_error = "--disable-map used"
		else:
			self.map_error = check_osmgpsmap()
		
		if self.map_error is not None:
			self.map_error =  "%s\nMap disabled" % self.map_error
			print(self.map_error, "\n")
		
		self.init_map()
		
		self.main_window = MainWindow(self.config,
			self.client_start,
			self.client_stop,
			self.map,
			self.networks,
			self.sources,
			self.tracks,
			self.client_threads)
		self.main_window.log_list.add("Kismon", "started")
		if self.map_error is not None:
			self.main_window.log_list.add("Kismon", self.map_error)
		
		self.networks_file = "%snetworks.json" % user_dir
		if os.path.isfile(self.networks_file):
			try:
				self.networks.load(self.networks_file)
			except:
				error = sys.exc_info()[1]
				print(error)
				dialog_message = "Could not read the networks file '%s':\n%s\n\nDo you want to continue?" % (self.networks_file, error)
				dialog = Gtk.MessageDialog(self.main_window.gtkwin, Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.ERROR, Gtk.ButtonsType.YES_NO, dialog_message)
				def dialog_response(dialog, response_id):
					self.dialog_response = response_id
				dialog.connect("response", dialog_response)
				dialog.run()
				dialog.destroy()
				if self.dialog_response == -9:
					print("exit")
					self.clients_stop()
					self.main_window.gtkwin = None
					return
		self.networks.set_autosave(self.config["networks"]["autosave"], self.networks_file, self.main_window.log_list.add)
		
		if self.map is not None:
			self.networks.notify_add_list["map"] = self.add_network_to_map
			self.networks.notify_remove_list["map"] = self.map.remove_marker
			GLib.timeout_add(100, self.map.set_last_from_config)
		
		self.main_window.network_list.crypt_cache = self.crypt_cache
		
		GLib.timeout_add(500, self.queues_handler)
		GLib.timeout_add(300, self.queues_handler_networks)
		GLib.idle_add(self.networks.apply_filters)
		
	def init_map(self):
		if self.map_error is not None:
			self.map = None
		else:
			try:
				from .map import Map
			except SystemError:
				from map import Map
			user_agent = 'kismon/%s' % utils.get_version()
			self.map = Map(self.config["map"], user_agent=user_agent)
			self.map.set_last_from_config()
		
	def init_client_thread(self, server_id):
		server = self.config["kismet"]["servers"][server_id]
		self.client_threads[server_id] = ClientThread(server)
		self.client_threads[server_id].client.set_capabilities(
			('status', 'source', 'info', 'gps', 'bssid', 'bssidsrc', 'ssid'))
		if "--create-kismet-dump" in sys.argv:
			self.client_threads[server_id].client.enable_dump()
		
	def init_client_threads(self):
		server_id=0
		for server in self.config["kismet"]["servers"]:
			self.init_client_thread(server_id)
			server_id += 1
		
	def client_start(self, server_id):
		if server_id in self.client_threads and self.client_threads[server_id].is_running:
			self.client_stop(server_id)
		self.sources[server_id] = {}
		self.init_client_thread(server_id)
		if "--load-kismet-dump" in sys.argv:
			self.client_threads[server_id].client.load_dump(sys.argv[2])
		self.client_threads[server_id].start()
		
	def client_stop(self, server_id):
		if self.client_threads[server_id].client.connecting:
			# kill connecting sockets, don't wait for the timeout
			try:
				self.client_threads[server_id].client.s.shutdown(socket.SHUT_RDWR)
			except OSError:
				pass
		self.client_threads[server_id].stop()
		
	def clients_stop(self):
		for server_id in self.client_threads:
			self.client_stop(server_id)
		return True
		
	def queue_handler(self, server_id):
		server_name = self.config['kismet']['servers'][server_id]
		if self.main_window.gtkwin is None:
			return False
		
		thread = self.client_threads[server_id]
		if len(thread.client.error) > 0:
			for error in thread.client.error:
				self.main_window.log_list.add(server_name, error)
			thread.client.error = []
			self.main_window.server_tabs[server_id].server_switch.set_active(False)
			page_num = self.main_window.notebook.page_num(self.main_window.log_list.widget)
			self.main_window.notebook.set_current_page(page_num)
		
		#gps
		gps = None
		fix = None
		gps_queue = thread.get_queue("gps")
		while True:
			try:
				data = gps_queue.pop()
				if gps is None:
					gps = data
				if data["fix"] > 1:
					fix = (data["lat"], data["lon"])
					if self.config['tracks']['store'] == True:
						self.tracks.add_point_to_track(server_name, data['lat'], data['lon'], data['alt'])
					break
			except IndexError:
				break
		if gps is not None:
			self.main_window.server_tabs[server_id].update_gps_table(gps)
			if fix is not None and self.map is not None:
				server = "server%s" % (server_id + 1)
				if server_id == 0:
					self.map.set_position(fix[0], fix[1])
				else:
					self.map.add_marker(server, server, fix[0], fix[1])
				self.map.add_track(fix[0], fix[1], server_id)
		
		#status
		for data in thread.get_queue("status"):
			self.main_window.log_list.add(server_name, data["text"])
		
		#info
		info_queue = thread.get_queue("info")
		try:
			data = info_queue.pop()
			self.main_window.server_tabs[server_id].update_info_table(data)
		except IndexError:
			pass
			
		#source
		update = False
		for data in thread.get_queue("source"):
			uuid = data["uuid"]
			if uuid == "00000000-0000-0000-0000-000000000000":
				continue
			self.sources[server_id][uuid] = data
			
			update = True
		if update is True:
			self.main_window.server_tabs[server_id].update_sources_table(self.sources[server_id])
		
	def queues_handler(self):
		for server_id in self.client_threads:
			self.queue_handler(server_id)
		return True
		
	def queue_handler_networks(self, server_id):
		thread = self.client_threads[server_id]
		
		#ssid
		for data in thread.get_queue("ssid"):
			self.networks.add_ssid_data(data)
		
		#bssid
		bssids = {}
		for data in thread.get_queue("bssid"):
			mac = data["bssid"]
			self.networks.add_bssid_data(data, server_id)
			if mac in self.main_window.signal_graphs and "signal_dbm" not in thread.client.capabilities["bssidsrc"]:
				self.main_window.signal_graphs[mac].add_value(None, None, data["signal_dbm"], server_id)
			
			bssids[mac] = True
			
		#bssidsrc
		for data in thread.get_queue("bssidsrc"):
			if "signal_dbm" not in data or data["uuid"] not in self.sources[server_id]:
				continue
			
			mac = data["bssid"]
			if mac in self.main_window.signal_graphs:
				self.main_window.signal_graphs[mac].add_value(self.sources[server_id][data["uuid"]], data, data["signal_dbm"], server_id)
		
		if len(self.networks.notify_add_queue) > 0:
			self.networks.start_queue()
			if len(self.networks.notify_add_queue) > 500:
				self.networks.disable_refresh()
				self.main_window.networks_queue_progress()
		
		self.main_window.update_statusbar()
		
	def queues_handler_networks(self):
		for server_id in self.client_threads:
			self.queue_handler_networks(server_id)
		return True
		
	def quit(self):
		self.clients_stop()
		
		if self.map is not None:
			lat = self.map.osm.get_property("latitude")
			lon = self.map.osm.get_property("longitude")
			self.config["map"]["last_position"] = "%.6f/%.6f" % (lat, lon)

		while None in self.config['kismet']['servers']:
			self.config['kismet']['servers'].remove(None)
		self.config_handler.write()
		self.networks.save(self.networks_file, force=True)
		if self.config['tracks']['store'] == True:
			self.tracks.save()

	def add_network_to_map(self, mac):
		network = self.networks.get_network(mac)
		
		try:
			crypt = self.crypt_cache[network["cryptset"]]
		except KeyError:
			crypt = decode_cryptset(network["cryptset"], True)
			self.crypt_cache[network["cryptset"]] = crypt
		
		if "AES_CCM" in crypt or "AES_OCB" in crypt:
			color = "red"
		elif "WPA" in crypt:
			color = "orange"
		elif "WEP" in crypt:
			color = "yellow"
		else:
			color = "green"
		
		self.map.add_marker(mac, color, network["lat"], network["lon"])
예제 #16
0
파일: k9d.py 프로젝트: aaaler/k9
class K9dApp:
    #Compile RE for iwconfig ouput parsing
    brre = re.compile(r"Bit Rate=([\d.]+ \S+)", re.M)
    lqre = re.compile(r"Link Quality=(\d+/\d+)  Signal level=(-\d+ dBm)", re.M)

    def __init__(self):
        #Kind a config here
        #arduino tracks bridge pinout
        self.tracks = Tracks(pin.port.PB5, pin.port.PB6, 28, pin.port.PB7,
                             pin.port.PB10, 29, 20)
        #ip
        self.addr = "192.168.0.22"
        self.UDP_IP = "0.0.0.0"
        self.UDP_PORT = 9999
        #sonar
        self.sonaron = True
        self.sonarfailsafe = 0.
        #mjpg_streamer related
        self.videomode = 'OFF'

        #init
        self.faststate = {}
        self.faststate["proxalert"] = False
        self.sonardist = 0
        self.sonarfailsafe_active = False
        self.festivalup = False
        self.log_init()
        #==============UDP INIT====================
        self.log.info("spinal interface daemon for K-9 starting")
        self.servsock = socket.socket(
            socket.AF_INET,  # Internet
            socket.SOCK_DGRAM)  # UDP
        self.servsock.bind((self.UDP_IP, self.UDP_PORT))
        self.respsock = socket.socket(
            socket.AF_INET,  # Internet
            socket.SOCK_DGRAM)  # UDP
        #============SERIAL INIT===================
        try:
            self.spinal = serial.Serial('/dev/ttyS2', 115200, timeout=0.5)
            self.spinal_enabled = True
        except:
            self.spinal_enabled = False
            self.log.info(
                "Could not open port for arduino -- connection disabled ")

        try:
            self.sonar = serial.Serial('/dev/ttyS1', 9600, timeout=0.5)
            self.sonar_enabled = True
        except:
            self.log.error("Could not open port for sonar -- sonar disabled")
            self.sonar_enabled = False

        #===========THREADING INIT=================

        self.faststate['S1'] = -1
        self.faststate['S2'] = -1
        self.faststate['A1'] = -1
        self.faststate['A2'] = -1
        self.faststate['A3'] = -1

        if self.spinal_enabled:
            self.tSerialRead = threading.Thread(target=self.sreader)
            self.tSerialRead.setDaemon(1)
            self.tSerialRead.start()

        self.tTrackWatchdog = threading.Thread(target=self.cmdtimeout)
        self.tTrackWatchdog.setDaemon(1)
        self.tTrackWatchdog.start()

        self.tStateUpload = threading.Thread(target=self.tstateup)
        self.tStateUpload.setDaemon(1)
        self.tStateUpload.start()

        if self.sonar_enabled:
            self.tSonar = threading.Thread(target=self.tsonar)
            self.tSonar.setDaemon(1)
            self.tSonar.start()

        self.log.info("ready to play")

    def __del__(self):
        self.log.info("Shutting down daemon")
        self.gsens.__del__()
        self.gsens = None

    def gsens_update(self):
        if hasattr(self.gsens, 'yaw'):
            self.faststate['yaw'] = self.gsens.yaw
            self.faststate['pitch'] = self.gsens.pitch
            self.faststate['roll'] = self.gsens.roll
            self.faststate['ax'] = self.gsens.ax
            self.faststate['ay'] = self.gsens.ay
            self.faststate['az'] = self.gsens.az
            self.stateupload()

    def log_init(self):

        if hasattr(self, 'log'):
            self.log.removeHandler(self.stdoutloghandler)
            self.log.removeHandler(self.udploghandler)
        else:
            self.log = logging.getLogger('k9d')

        self.stdoutloghandler = logging.StreamHandler(sys.stdout)
        self.stdoutloghandler.setFormatter(
            logging.Formatter(
                "%(asctime)s [%(name)s#%(levelname)s]: %(message)s"))
        self.stdoutloghandler.setLevel(logging.DEBUG)
        self.udploghandler = logging.handlers.DatagramHandler(
            self.addr, self.UDP_PORT)
        self.udploghandler.setFormatter(
            logging.Formatter(
                "%(asctime)s [%(name)s#%(levelname)s]: %(message)s"))
        self.udploghandler.setLevel(logging.DEBUG)

        self.log.setLevel(logging.DEBUG)
        self.log.addHandler(self.stdoutloghandler)
        self.log.addHandler(self.udploghandler)

    def mainloop(self):
        while True:
            data, (addr, self.port) = self.servsock.recvfrom(
                1024)  # buffer size is 1024 bytes
            if addr != self.addr:
                self.log.warn("New client ip: {}".format(addr))
                self.addr = addr
                self.log_init()
            out = "{}>{} &".format(str(self.addr), data)

            request = data.split(' ')
            CMD = request.pop(0)
            CMD = CMD.strip("\n")
            if CMD == "STOP":
                self.tracks.neutral()
                self.faststate['trackr'] = self.tracks.trackr
                self.faststate['trackl'] = self.tracks.trackl
                self.stateupload()
                self.log.debug("Tracks vector set to neutral")
            elif CMD == "SPINAL":
                emsg = ' '.join(request)
                self.log.info("Sending user packet to spinal: {}".format(emsg))
                self.spinal_write(emsg)
            elif CMD == "PING":
                self.log.info("PING {} got".format(request[0]))
                self.send("PONG {} {}".format(time.time(), request[0]),
                          self.addr)
            elif CMD == "TRACKS":
                self.tracks.vector(request[0], request[1])
                self.log.debug("Tracks vector set to {},{}".format(
                    request[0], request[1]))
                self.faststate['trackr'] = self.tracks.trackr
                self.faststate['trackl'] = self.tracks.trackl
                self.stateupload()
            elif CMD == "SERVO":
                self.servo(request[0], request[1])
            elif CMD == "SON":
                if request[0] == 'Failsafe':
                    self.sonaron = True
                    if request[1] == 'off': self.sonarfailsafe = 0
                    else: self.sonarfailsafe = float(request[1])
                elif request[0] == 'Sonar' and request[1] == 'off':
                    self.sonaron = False
                    self.sonarfailsafe = 0
            elif CMD == "CAM":
                if request[0] == 'RES':
                    if hasattr(self, 'pmjpg'):
                        if self.pmjpg.poll() == None:
                            pid = self.pmjpg.pid
                            self.pmjpg.kill()
                            self.videomode = "OFF"
                            t = threading.Timer(2.0, self.run_mjpg,
                                                [request[1]])
                            t.start()
                            self.log.info(
                                "Killed mjpg with pid {} and deferred run with {}"
                                .format(pid, request[1]))
                        else:
                            self.run_mjpg(request[1])
                    else:
                        self.run_mjpg(request[1])
                elif request[0] == 'OFF':
                    if hasattr(self, 'pmjpg') and self.pmjpg.poll() == None:
                        self.pmjpg.kill()
                    self.videomode = "OFF"
                    self.log.info("Killed mjpg.")
                elif request[0] == 'ZOOM' and request[1] == 'OFF':
                    status = subprocess.call(
                        ["/usr/bin/v4l2-ctl", "--set-ctrl=zoom_absolute=1"])
                    self.log.info("Zoom OFF")
                elif request[0] == 'ZOOM' and request[1] == 'ON':
                    status = subprocess.call(
                        ["/usr/bin/v4l2-ctl", "--set-ctrl=zoom_absolute=5"])
                    self.log.info("Zoom ON")
            elif CMD == "FESTIVAL":
                if request[0] == 'ON':
                    if hasattr(self, 'pfestival'):
                        if self.pfestival.poll() == None:
                            pid = self.pfestival.pid
                            self.pfestival.kill()
                            self.festivalup = False
                            t = threading.Timer(2.0, self.run_festival)
                            t.start()
                            self.log.info(
                                "Killed festival with pid {} and deferred run".
                                format(pid))
                        else:
                            self.run_festival()
                    else:
                        self.run_festival()
                elif request[0] == 'OFF':
                    if hasattr(self,
                               'pfestival') and self.pfestival.poll() == None:
                        self.pfestival.kill()
                    self.festivalup = False
                    self.log.info("Killed festival")
            elif CMD == "SAY":
                tts = cPickle.loads(data[4:])
                if self.festivalup:
                    self.pfestival.stdin.write("(SayText \"{}\")".format(
                        tts.encode("utf-8")))
                    self.pfestival.stdin.flush()
                    self.log.info("Pronouncing '{}'".format(
                        tts.encode("utf-8")))
                else:
                    self.log.err("Can't SAY, festival down")
            elif CMD == 'EVAL':
                ecmd = " ".join(request)
                try:
                    output = eval("pprint.pformat({})".format(ecmd))
                    self.log.info("{} = {}".format(ecmd, output))
                except Exception, e:
                    self.log.error(
                        "eval \"{}\" raised {} Exception: {}".format(
                            ecmd,
                            type(e).__name__, e))

            elif CMD == "GSENSOR":
                if request[0] == 'ON':
                    self.gsens = GSens(0, self.gsens_update, self.log.error,
                                       self.log.info, self.log.debug)
                elif request[0] == 'OFF':
                    self.gsens.__del__()
                    self.gsens = None

            else:
예제 #17
0
파일: k9d.py 프로젝트: aaaler/k9
    def __init__(self):
        #Kind a config here
        #arduino tracks bridge pinout
        self.tracks = Tracks(pin.port.PB5, pin.port.PB6, 28, pin.port.PB7,
                             pin.port.PB10, 29, 20)
        #ip
        self.addr = "192.168.0.22"
        self.UDP_IP = "0.0.0.0"
        self.UDP_PORT = 9999
        #sonar
        self.sonaron = True
        self.sonarfailsafe = 0.
        #mjpg_streamer related
        self.videomode = 'OFF'

        #init
        self.faststate = {}
        self.faststate["proxalert"] = False
        self.sonardist = 0
        self.sonarfailsafe_active = False
        self.festivalup = False
        self.log_init()
        #==============UDP INIT====================
        self.log.info("spinal interface daemon for K-9 starting")
        self.servsock = socket.socket(
            socket.AF_INET,  # Internet
            socket.SOCK_DGRAM)  # UDP
        self.servsock.bind((self.UDP_IP, self.UDP_PORT))
        self.respsock = socket.socket(
            socket.AF_INET,  # Internet
            socket.SOCK_DGRAM)  # UDP
        #============SERIAL INIT===================
        try:
            self.spinal = serial.Serial('/dev/ttyS2', 115200, timeout=0.5)
            self.spinal_enabled = True
        except:
            self.spinal_enabled = False
            self.log.info(
                "Could not open port for arduino -- connection disabled ")

        try:
            self.sonar = serial.Serial('/dev/ttyS1', 9600, timeout=0.5)
            self.sonar_enabled = True
        except:
            self.log.error("Could not open port for sonar -- sonar disabled")
            self.sonar_enabled = False

        #===========THREADING INIT=================

        self.faststate['S1'] = -1
        self.faststate['S2'] = -1
        self.faststate['A1'] = -1
        self.faststate['A2'] = -1
        self.faststate['A3'] = -1

        if self.spinal_enabled:
            self.tSerialRead = threading.Thread(target=self.sreader)
            self.tSerialRead.setDaemon(1)
            self.tSerialRead.start()

        self.tTrackWatchdog = threading.Thread(target=self.cmdtimeout)
        self.tTrackWatchdog.setDaemon(1)
        self.tTrackWatchdog.start()

        self.tStateUpload = threading.Thread(target=self.tstateup)
        self.tStateUpload.setDaemon(1)
        self.tStateUpload.start()

        if self.sonar_enabled:
            self.tSonar = threading.Thread(target=self.tsonar)
            self.tSonar.setDaemon(1)
            self.tSonar.start()

        self.log.info("ready to play")
예제 #18
0
파일: k9d.py 프로젝트: aaaler/k9
    def __init__ (self):
        #Kind a config here
        #arduino tracks bridge pinout
        self.tracks = Tracks (pin.port.PB5, pin.port.PB6, 28, pin.port.PB7, pin.port.PB10, 29, 20)
        #ip
        self.addr = "192.168.0.22"
        self.UDP_IP = "0.0.0.0"
        self.UDP_PORT = 9999
        #sonar
        self.sonaron = True
        self.sonarfailsafe = 0.
        #mjpg_streamer related
        self.videomode = 'OFF'
       
        #init
        self.faststate = {}
        self.faststate["proxalert"] = False
        self.sonardist = 0
        self.sonarfailsafe_active = False
        self.festivalup = False
        self.log_init()
        #==============UDP INIT====================
        self.log.info ("spinal interface daemon for K-9 starting");
        self.servsock = socket.socket(socket.AF_INET, # Internet
                              socket.SOCK_DGRAM) # UDP
        self.servsock.bind((self.UDP_IP, self.UDP_PORT))
        self.respsock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
        #============SERIAL INIT===================
        try:
          self.spinal = serial.Serial('/dev/ttyS2', 115200, timeout=0.5)
          self.spinal_enabled = True
        except:
          self.spinal_enabled = False
          self.log.info("Could not open port for arduino -- connection disabled ")                
        
        try:
          self.sonar = serial.Serial('/dev/ttyS1', 9600, timeout=0.5)
          self.sonar_enabled = True
        except:
          self.log.error("Could not open port for sonar -- sonar disabled")
          self.sonar_enabled = False
        
        #===========THREADING INIT=================
        
        self.faststate['S1']=-1
        self.faststate['S2']=-1
        self.faststate['A1']=-1
        self.faststate['A2']=-1
        self.faststate['A3']=-1

        if self.spinal_enabled:
            self.tSerialRead = threading.Thread(target=self.sreader)
            self.tSerialRead.setDaemon (1)
            self.tSerialRead.start()
        
        self.tTrackWatchdog = threading.Thread(target=self.cmdtimeout)
        self.tTrackWatchdog.setDaemon (1)
        self.tTrackWatchdog.start()
        
        self.tStateUpload = threading.Thread(target=self.tstateup)
        self.tStateUpload.setDaemon (1)
        self.tStateUpload.start()
    
        if self.sonar_enabled:        
            self.tSonar = threading.Thread(target=self.tsonar)
            self.tSonar.setDaemon (1)
            self.tSonar.start()

        
        self.log.info ("ready to play");