Ejemplo n.º 1
0
    def __init__(self, ser):
        self._last_angles = np.ndarray
        self._last_imu = np.ndarray

        # https://www.pieter-jan.com/node/11
        self.pitch_acc = 0
        self.roll_acc = 0
        self.pitch = 0
        self.roll = 0

        self._tx_thread = Transmitter(name="tx_th", ser=ser)
        self._rx_thread = Receiver(name="rx_th", ser=ser)
        self._rx_thread.set_timeout(0.010)
        self._rx_thread.bind(self.receive_callback)

        self._pub_imu = rp.Publisher('imu_raw', Imu, queue_size=1)
        self._pub_joint_states = rp.Publisher('joint_states',
                                              JointState,
                                              queue_size=1)
        self._motor_map = rp.get_param("~motor_mapping")
        self._imu_calibration = rp.get_param("~imu_calibration")
        for motor in self._motor_map:
            self._motor_map[motor]["subscriber"] = rp.Subscriber(
                motor + "/command", Float64, self.trajectory_callback, motor)
            self._motor_map[motor]["publisher"] = rp.Publisher(
                motor + "/state", JointControllerState, queue_size=1)
            self._motor_map[motor]["value"] = 0.0

        self._publish_timer = rp.Timer(rp.Duration(nsecs=10000000),
                                       self.send_angles)
Ejemplo n.º 2
0
 def __init__(self):
     self.__transmitter = Transmitter()
     self.__configpath = self.__set_configpath()
     self.__config = self.__init_config()
     self.__default_account = AccountManager.get_default_account()
     self.__accounts = []
     self.__load_accounts_from_config()
Ejemplo n.º 3
0
    def __init__(self):
        mainServerIP = globe.components.mainServerIp
        mainServerPort = globe.components.mainServerPort
        self.mainServerAddress = 'http://' + mainServerIP + ':' + mainServerPort

        # Starting receiver flask server process:
        print("Starting the receiver HTTP server...\n")

        self.serverThread = threading.Thread(target=initReceiver, args=())
        self.serverThread.start()
        time.sleep(1)

        self.transmitter = Transmitter(self.mainServerAddress)

        # Send the content of jsonPath to each devices:
        print("\nSending JSON paths to devices...")

        archAddress = globe.content[0][:-1]
        connMapAddress = globe.content[1][:-1]
        data = archAddress + '#' + connMapAddress

        for ip in globe.components.devicesIp:
            address = f'http://{ip}:8484/updateJsonPath'  # f for format

            response = requests.post(address, data)
            if globe.jupyterFlag == 0:
                print(response.ok, response.status_code)

        time.sleep(1)
Ejemplo n.º 4
0
def clicked_btn():
    string = r'(25[0-5]|2[0-4][0-9]|[0]|[1]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[0]|[1]?[0-9][0-9]?)){3}'
    ip = IP_entry.get()
    port = int(port_spin.get())
    buff_size = int(Buff_size_spin.get())
    file_name = open_file_entry.get()
    Prog_bar_w.configure(maximum=os.path.getsize(file_name) // buff_size)
    if re.fullmatch(string, ip) and 10000 < int(port) < 65535 and 100 <= int(buff_size) <= 8958 and file_name:
        sender = Transmitter(ip, file_name, buff_size, port)
        t = Thread(target=sender.send, args=(queue,))
        txt.insert("insert",
                   'Sending {} to {} at port {}, UDP data size - {}'.format(os.path.basename(file_name), ip, port,
                                                                            buff_size) + '\n')
        txt.yview('end')
        try:
            t.start()
            check_queue()
        except ConnectionRefusedError:
            txt.insert("insert", "Error" + '\n')
            txt.insert("insert", "-" * 70 + '\n')
            txt.yview('end')
            messagebox.showinfo("Ошибка", "Удаленный компьютер не отвечает")
            Prog_bar_w.stop()
            Prog_bar_w["value"] = 0
        else:
            txt.insert("insert", "Done" + '\n')
            txt.insert("insert", "-" * 70 + '\n')
            txt.yview('end')
            open_file_entry.delete(0, 'end')
            Prog_bar_w.stop()
            Prog_bar_w["value"] = 0
    else:
        messagebox.showinfo("Ошибка", "Некоректные данные сетевого соединения или не выбран файл")
Ejemplo n.º 5
0
 def __init__(self, numOfInputs):
     self.transmitter = Transmitter()
     self.receiver = Receiver()
     self.wirelessChannel = wireless_channel(0.1)
     self.numOfInputs = numOfInputs
     self.sigmaValues = [10, 1, 0.1]
     self.generated_Points = []
     self.colors = ['purple', 'yellow', 'orange']
Ejemplo n.º 6
0
 def test_upload_entry(self):
     tt = Transmitter()
     tt.set_account(self.account_with_good_password)
     filename = 'test_files/entry_test'
     entry = ElyxerEntry()
     entry.set_transmitter(tt)
     entry.load(filename)
     entry.set_title('WoooYAH!')
     tt.publish_entry(entry)
Ejemplo n.º 7
0
 def test_set_transmitter_exactly_once(self):
     tt = Transmitter()
     url = 'whee.com'
     username = '******'
     account = Account(url, username, None)
     tt.set_account(account)
     aa = ElyxerEntry()
     aa.set_transmitter(tt)
     self.assertRaises(TransmitterAlreadyExistsError,
                       lambda: aa.set_transmitter(tt))
Ejemplo n.º 8
0
 def test_publish_image(self):
     Image.set_abs_reference_dir_from_html_file(self.filename)
     account = AccountManager.get_default_account()
     tt = Transmitter()
     tt.set_account(account)
     image = Image("some <img src='Suzanne.jpg' /> string")
     before = image.get_remote_src()
     self.assertEqual(before, None)
     tt.publish_image(image)
     after = image.get_remote_src()
     self.assertNotEqual(after, None)
Ejemplo n.º 9
0
	def __init__(self, daemon = False):
		self.__loggingLock = Lock()
		self.__lock = RLock()
		self.__jails = Jails()
		self.__daemon = daemon
		self.__transm = Transmitter(self)
		self.__asyncServer = AsyncServer(self.__transm)
		self.__logLevel = None
		self.__logTarget = None
		# Set logging level
		self.setLogLevel(3)
		self.setLogTarget("STDOUT")
Ejemplo n.º 10
0
    def __init__(self):
        self.drive_msg = DriveMessage()
        self.check_msg = CheckMessage()
        self._bus = can.interface.Bus(bustype='socketcan', channel='can0')
        self.transmitter = Transmitter(self._bus)
        self.receiver = Receiver(self._bus, self.update)
        self.data = CarData()
        self.last_update = time.time()
        self.notifier = can.Notifier(self._bus, [self.receiver])
        self.controller = PIController(proportional=0.05, integral=0.1)

        gpsd.connect()

        self.send_messages()
Ejemplo n.º 11
0
	def __init__(self, midi_in, midi_out, loopback, modes):
		self.midi_in = midi_in
		self.led_control = Transmitter(midi_out)
		self.transmitter = Transmitter(loopback)

		self.active_mode = None
		self.active_bank = 0
		self.button_state = [False] * 12
		self.detune = 0
		self.octave = [0, 0]
		self.split_zone = 0

		self.black_key_indices = [
			1, 3, 6, 8, 10,
		]

		self.modes = modes
		for mode in self.modes:
			mode.register(self)

		# set initial mode on start
		self.set_mode(0)
		print('Ready!')
Ejemplo n.º 12
0
def main():

    if sys.argv[1] == 'leap_motion':
        motion_capturer = MotionCapturerLeapMotion()
    elif sys.argv[1] == 'mouse':
        motion_capturer = MotionCapturerMouse()
    elif sys.argv[1] == 'mix':
        motion_capturer = MotionCapturerLeapAndMouse()

    transmitter = Transmitter(sys.argv[2])

    while True:
        try:
            (pitch, roll, yaw, throttle) = motion_capturer.get_axis_values()
            transmitter.send_axis_values(pitch, roll, yaw, throttle)
        except ValueError:
            print('Ignoring frame')
        except KeyboardInterrupt:
            motion_capturer.shutdown()
Ejemplo n.º 13
0
    # Print option summary:
    print 'Parameters in experiment:'
    print '\tSamples per bit:', opt.spb
    print '\tChannel type:', ('Audio' if not opt.bypass else 'Bypass')
    if opt.bypass:
        print '\t  Noise:', opt.noise, ' lag:', opt.lag, 'h: [', opt.h, ']'
    print '\tFrequency:', fc, 'Hz'
    print '\tHamming code n :', opt.cc_len
########################################################

    #instantiate and run the source block
    src = Source(opt.monotone, opt.fname)
    src_payload, databits = src.process()  

    # instantiate and run the transmitter block
    xmitter = Transmitter(fc, opt.samplerate, opt.one, opt.spb, opt.silence, opt.cc_len)
    coded_bits = xmitter.encode(databits)
    coded_bits_with_preamble = xmitter.add_preamble(coded_bits)
    samples = xmitter.bits_to_samples(coded_bits_with_preamble)
    mod_samples = xmitter.modulate(samples)

####################################    
    # create channel instance
    if opt.bypass:
        h = [float(x) for x in opt.h.split(' ')]
        channel = bch.BypassChannel(opt.noise, opt.lag, h)
    else:
        channel = ach.AudioChannel(opt.samplerate, opt.chunksize, opt.prefill)
        
    # transmit the samples, and retrieve samples back from the channel
    try:
Ejemplo n.º 14
0
                )
        nodes.append(node)
        print(node)

    ################################################################################
    #Determine which node will be the transmitter for the simulation
    ################################################################################
    #boundary check the transmit node index
    tx_node = config['tx_node']
    if tx_node<1: #choose a random transmit node
        tx_node = random.randint(1,config['nodes'])
        print("Randomly Chose Node %d as the transmitter" % tx_node)
    tx_index=min(tx_node, config['nodes'])
    tx_index=max(tx_index, 1)
    tx_node = nodes[tx_index-1]
    transmitter = Transmitter(port=tx_node.phy_port)


    ################################################################################
    #Save all settings complied from defaults, test specific json and command line args as "last_run.json"
    ################################################################################
    with open("last_run.json", 'w') as f:
        json.dump(config, f, indent=2)
       
    ################################################################################
    #Write a spice file with the system setup
    ################################################################################
    with open("cable.p", 'w') as cable:
        cable.write("*lumped transmission line model with %d segments per meter at %d meters\n"\
        % (config['segments_per_meter'], config['length']))
        cable.write("*and a %f meter long cable\n" % config['length'])
Ejemplo n.º 15
0
from RgbLed import RgbLed
import serial
from time import sleep

from airbornedata import AirborneData
from transmitter import Transmitter

try:
    import struct
except ImportError:
    import ustruct as struct

# Data collection variables
sensor_name = "Construction Hallway"
sensor_id = 2
transmitter = Transmitter()
airborne_data_list = []
########################

# Setup LED
led = RgbLed(17, 27, 22)
########################

# Test LED
led.red()
sleep(.25)
led.green()
sleep(.25)
led.blue()
sleep(.25)
led.magenta()
Ejemplo n.º 16
0
from transmitter import Transmitter
from receiver import Receiver
import atexit

SEND_ADDRESS = "c"
RECEIVE_ADDRESS = "c"
MINIMUM_BLINK_TIME = 1000

if __name__ == '__main__':
	transmitter = Transmitter(minimum_blink_time = MINIMUM_BLINK_TIME, send_address = SEND_ADDRESS)
	receiver = Receiver(transmitter, minimum_blink_time = MINIMUM_BLINK_TIME, address = RECEIVE_ADDRESS)
	
	def cleanup():
		transmitter.cleanup()
		receiver.cleanup()
		GPIO.cleanup()

	atexit.register(cleanup)

	while True:
		message = input("message: ")
		transmitter.send(message)
Ejemplo n.º 17
0
    G_0 = np.array(
        [[(receivers[0].x - tran.x) / r1 - (receivers[1].x - tran.x) / r2,
          (receivers[0].y - tran.y) / r1 - (receivers[1].y - tran.y) / r2],
         [(receivers[0].x - tran.x) / r1 - (receivers[2].x - tran.x) / r3,
          (receivers[0].y - tran.y) / r1 - (receivers[2].y - tran.y) / r3]])

    Q_pinv = np.linalg.pinv(Q)

    crlb = np.linalg.pinv(G_0.transpose() @ Q_pinv @ G_0)

    return crlb


if __name__ == '__main__':
    transmitter = Transmitter([0, 0])

    crlbs = []

    for loc in range(5000, 1000, -100):
        receiver1 = Receiver([-loc, loc], is_center=True)
        receiver2 = Receiver([loc, loc], is_center=False)
        receiver3 = Receiver([loc, -loc], is_center=False)
        receivers = [receiver1, receiver2, receiver3]
        crlb = CRLB(receivers, transmitter)

        crlbs.append(np.sqrt(np.trace(crlb) / crlb.shape[0]))

    print(crlbs)
    plt.plot(crlbs)
    plt.show()
Ejemplo n.º 18
0
 def __init__(self):
     channel = "/dev/rfcomm8"
     self.TR = Transmitter(channel)
     self.TR
Ejemplo n.º 19
0
 def test_check_credentials_no_password(self):
     tt = Transmitter()
     tt.set_account(self.account_with_no_password)
     self.assertEquals(tt.check_credentials(), True) 
Ejemplo n.º 20
0
 def test_check_credentials_bad_password(self):
     tt = Transmitter()
     tt.set_account(self.account_with_bad_password)
     self.assertEquals(tt.check_credentials(), 'username/password error') 
Ejemplo n.º 21
0
murint7 = Wall(0.2, [(3, -1), (3, 1)], murint_materiau)

list_walls = [
    murext1, murext2, murext3, murext4, murext5, murext6, murext7, murext8,
    murext9, murext10, murint1, murint2, murint3, murint4, murint5, murint6,
    murint7
]

#
# creation de la pièce
#
room1 = Room()

room1.list_of_walls = list_walls

#
# ajout d'un emetteur dans la pièce
#
transmitter = Transmitter((5, 0), "lambda-demi")
room1.list_of_transmitters.append(transmitter)

#
# ajout de recepteurs couvrant toute la piece
# utiles au calcul de la puissance
#
list_of_receivers_creation(room1, 3, 3)

#
# fonction principale de l'algorithme de ray-tracing
#
room1.ray_and_power_distribution((0, 6), 2, "m")
Ejemplo n.º 22
0
 def __init__(self):
   self.message = bytes(0)
   self.transmitter = Transmitter(SERIAL)
   self.location = 'imgs/foto_nova.png'
Ejemplo n.º 23
0
def _send_code(code):
    pi = pigpio.pi()
    tx = Transmitter(pi, PIN)
    tx.send(code)
    time.sleep(1)
    tx.cancel()
Ejemplo n.º 24
0
 def __init__(self):
     self.transmitter = Transmitter()
     self.protocol_parser = ProtocolParser()
Ejemplo n.º 25
0
from collector import Ping
from transmitter import Transmitter

output_queue = None


def enqueue_output(data):
    """ Accepts a dictionary containg send_time and replies[] """
    output_queue.put(data)
    print("enqueued output")


def dequeue_output():
    """ Pops a dictionary from the output queue """
    return output_queue.get()


def collector_run():
    hosts = ('192.168.5.5', '192.168.5.18', '8.8.8.8', 'ucla.edu')
    pinger = Ping(hosts, enqueue_output)
    pinger.run()


if __name__ == '__main__':
    output_queue = queue.Queue()
    collector_thread = threading.Thread(target=collector_run, name="collector")
    recorder_url = 'ws://localhost:8765/'
    transmitter = Transmitter(dequeue_output, recorder_url)
    collector_thread.start()
    transmitter.start()
Ejemplo n.º 26
0
def runner():

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "process",
        help="select whether the module acts as (t)ransmitter or (r)eceiver")
    parser.add_argument("-d",
                        "--debug",
                        help="turn on extra logging level",
                        action="store_true")
    args = parser.parse_args()

    if args.debug:
        logging.basicConfig(
            stream=sys.stdout,
            filemode="a",
            format=
            "%(asctime)s - %(module)-12s - %(levelname)-8s - %(message)s",
            datefmt="%d-%m-%Y %H:%M:%S",
            level=logging.DEBUG)
        logging.debug("Logging level set to DEBUG")
    else:
        # filename="/share/log.txt"
        logging.basicConfig(
            stream=sys.stdout,
            filemode="a",
            format=
            "%(asctime)s - %(module)-12s - %(levelname)-8s - %(message)s",
            datefmt="%d-%m-%Y %H:%M:%S",
            level=logging.INFO)

    if args.process == 't' or args.process == 'T':
        role = Role.transmitter
        logging.debug("Module acting as transmitter")
    elif args.process == 'r' or args.process == 'R':
        role = Role.receiver
        logging.debug("Module acting as receiver")
    else:
        print("Cannot parse the argument, use either 't/T' or 'r/R'")
        sys.exit(-1)

    if role == Role.receiver:
        lora = Receiver(verbose=False)

        try:
            print(lora)
            lora.start()
        except KeyboardInterrupt:
            sys.stdout.flush()
            sys.stderr.write("KeyboardInterrupt\n")
        finally:
            lora.stop()
            sys.stdout.flush()
            logging.debug("Exiting the program")

    elif role == Role.transmitter:
        lora = Transmitter(verbose=False)
        print(lora)
        lora.start()
        logging.debug("Stopping transmitter.")
        lora.stop()
Ejemplo n.º 27
0
    logger.addHandler(fh)
logger.addHandler(ch)

logger.debug("Server running")
logger.debug("The arguments are: %s", sys.argv[1:])

# initialize ctype
dataReader = ctypes.CDLL('./dataReader.so')
dataReader.detect.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.c_double, ctypes.c_double, ctypes.c_int]
channel = 4
size = 10 * 20 * 1000
dataType = ((ctypes.c_double * size) * channel)

mainloop = GLib.MainLoop()

link = Transmitter(mainloop)


def sendData():
    dataSet = np.zeros((size, 4), dtype='double')
    dataSetC = dataSet.ctypes.data_as(ctypes.POINTER(ctypes.c_double))

    # sampling
    if dataReader.detect(dataSetC, ctypes.c_double(125), ctypes.c_double(125), ctypes.c_int(size)) == 1:
        print("Sampling success")

    # print(dataSet)
    #
    # exit()

    # a4=[]
Ejemplo n.º 28
0
from flask import Flask
from flask import render_template
from flask import redirect
from transmitter import Transmitter
from config import Config
app = Flask(__name__)
config = Config()
transmitter = Transmitter(config)


@app.route('/')
def index_pimator():
    return render_template('index.html',
                           codes=config.codes,
                           application_prefix=config.application_prefix)


@app.route('/outlet/<string:outlet>/<string:state>', methods=['POST'])
def apply_state_to_one_outlet(outlet, state):
    transmitter.apply_state_to_one_outlet(outlet, state)
    return redirect(config.application_prefix, code=302)


@app.route('/outlet/all/<string:state>', methods=['POST'])
def apply_state_to_all_outlets(state):
    transmitter.apply_state_to_all_outlets(state)
    return redirect(config.application_prefix, code=302)


# if __name__ == "__main__":
#     app.run(debug=True, host="0.0.0.0")
Ejemplo n.º 29
0
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from transmitter import Transmitter

# initialize GPIO
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)

# read data using pin 17
instance = dht11.DHT11(pin=17)

if __name__ == '__main__':
    channel = "/dev/rfcomm8"
    TR = Transmitter(channel)
    TR
    while True:
        result = instance.read()
        #print("waiting")
        if result.is_valid():
            date = "Last valid input: " + str(datetime.datetime.now())

            temp = "Temperature: %-3.1f C" % result.temperature
            humid = "Humidity: %-3.1f %%" % result.humidity
            TR.sendData(temp + "\n")
            TR.sendData(humid + "\n")
Ejemplo n.º 30
0
 def __init__(self):
     self.message = bytes(0)
     self.transmitter = Transmitter(SERIAL)