Exemplo n.º 1
0
class Monitor:
    def __init__(self):
        self._rate_detectors = defaultdict(RateDetector)

    def connect(self):
        self._client = LognplotTcpClient()
        self._client.connect()

    def update(self):
        for process_folder in os.listdir('/proc'):
            if re.match(r'\d+', process_folder):
                # print("Ow yeah!")
                timestamp = time.time()
                stat_filename = f'/proc/{process_folder}/stat'
                with open(stat_filename, 'r') as f:
                    line = f.read()
                # print(line)
                self.analyze_line(timestamp, line)
                # self.measure(timestamp, pid, filename, user_jiffies, kernel_jiffies)

    def analyze_line(self, timestamp, line):
        parts = line.split(' ')
        pid = int(parts[0])
        filename = parts[1]
        user_jiffies = int(parts[13])
        kernel_jiffies = int(parts[14])
        # print(pid, filename)
        self.measure(f'{filename}_{pid}_user', (timestamp, user_jiffies))
        self.measure(f'{filename}_{pid}_kernel', (timestamp, kernel_jiffies))
    
    def measure(self, signal_name, measurement):
        rate = self._rate_detectors[signal_name].update(measurement)
        # print(signal_name, rate)
        self._client.send_sample(signal_name, float(measurement[0]), float(rate))
Exemplo n.º 2
0
def main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("--ams-net-id",
                        help="ams net id",
                        default="127.0.0.1.1.1",
                        type=str)
    parser.add_argument("--ams-net-port",
                        help="ams net port",
                        default=851,
                        type=int)
    parser.add_argument(
        "--regex",
        help="Regular expression pattern used for filtering",
        default=".*",
        type=str,
    )
    parser.add_argument("--lognplot-hostname", default="localhost", type=str)
    parser.add_argument("--lognplot-port", default="12345", type=int)
    args = parser.parse_args()

    lnp_client = LognplotTcpClient(hostname=args.lognplot_hostname,
                                   port=args.lognplot_port)
    lnp_client.connect()

    ads_client = AdsClient(args.ams_net_id, args.ams_net_port, lnp_client)

    ads_client.subscribe(args.regex)
Exemplo n.º 3
0
 def connect(self):
     try:
         self._client = LognplotTcpClient(hostname=self._lognplot_host,
                                          port=self._lognplot_port)
         self._client.connect()
     except ConnectionRefusedError:
         print("Error connecting to lognplot GUI!")
         self._client = None
Exemplo n.º 4
0
def init_lognplot(hostname, port):
    client = None
    try:
        client = LognplotTcpClient(hostname=hostname, port=port)
        print("Connecting to lognplot...")
        client.connect()
    except ConnectionError as err:
        print("Error while connecting to lognplot: ", err)
    except TimeoutError as err:
        print("Error while connecting to lognplot: ", err)

    return client
Exemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("mqtt_hostname",
                        help="Hostname of the mqtt server",
                        type=str)
    parser.add_argument("--mqtt-port",
                        help="Port of the mqtt server",
                        default=1883,
                        type=int)
    parser.add_argument("--topic",
                        help="Topic to subscribe to",
                        default="#",
                        type=str)
    parser.add_argument("--lognplot-hostname", default="127.0.0.1", type=str)
    parser.add_argument("--lognplot-port", default="12345", type=int)
    args = parser.parse_args()

    lognplot_client = LognplotTcpClient(hostname=args.lognplot_hostname,
                                        port=args.lognplot_port)
    lognplot_client.connect()

    # The callback for when the client receives a CONNACK response from the server.
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code " + str(rc))

        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        client.subscribe(args.topic)

    # The callback for when a PUBLISH message is received from the server.
    def on_message(client, userdata, msg):
        try:
            value = float(msg.payload)
        except ValueError:
            pass
        else:
            timestamp = time.time()
            topic_name = "/mqtt{}".format(msg.topic)
            lognplot_client.send_sample(topic_name, timestamp, value)

    mqtt_client = mqtt.Client()
    mqtt_client.on_connect = on_connect
    mqtt_client.on_message = on_message

    mqtt_client.connect(args.mqtt_hostname, args.mqtt_port, 60)

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    mqtt_client.loop_forever()
Exemplo n.º 6
0
def main():
    t = 0.0
    A = 10.0  # Sine wave amplitude [-]
    F = 1.3  # Sine wave frequency [Hz]
    A2 = 1.2
    F2 = 100
    B = 5.0  # Sine wave offset
    client = LognplotTcpClient()
    client.connect()

    dt = 0.0001  # 10 kHz
    n_samples = 2000
    while True:
        samples = []
        samples2 = []
        t0 = t
        # Generate samples:
        for _ in range(n_samples):
            omega = 2 * math.pi * F
            omega2 = 2 * math.pi * F2
            sample = A * math.sin(omega * t) + B + A2 * math.cos(omega2 * t)
            sample2 = A * math.sin(omega * t) + B + A2 * math.cos(omega2 * t) + 9
            samples.append(sample)
            samples2.append(sample2)

            # Increment time:
            t += dt

        print(f"Sending {len(samples)} samples")
        client.send_samples("Trace1", t0, dt, samples)
        client.send_samples("Trace2", t0, dt, samples2)

        time.sleep(n_samples * dt)
Exemplo n.º 7
0
def main():
    t = 0.0
    dt = 2.0
    client = LognplotTcpClient()
    client.connect()
    while True:
        print(f'Sending at t={t}')
        for x in range(20):
            client.send_sample(f"Trace_{x}", t, (t + x) % 36)
        time.sleep(dt)
        t += dt
Exemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("csv_file")
    parser.add_argument("--delimiter",
                        default=",",
                        help="The value delimiter to use")
    parser.add_argument(
        "--skip-rows",
        default=0,
        type=int,
        help="Amount of rows to skip at the beginning of the file",
    )
    parser.add_argument(
        "--time-column",
        type=int,
        help=
        "The CSV column to use as time column. If not provided, the CSV row will be used as time.",
    )
    parser.add_argument("--lognplot-hostname", default="localhost", type=str)
    parser.add_argument("--lognplot-port", default="12345", type=int)
    args = parser.parse_args()
    print(args)

    lognplot_client = LognplotTcpClient(hostname=args.lognplot_hostname,
                                        port=args.lognplot_port)
    lognplot_client.connect()

    if hasattr(args, "time_column") and args.time_column is not None:
        time_column = int(args.time_column)
    else:
        time_column = None

    with open(args.csv_file, "r") as csv_file:
        reader = csv.reader(csv_file, delimiter=args.delimiter)
        for row_index, row in enumerate(reader):
            if row_index >= args.skip_rows:
                # print(row)

                timestamp = (float(row[time_column])
                             if time_column is not None else row_index)

                for column_index, column in enumerate(row):
                    name = f"csv_column_{column_index}"
                    lognplot_client.send_sample(name, timestamp, float(column))
Exemplo n.º 9
0
def main():
    client = LognplotTcpClient()
    client.connect()

    N_batches = 1_000
    batch_size = 10_000

    timestamp = 0.0
    value = 0.0

    for _ in range(N_batches):
        samples = []
        for _ in range(batch_size):
            samples.append((timestamp, value))

            # Create next value:
            timestamp += 0.7 + random.random() * 10.0
            value += -0.5 + random.random()

        client.send_sample_batch("TEN_MEG", samples)
Exemplo n.º 10
0
    polledObjects = NatSort(parent=app)
    polledObjects.setSourceModel(model)
    polledObjects.setSortRole(model.NameRole)
    polledObjects.setFilterRole(model.PollingRole)
    polledObjects.setFilterRegularExpression('true')
    polledObjects.setSortCaseSensitivity(Qt.CaseInsensitive)
    polledObjects.sort(0)

    engine.rootContext().setContextProperty("objects", filteredObjects)
    engine.rootContext().setContextProperty("polledObjects", polledObjects)

    if args.lognplot != None:
        print(
            f'Connecting to lognplot at {args.lognplot}:{args.lognplotport}...'
        )
        lognplot = LognplotTcpClient(args.lognplot, args.lognplotport)
        lognplot.connect()
        for o in client.objects:
            if o.isFixed():
                o.valueUpdated.connect(lambda o=o: lognplot_send(lognplot, o))

    engine.load(
        QUrl.fromLocalFile(
            os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "gui_client.qml")))
    if not engine.rootObjects():
        sys.exit(-1)

    client.restoreState()

    res = app.exec_()
Exemplo n.º 11
0
def main():
    t = 0.0
    A = 10.0  # Sine wave amplitude [-]
    F = 1.3  # Sine wave frequency [Hz]
    A2 = 1.2
    F2 = 100
    B = 5.0  # Sine wave offset
    sigma_delta_step = 0.3
    sigma_delta_value = 0
    client = LognplotTcpClient()
    client.connect()

    dt = 0.0001  # 10 kHz
    n_samples = 2000
    while True:
        samples = []
        samples2 = []
        samples3 = []
        samples4 = []

        t0 = t
        # Generate samples:
        for _ in range(n_samples):
            omega = 2 * math.pi * F
            omega2 = 2 * math.pi * F2
            sample = A * math.sin(omega * t) + B + A2 * math.cos(omega2 * t)
            sample2 = A * math.sin(omega * t) + B + A2 * math.cos(
                omega2 * t) + 9

            # Track sample with binary output:
            if sigma_delta_value < sample:
                sample3 = 1.0
                sigma_delta_value += sigma_delta_step
            else:
                sample3 = 0.0
                sigma_delta_value -= sigma_delta_step

            samples.append(sample)
            samples2.append(sample2)
            samples3.append(sample3)
            samples4.append(float(random.randint(0, 1)))

            # Increment time:
            t += dt

        gen = random_bits()
        samples5 = [float(next(gen)) for _ in range(n_samples)]

        print(f"Sending {len(samples)} samples")
        client.send_samples("Trace1", t0, dt, samples)
        client.send_samples("Trace2", t0, dt, samples2)
        client.send_samples("SIGMA-DELTA", t0, dt, samples3)
        client.send_samples("RANDOM", t0, dt, samples4)
        client.send_samples("TEXT_BITS", t0, dt, samples5)
        client.send_text("Log", t0, f"Log at {t0:.3}")
        client.send_text("Log2", t0, f"Another log at {t0:.3}")
        client.send_text("Other TXT", t0, f"Yet {t0:.3} blah")

        time.sleep(n_samples * dt)
Exemplo n.º 12
0
class RosToLogNPlot:
    def __init__(self, lognplot_host, lognplot_port):
        self._subscriptions = {}
        self._lognplot_host = lognplot_host
        self._lognplot_port = lognplot_port

    def connect(self):
        try:
            self._client = LognplotTcpClient(hostname=self._lognplot_host,
                                             port=self._lognplot_port)
            self._client.connect()
        except ConnectionRefusedError:
            print("Error connecting to lognplot GUI!")
            self._client = None

    def is_connected(self):
        return bool(self._client)

    def run(self):
        self.node = rclpy.create_node("ros_to_lognplot")
        self.timer = self.node.create_timer(2.0, self._check_topics)
        self.node.create_subscription(Log, "/rosout", self.on_ros_out_msg, 0)
        rclpy.spin(self.node)
        rclpy.shutdown()

    def on_ros_out_msg(self, msg):
        signal_name = f'/rosout/{msg.name}'
        timestamp = time.time()
        text = msg.msg
        self.send_text(signal_name, timestamp, text)

    def _check_topics(self):
        """ Check which topics are present in the system, and subscribe to them all!
        """
        topics = self.node.get_topic_names_and_types()
        for topic_name, topic_type_name in topics:
            if not self.is_subscribed(topic_name):
                print("-", topic_name, "---", topic_type_name)
                topic_type = load_type(topic_type_name[0])
                self._subscribe_on_topic(topic_name, topic_type)

    def is_subscribed(self, topic_name):
        return topic_name in self._subscriptions

    def _subscribe_on_topic(self, topic_name, topic_type):
        assert topic_name not in self._subscriptions

        def handler(msg):
            timestamp = time.time()
            self.process_message(topic_name, topic_type, timestamp, msg)

        subscription = self.node.create_subscription(topic_type, topic_name,
                                                     handler,
                                                     qos_profile_sensor_data)
        self._subscriptions[topic_name] = subscription

    def process_message(self, topic_name, topic_type, timestamp, msg):
        """ Process an incoming ROS message.
        """
        self.process_value(topic_name, topic_type, timestamp, msg)

    def process_value(self, full_name, value_type, timestamp, value):
        if hasattr(value, "get_fields_and_field_types"):
            for field_name, field_type in value.get_fields_and_field_types(
            ).items():
                field_value = getattr(value, field_name)
                full_field_name = f"{full_name}.{field_name}"
                self.process_value(full_field_name, field_type, timestamp,
                                   field_value)
        else:
            if isinstance(value, (float, np.float32, int)):
                self.send_sample(full_name, timestamp, float(value))
            elif isinstance(value, (list, np.ndarray)):
                for element_index, element_value in enumerate(value):
                    element_name = f"{full_name}[{element_index}]"
                    element_type = None
                    self.process_value(element_name, element_type, timestamp,
                                       element_value)
            else:
                # Great panic! What now?
                # Ignore for now..
                pass

    def send_sample(self, signal_name: str, timestamp, value):
        """ Emit a single sample to the lognplot GUI. """
        if self._client:
            self._client.send_sample(signal_name, timestamp, value)

    def send_text(self, signal_name: str, timestamp, text):
        """ Emit a single text to the lognplot GUI. """
        if self._client:
            self._client.send_text(signal_name, timestamp, text)
Exemplo n.º 13
0
import numpy as np
import binascii
import struct
import time
import bitstruct

import scipy.fftpack
import fport_tx
import random

from lognplot.client import LognplotTcpClient

#baud = 115200 # 2000000
baud = 2000000

client = LognplotTcpClient()
client.connect()

use_file = len(sys.argv) > 1

if use_file:
    inputFile = open(sys.argv[1], "rb")
else:
    ser = serial.Serial(port='/dev/ttyUSB0', baudrate=baud, stopbits=1)
    ser.flushInput()

size = 1024
pause_time = 0.1

msgGyro = struct.Struct('< i i i')
Exemplo n.º 14
0
def main():
    client = LognplotTcpClient()
    client.connect()
    topic = 'test'
    value = 1337.0
    client.send_sample(topic, 10.0, value)
Exemplo n.º 15
0
    "--source",
    help="Description of the hawktracer source; either file name or IP address",
    required=True,
)
parser.add_argument("--lognplot-hostname", default="127.0.0.1", type=str)
parser.add_argument("--lognplot-port", default="12345", type=int)

args = parser.parse_args()

# Connect to hawktracer:
hawktracer_client = HawkTracerClient()
hawktracer_client.start(args.source)

# Connect to lognplot:
lognplot_client = LognplotTcpClient(
    hostname=args.lognplot_hostname, port=args.lognplot_port
)
lognplot_client.connect()

# Harvest data:

was_eos = False

while True:
    event = hawktracer_client.poll_event()

    if event:
        event_type, data = event
        if event_type == "HT_CallstackStringEvent":
            # Convert timestamp to second-ish units:
            timestamp = float(data["timestamp"]) / 1e9
Exemplo n.º 16
0
 def connect(self):
     self._client = LognplotTcpClient()
     self._client.connect()
Exemplo n.º 17
0
"""

import argparse
import struct
import sys
from lognplot.client import LognplotTcpClient

# Assume 44100 Hz and
fs = 44100
ts = 1 / fs
fmt = "S16_LE"
fmt = "<h"  # 16 bit signed little endian
t = 0.0
buf_size = 2048  # Number of samples to read at once.
sample_size = struct.calcsize(fmt)

lpc = LognplotTcpClient()
lpc.connect()

while True:
    data = sys.stdin.buffer.read(buf_size * sample_size)

    print(len(data))
    samples = []
    for i in range(buf_size):
        (v, ) = struct.unpack(
            fmt, data[i * sample_size:i * sample_size + sample_size])
        samples.append(float(v))
    lpc.send_samples("AUDIO", t, ts, samples)
    t += buf_size * ts