Example #1
0
    def __init__(self, teamID, UDP=False, dilationFactor=1, networkSize=4):
        self.teamID = teamID
        self.nextPlayer = False
        self.waitingControl = True
        self.finishedCounter = 0

        self.networkSize = networkSize
        self.dilationFactor = dilationFactor
        self.tData = (0.005*3 + 0.005)*self.dilationFactor
        self.tACK = 0.04*self.dilationFactor

        self.savingFiles = [0]*self.networkSize
        self.senderFiles = [0]*self.networkSize
        for i in range(self.networkSize):
            if i != self.teamID:
                savingFilePath = os.path.join("./savingFiles" + str(self.teamID), "team" + str(i), "received_file.txt")
                self.savingFiles[i] = FileClass(reader=False, path=savingFilePath)
                senderFolder = os.path.join("./sendFiles" + str(self.teamID), "team" + str(i))
                senderFilePath = os.path.join(senderFolder, os.listdir(senderFolder)[0])
                self.senderFiles[i] = FileClass(reader=True, path=senderFilePath)

        self.pipeRX = [0xe7, 0xe7, 0xe7, 0xe7, 0xe7]
        self.pipeTX = [0xe7, 0xe7, 0xe7, 0xe7, 0xe7]

        pinTX = 22
        pinValTx = 0
        pinRX = 23
        pinValRx = 1

        # pinTX = 27
        # pinRX = 17

        self.radioTX = radio.Radio(self.pipeTX, rx=False, pins=[pinValTx, pinTX], teamID=self.teamID, UDP=UDP)
        self.radioRX = radio.Radio(self.pipeRX, rx=True, pins=[pinValRx, pinRX], teamID=self.teamID, UDP=UDP)
Example #2
0
    def __init__(self, id, eui64=None):

        # store params
        self.id = id

        # admin
        self.dataLock = threading.RLock()

        # singletons (quicker access, instead of recreating every time)
        self.log = SimEngine.SimLog.SimLog().log
        self.engine = SimEngine.SimEngine.SimEngine()
        self.settings = SimEngine.SimSettings.SimSettings()

        # stack state
        self.dagRoot = False
        self._init_eui64(eui64)
        self.ipv6_prefix = None

        # stack
        self.app = app.App(self)
        self.secjoin = secjoin.SecJoin(self)
        self.rpl = rpl.Rpl(self)
        self.sixlowpan = sixlowpan.Sixlowpan(self)
        self.trae = trae.TRAE(self)
        self.sf = sf.SchedulingFunction(self)
        self.sixp = sixp.SixP(self)
        self.tsch = tsch.Tsch(self)
        self.radio = radio.Radio(self)
        self.batt = batt.Batt(self)
Example #3
0
    def test_send_packet_with_eventual_success(self, encrypt_mock):
        expected_packet = [39, 0, 5, 4, 1, 2, 3, 4]
        expected_packet = bytes(expected_packet)
        encrypted_packet = bytes([8] * 32)
        radio_instance = radio.Radio()
        radio_instance.clients = [{
            'client_id': 1,
            'address': MOCK_CLIENT_ADDRESS,
            'server_counter': 10000
        }]
        radio_instance.nrf24.openReadingPipe.reset_mock()
        radio_instance.nrf24.openWritingPipe.reset_mock()
        radio_instance.nrf24.startListening.reset_mock()
        radio_instance.nrf24.write.side_effect = [False, False, True]
        encrypt_mock.return_value = encrypted_packet

        success = radio_instance.send_packet(1, 5, bytes([1, 2, 3, 4]))

        self.assertEqual(len(encrypt_mock.call_args[0][0]), 32)
        self.assertEqual(encrypt_mock.call_args[0][0][:len(expected_packet)],
                         expected_packet)
        self.assertEqual(encrypt_mock.call_args[0][0][-1], 16)
        radio_instance.nrf24.stopListening.assert_called_once_with()
        radio_instance.nrf24.openWritingPipe.assert_called_once_with(
            MOCK_CLIENT_ADDRESS)
        self.assertEqual(radio_instance.nrf24.write.call_count, 3)
        radio_instance.nrf24.startListening.assert_called_once()

        self.assertEqual(success, True)
Example #4
0
 def __init__(self, msgHandler, errHandler, lot, tid, address=None):
     self.messageHandler = msgHandler
     self.errorHandler = errHandler
     self.lot = lot
     self.tid = tid
     self.address = address
     self.pdmMessage = None
     self.radio = radio.Radio(0)
Example #5
0
 def __init__(self, puerto):
     self.nomApp = "InterfaceRadioArduino->"
     self.radio = radio.Radio()
     self.arduino = arduinoComunication.ArduinoComunication(self, puerto)
     #Cambiando esta variable a true, se deja de comunicar con arduino
     self.stop = false
     #Recoge la opcion enviada por arduino, por defecto es cero (vacio)
     self.opcion = 0
     print("InterfaceRadioArduino")
Example #6
0
    def test_get_client_id_with_existing_client_address(self):
        radio_instance = radio.Radio()
        expected_client_id = random.randint(1, 255)

        radio_instance.clients.append({
            'client_id': expected_client_id,
            'address': MOCK_CLIENT_ADDRESS
        })

        self.assertEqual(radio_instance.get_client_id(MOCK_CLIENT_ADDRESS),
                         expected_client_id)
Example #7
0
    def test_get_client_id_with_new_client_address(self):
        radio_instance = radio.Radio()
        number_already_registered = random.randint(0, 255)

        for i in range(number_already_registered):
            radio_instance.clients.append({
                'client_id': i + 1,
                'address': OTHER_MOCK_CLIENT_ADDRESS
            })

        self.assertEqual(radio_instance.get_client_id(MOCK_CLIENT_ADDRESS),
                         number_already_registered + 1)
Example #8
0
    def test_get_client_address_without_remaining_client_ids(self):
        radio_instance = radio.Radio()
        number_already_registered = 254

        for i in range(number_already_registered):
            radio_instance.clients.append({
                'client_id': i + 1,
                'address': OTHER_MOCK_CLIENT_ADDRESS
            })

        self.assertEqual(radio_instance.get_client_id(MOCK_CLIENT_ADDRESS),
                         False)
Example #9
0
    def test_send_packet_with_error(self):
        radio_instance = radio.Radio()
        radio_instance.clients = [{
            'client_id': 1,
            'address': MOCK_CLIENT_ADDRESS,
            'server_counter': 10000
        }]
        radio_instance.nrf24.write.return_value = False

        success = radio_instance.send_packet(1, 5, bytes([1, 2, 3, 4]))

        self.assertEqual(success, False)
        self.assertEqual(radio_instance.nrf24.write.call_count, 10)
Example #10
0
 def testradioIC910(self):
     ic910 = radio.Radio("IC910", "Sub", "CW")
     ic910.connect("/dev/ttyUSB0")
     #print ic910.getfreq()
     #ic910.getmode()
     ic910.changefreq(437.38590)
     #print "Sub FM"
     #ic910.chengemode("Sub","FM")
     print "Sub CW"
     ic910.changemode("Sub", "FM")
     #print "Main FM"
     #ic910.chengemode("Main","FM")
     #print "Main CW"
     #ic910.chengemode("Main","CW")
     ic910.close()
Example #11
0
 def test_has_client_id(self):
     client_id = 100
     test_cases = [
         ([{
             'client_id': 100
         }], True),
         ([{
             'client_id': 101
         }], False),
         ([], False),
     ]
     radio_instance = radio.Radio()
     for clients, expected in test_cases:
         with self.subTest(clients=clients, expected=expected):
             radio_instance.clients = clients
             self.assertEqual(radio_instance.has_client_id(client_id),
                              expected)
Example #12
0
 def __init__(self,
              pktHandler,
              msgHandler,
              errHandler,
              lot=None,
              tid=None,
              address=None):
     self.pktHandler = pktHandler
     self.messageHandler = msgHandler
     self.errHandler = errHandler
     self.lot = lot
     self.tid = tid
     self.address = address
     self.nextPacketSequence = None
     self.packetSequences = dict()
     self.address = None
     self.message = None
     self.radio = radio.Radio(0)
Example #13
0
 def setup_for_test_get_packet(self):
     radio_instance = radio.Radio()
     radio_instance.nrf24.available.return_value = True
     radio_instance.has_client_id = Mock(return_value=True)
     radio_instance.is_counter_is_in_expected_range = Mock(
         return_value=True)
     client_id = 100
     message_id = 101
     payload = [1, 2, 3, 4]
     counter_byte_1 = 16
     counter_byte_2 = 39
     decrypted_packet = [
         counter_byte_2, client_id, message_id,
         len(payload)
     ]
     decrypted_packet.extend(payload)
     decrypted_packet.extend([counter_byte_1])
     radio.decrypt_packet.return_value = bytes(decrypted_packet)
     return radio_instance
Example #14
0
def radio(action, id):
    listen = program.Radio(id)
    if action == "on":
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(24, GPIO.OUT)
        GPIO.output(24, GPIO.HIGH)
        listen.start()
        return ("Radio Started: " + id)

    if action == "off":
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(24, GPIO.OUT)
        GPIO.output(24, GPIO.LOW)
        listen.stop()
        return ("Radio off")

    if action == "status":
        res = listen.status()
        return (res)
Example #15
0
    def __init__(self, iface_name):
        self._radio = radio.Radio(iface_name)
        self.iface_name = iface_name
        self._up_state_pub = netlink_monitor.get_state_publisher(
            iface_name, IFSTATE.UP)
        self.activate_request = state_publisher.StatePublisher(False)
        self.is_active = state_publisher.StatePublisher(False)
        self.scanning_enabled = state_publisher.StatePublisher(False)
        self.associate_request = event.Event()
        self.disactivate_delay = 1
        self.pre_up_sleep = 1

        # Copy radio members that we are willing to expose
        self.unassociate = self._radio.unassociate
        self.associated = self._radio.associated
        self.scanning = self._radio.scanning
        self.scan = self._radio.scan
        self.scan_results_event = self._radio.scan_results_event
        self.frequency_list = self._radio.frequency_list
Example #16
0
 def __init__(self, logger):
     self.logger = logger
     self.queue = queue.Queue()
     self.radio = radio.Radio(self.logger)
     self.device = device.Device(self.logger, self.radio)
     self.scheduler = Scheduler(self.logger, asyncio.new_event_loop(), self)
     self.schedulerthread = threading.Thread(target=self.scheduler.run,
                                             name='scheduler',
                                             daemon=True)
     self.api = api.API(asyncio.new_event_loop(), self.queue, self.logger,
                        os.environ.get('TOKEN'))
     self.apithread = threading.Thread(target=self.api.run,
                                       name='api',
                                       daemon=True)
     self.mode = 1
     self.nightmode = 0
     self.temp = 0
     self.press = 0
     self.humid = 0
     self.etemp = 0
Example #17
0
    def __init__(self, id, eui64=None):

        # store params
        self.id                        = id

        # admin
        self.dataLock                  = threading.RLock()

        # singletons (quicker access, instead of recreating every time)
        self.log                       = SimEngine.SimLog.SimLog().log
        self.engine                    = SimEngine.SimEngine.SimEngine()
        self.settings                  = SimEngine.SimSettings.SimSettings()

        # stack state
        self.dagRoot                   = False
        self._init_eui64(eui64)
        self.ipv6_prefix               = None

        # stack
        self.app                       = app.App(self)
        self.secjoin                   = secjoin.SecJoin(self)
        self.rpl                       = rpl.Rpl(self)
        self.sixlowpan                 = sixlowpan.Sixlowpan(self)
        self.sf                        = sf.SchedulingFunction(self)
        self.sixp                      = sixp.SixP(self)
        self.tsch                      = tsch.Tsch(self)
        self.radio                     = radio.Radio(self)
        self.batt                      = batt.Batt(self)

        # :) Low Delay Scheduling Function - Virtual Slot Frame proportional to CBR of the node.

        self.flow_gen_time             = -1  # offset of subframe of flow of data
        self.hops                      = -1  # initialize hops
        self.lock_TX                   =  0  # locking TX before Scheduling
        self.start_tx                  = -1
        self.tx_slot                   = -1
        self.lock_schedule             =  0
        self.is_leaf                   =  1  # 1 - is leaf, 0- is relay node
        self.flip_flop                 =  0  # enable more childrens for DagRoot mote

        self.black_parent                 = [] #mac  address
Example #18
0
    def __init__(self, id, eui64=None):

        # store params
        self.id = id

        # admin
        self.dataLock = threading.RLock()

        # singletons (quicker access, instead of recreating every time)
        self.log = SimEngine.SimLog.SimLog().log
        self.engine = SimEngine.SimEngine.SimEngine()
        self.settings = SimEngine.SimSettings.SimSettings()

        # stack state
        self.dagRoot = False
        self._init_eui64(eui64)
        self.ipv6_prefix = None

        # stack
        self.app = app.App(self)
        self.secjoin = secjoin.SecJoin(self)
        self.rpl = rpl.Rpl(self)
        self.sixlowpan = sixlowpan.Sixlowpan(self)
        self.sf = sf.SchedulingFunction(self)
        self.sixp = sixp.SixP(self)
        self.tsch = tsch.Tsch(self)
        self.radio = radio.Radio(self)
        self.batt = batt.Batt(self)

        # :) energy save
        self.lock_schedule = 0

        # Generation of periodic traffic

        delay = self.settings.tsch_slotDuration + (self.settings.app_pkPeriod *
                                                   random.random())
        gen_timeslot = int(((self.engine.getAsn() + delay / 0.01) %
                            self.settings.tsch_slotframeLength - 1))
        print "~#ID", self.id, "Gen Timeslot", gen_timeslot

        self.gen_timeslot = gen_timeslot
Example #19
0
    def build(self):
        self.root = SampleWidget()
        self.root.buttonOperation.bind(on_press=self.buttonOperation_clicked)
        Clock.schedule_interval(self.callback_operation, 1)
        self.root.spinfreqmode.bind(text=self.spinchanged)

        self.conf = config.ConfigRead().read()
        self.gslat = self.conf['lat']
        self.gslon = self.conf['lon']
        self.gsantenna = self.conf['antenna']
        self.gsheight = self.conf['height']
        self.gsradio = self.conf['radio']
        self.gsradioport = self.conf['radioport']
        self.gsradiobaudrate = self.conf['radiobaudrate']
        self.gsantennaport = self.conf['antennaport']
        self.gsantennabaudrate = self.conf['antennabaudrate']
        self.ant = antenna.Antenna(self.gsantenna)
        self.ant.connect(self.gsantennaport)
        self.ic910 = radio.Radio(self.gsradio, "Sub", "CW")
        self.ic910.connect(self.gsradioport)
        return self.root
Example #20
0
 def test_init(self):
     logging.basicConfig(level=logging.INFO)
     radio_instance = radio.Radio()
     radio_instance.nrf24.begin.assert_called_once_with(0, 0, 25, 24)
     radio_instance.nrf24.setRetries.assert_called_once_with(10, 10)
     radio_instance.nrf24.setPayloadSize.assert_called_once_with(32)
     radio_instance.nrf24.setChannel.assert_called_once_with(0x4c)
     radio_instance.nrf24.setDataRate.assert_called_once_with(
         MockNRF24.BR_250KBPS)
     radio_instance.nrf24.setPALevel.assert_called_once_with(
         MockNRF24.PA_HIGH)
     radio_instance.nrf24.setCRCLength.assert_called_once_with(
         MockNRF24.CRC_16)
     radio_instance.nrf24.setAutoAck.assert_called_once_with(True)
     radio_instance.nrf24.enableAckPayload.assert_called_once_with()
     radio_instance.nrf24.openReadingPipe.assert_called_once_with(
         1, MOCK_SERVER_ADDRESS)
     radio_instance.nrf24.openWritingPipe.assert_called_once_with(
         MOCK_SERVER_ADDRESS)
     radio_instance.nrf24.startListening.assert_called_once_with()
     radio_instance.nrf24.printDetails.assert_called_once_with()
Example #21
0
    def test_is_counter_in_expected_range(self):
        client_id = 100
        current_client_counter = 65533
        test_cases = [
            (100, False),
            (65533, False),
            (65534, True),
            (65535, True),
            (0, True),
            (7, True),
            (8, False),
            (10, False),
        ]

        radio_instance = radio.Radio()
        radio_instance.clients.append({
            'client_id': client_id,
            'client_counter': current_client_counter
        })
        for counter, expected in test_cases:
            with self.subTest(counter=counter, expected=expected):
                self.assertEqual(
                    radio_instance.is_counter_is_in_expected_range(
                        client_id, counter), expected)
Example #22
0
 def test_init_with_higher_loglevel(self):
     logging.basicConfig(level=logging.WARN)
     radio_instance = radio.Radio()
     self.assertFalse(radio_instance.nrf24.printDetails.called)
Example #23
0
    parser.add_argument("--wampl", default=0.3, type=float)
    return parser.parse_args()


def do_alarm(runvar, duration):
    time.sleep(duration)
    print("whee!")
    runvar.value = False


if __name__ == '__main__':
    args = parse_args()

    runvar = mp.Value('b', True)
    proc = mp.Process(target=do_alarm, args=(runvar, args.duration))
    proc.start()

    endtime = time.time() + args.duration
    rad = radio.Radio()
    rad.tune(args.freq, args.gain)

    nsamps = 10000 * int(np.floor(args.rate / args.wfreq))
    vals = np.ones((1, nsamps), dtype=np.complex64) * np.arange(nsamps)
    samps = args.wampl * np.exp(vals * 2j * np.pi * args.wfreq / args.rate)

    while runvar.value:
        for i in range(10):
            rad.send_samples(samps)

    proc.join()
Example #24
0
    "domaincontroller":
    None,  # None: domain_controller.WsgiDAVDomainController(user_mapping)
})
wsgidav = WsgiDAVApp(config)


def wsgidav_application(environ, start_response):
    return wsgidav(environ, start_response)


class Services:
    pass


services = Services()
services.radio = radio.Radio(irlp_home)
services.player = playback.Player(services.radio)
services.scheduler = scheduler.Scheduler(services.player, services.radio)


# Put all top level module instances here that need to get stuff done
def top_ticker():
    services.radio.tick()
    services.player.tick()
    services.scheduler.tick()


root = static.Data("", "text/plain")
root.putChild("files", static.File("../files"))
root.putChild("static", static.File("../static"))
#simple = Simple()
Example #25
0
        to = str(to)
        mid = str(mid)
        wh = str(which)
        hm = str(howmany)
        ttl = str(ttl)
        prefix = to + mid + wh + hm + ttl
        message = bytes(prefix, 'utf-8') + mslice + bytes('\n', 'utf-8')
        print(message.decode('utf-8'))
        assert len(message) <= 64
        return message


def run(server_class=HTTPServer, handler_class=S, port=config.PORT):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print("Starting httpd...")
    httpd.serve_forever()


if __name__ == "__main__":
    from sys import argv
    # init radio, start thread that handles incoming packets from radio
    radio = radio.Radio(config.SERIALPORT, config.BAUD)
    listener_thread = Thread(target=listener.listen_forever, args=(radio, ))
    listener_thread.start()

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
Example #26
0
import busio
import adafruit_character_lcd.character_lcd_rgb_i2c as character_lcd

from threading import Barrier
import radio 
import phatbeat
import subprocess

import socket
import threading 

i2c = busio.I2C(board.SCL, board.SDA)
lcd = character_lcd.Character_LCD_RGB_I2C(i2c, 16, 2)

global radio
radio = radio.Radio(lcd)
radio.play()

os.system("ping -c 1 google.com")
time.sleep(5)

def lcd_buttonthread():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    while True:
        if lcd.select_button:
            try:
                s.connect(('10.255.255.255', 1))
                IP = s.getsockname()[0]
            except:
                IP = '127.0.0.1'
Example #27
0
import radio
import parlante
import os
marca_zapatera=os.sys.argv[1]
zapato_marca=os.sys.argv[2]
zap1=parlante.Parlante(zapato_marca,42,"cuero","deportivo",1200)
z1=radio.Radio(marca_zapatera,zap1,"madera",20,"americano")
print("radio:"+z1.getMarca())
print("parlante:"+zap1.getMarca())
z1.setParlante(zap1)
print(z1.reproducir())
Example #28
0
#!/usr/bin/python3

from flask import Flask, render_template, request
import radio as r
import threading, os

while (True):  #wait for internet
    if (os.system("ping -c 1 google.com") == 0):
        break

rad = r.Radio()
rad.start()

web = Flask(__name__)


@web.route("/", methods=["POST", "GET"])
def home():
    if (request.method == "POST"):
        tmp = int(request.form["state"])
        if (tmp == -1):
            rad.Play(-1)
            print("Previous")
        elif (tmp == 0):
            rad.pause()
            print("Pause")
        elif (tmp == 1):
            rad.Play(1)
            print("Next")

    return render_template("radio.html", playing=rad.cPlay, volume=rad.volume)
Example #29
0
import radio
import SimpleEncoder
import machine
from machine import Pin
import lcd_api
import i2c_lcd
import bounce
import time
import si5351

synth = si5351.SI5351( data=Pin(21), clock=Pin(22) )

lcd = i2c_lcd.I2cLcd( data=Pin(21), clock=Pin(22), num_lines=2, num_columns=16 )
button = bounce.Bounce( Pin(15, mode=Pin.IN, pull=Pin.PULL_UP))
enc = SimpleEncoder.Encoder( 26, 27 )
r = radio.Radio( button, enc, lcd, synth, 7010000 )
r.run()