def initializeRadio():
    if testConfig:
        radio = Radio(FREQ_915MHZ, node_id, network_id, key, True, False)# use for pytest -> fails for production
        print("Radio Test Mode: set testConfig = False to enable hardware")
    else:
        radio = Radio(FREQ_915MHZ, node_id, network_id, encryptionKey=key, isHighPower=True, verbose=False) #use for production -> kwargs fails for pytest

    return radio
Example #2
0
 def __init__(self):
     self.radio = Radio(FREQ_915MHZ,
                        node_id,
                        network_id,
                        isHighPower=True,
                        verbose=True)
     self.command_type = 1
     self.r = 0
     self.b = 0
     self.g = 0
     self.ir = 0
Example #3
0
def test_receive():
    with Radio(FREQ_433MHZ, 1, 100, isHighPower=True, verbose=True) as radio:
        while True:
            for _ in radio.get_packets():
                assert True
                return True
            time.sleep(.1)
Example #4
0
def test_init_bad_spi_device():
    with pytest.raises(IOError) as _:
        Radio(FREQ_433MHZ, 1, spiDevice=-1)

# def test_encryption_key_set():
#     with Radio(FREQ_433MHZ, 1, encryptionKey="sampleEncryptKey") as radio:
#         assert radio._enc
Example #5
0
def main():
    with Radio(FREQ_915MHZ,
               THIS_NODE_ID,
               NETWORK_ID,
               isHighPower=False,
               verbose=False) as radio:
        print("node {} ready!!".format(THIS_NODE_ID))

        #set bitrate to 1.2kbps from library default of 55kbps
        # The minimum RSSI value that gets through goes down,
        # Demonstrating that it is more robust
        radio._writeReg(0x03, 0x68)
        radio._writeReg(0x04, 0x2B)

        # enable pre-amp on receiver, increasing sensitivty and range
        # to verfiy, place Tx and RX in non moving locations, and print RSSI
        # values with this used and without it. There should be a 2-4 dB
        # benefit from using the pre-amp
        # lowpowerlab.com/forum/rf-range-antennas-rfm69-library/rfm69hw-range-test!/
        # radio._writeReg(0x58, 0x2D)

        while True:
            ##print("termp is", radio.read_temperature())
            #regs = radio.read_registers()
            #for addr, data in regs:
            #   print( str(addr) + '\t' + str(data))
            # Every 10 seconds get packets
            # Process packets
            packets = radio.get_packets()
            if packets:
                # print("received a message!!!")
                for packet in packets:
                    print(packet.RSSI, bytes2floats(packet.data))
                # print("no packet received :(")

            # Every 5 seconds send a message


##            if tx_counter > 5:
##                tx_counter=0
##
##                # Send
##                print ("Sending")
##                if radio.send(2, "TEST", attempts=3, waitTime=100):
##                    print ("Acknowledgement received")
##                else:
##                    print ("No Acknowledgement")

#print("Listening...", len(radio.packets), radio.mode_name)
            delay = .05
            time.sleep(delay)
Example #6
0
class kite:
    def __init__(self):
        self.radio = Radio(FREQ_915MHZ,
                           node_id,
                           network_id,
                           isHighPower=True,
                           verbose=True)
        self.command_type = 1
        self.r = 0
        self.b = 0
        self.g = 0
        self.ir = 0

    def send(self, color1, color2):
        ct = self.command_type.to_bytes(1, byteorder='big')[0]
        r = color1.r.to_bytes(1, byteorder='big')[0]
        g = color1.g.to_bytes(1, byteorder='big')[0]
        b = color1.b.to_bytes(1, byteorder='big')[0]
        ir = self.ir.to_bytes(1, byteorder='big')[0]

        ba = list([ct, r, g, b, ir])
        print("Sending", ct, r, g, b, ir)
        self.radio.send(recipient_id, ba, attempts=3, waitTime=100)
Example #7
0
    def run(self):
        # just to make the library shutup about using pins already in use...
        import RPi.GPIO as GPIO
        GPIO.setwarnings(False)

        with Radio(FREQ_915MHZ,
                   THIS_NODE_ID,
                   NETWORK_ID,
                   isHighPower=False,
                   verbose=False) as radio:

            #set bitrate to 1.2kbps from library default of 55kbps
            # The minimum RSSI value that gets through goes down,
            # Demonstrating that it is more robust
            radio._writeReg(0x03, 0x68)
            radio._writeReg(0x04, 0x2B)

            # enable pre-amp on receiver, increasing sensitivty and range
            # to verfiy, place Tx and RX in non moving locations, and print RSSI
            # values with this used and without it. There should be a 2-4 dB
            # benefit from using the pre-amp
            # lowpowerlab.com/forum/rf-range-antennas-rfm69-library/rfm69hw-range-test!
            radio._writeReg(0x58, 0x2D)

            last_receive_time = time.time()
            is_connected = True
            logger.info("Trying to initiate connection to skiff...")
            while True:
                # print("RadioPoller is polling...")
                for packet in radio.get_packets():
                    if not is_connected:
                        logger.warning("Got a radio connection to skiff!")
                    is_connected = True
                    logger.debug("Got a radio packet with rssi={}".format(
                        packet.RSSI))
                    last_receive_time = time.time()
                    self.q.put(packet.data[:])
                    # print (packet.RSSI, bytes2floats(packet.data))
                if is_connected and (time.time() - last_receive_time >
                                     self.connection_timeout):
                    is_connected = False
                    logger.warning("Lost connection to skiff!")
                time.sleep(self.sleep_time)
Example #8
0
    def run(self):
        try:
            # Get our async loop object.
            self.loop = asyncio.get_event_loop()

            # Record station location estimate, based on our base station's IP address.
            self.record_location()

            # Initialize the radio as a resource, unless a radio was passed in (i.e. testing).
            self.logger.info('Radio initialization...')
            if self.radio is None:
                with Radio(
                        FREQ_915MHZ,
                        RADIO_BASE_NODE_ID,
                        RADIO_NETWORK_ID,
                        isHighPower=True,
                        encryptionKey=ENCRYPT_KEY,
                        power=
                        10,  # Send at 100% power, since we don't care about power saving on this end (we are wired in).
                        promiscuous=
                        False,  # We don't care about any messages except our weather station.
                        autoAcknowledge=
                        True,  # Station expects Acknowledgements.
                        verbose=False) as radio:
                    self.radio = radio
                    self.logger.info('Done.')
                    self.start_daemon()
            else:
                self.start_daemon()

        except KeyboardInterrupt:  # If CTRL+C is pressed, exit cleanly:
            self.logger.info('Keyboard interrupt.')
            self.stop_daemon()

        except Exception:
            self.logger.info('An error occured: {0}.', exc_info=1)
            self.stop_daemon()

        finally:
            self.shutdown()
Example #9
0
def run_radio():
    """
    Initialise radio and process radio packets
    """

    # Initialise the radio and start processing packets
    with Radio(FREQ_433MHZ,
               base_station_id,
               network_id,
               isHighPower=True,
               verbose=False,
               encryptionKey=encrypt_key) as radio:
        print("Starting radio loop")
        while True:

            # Process packets at each interval
            for packet in radio.get_packets():
                process_packet(packet, radio)

            # Periodically process packets
            delay = 0.05
            time.sleep(delay)
Example #10
0
GPIO.output(Power_LED_Pin_Number, Power_LED_STATE)  # Set pin Low

# Button Pin
# Button Pin - Used to pair the Home Station to the User's WIFI
WPS_BUTTON_Pin_Number = 7  # Enter pin
GPIO.setup(WPS_BUTTON_Pin_Number, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#GPIO.setup(WPS_BUTTON_Pin_Number, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Radio
node_id = 1
network_id = 100
recipient_id = 2
Radio_Power_Level = 90  # Between 0 - 100 (dB)
HomeRadio = Radio(FREQ_915MHZ,
                  node_id,
                  network_id,
                  isHighPower=True,
                  verbose=False)

# Main
TimeBetweenSystemCheck = 3600

#*******************************************#
#           Control Panel - End             #
#*******************************************#


#*******************************************#
#                   Begin                   #
#*******************************************#
# main.py will begin when system starts up using crontab
Example #11
0
node_id = 2
network_id = 100
recipient_id = 1


def led(state):
    if state == True:
        GPIO.output(pin, GPIO.HIGH)
    else:
        GPIO.output(pin, GPIO.LOW)
    return


with Radio(FREQ_915MHZ,
           node_id,
           network_id,
           isHighPower=True,
           promiscuousMode=True) as radio:
    print("Starting Loop...")

    rx_counter = 0
    tx_counter = 0

    while True:

        #Receive Packets
        if (radio.has_received_packet()):
            packet = radio.get_packets()
            if (len(packet[0].data) == 5):
                print("Packet Received")
                print(packet[0].data)
Example #12
0
from RFM69 import Radio, FREQ_915MHZ
import datetime
import time
import random

node_id = 1
network_id = 100
recipient_id = 2

with Radio(FREQ_915MHZ, node_id, network_id, isHighPower=True,
           verbose=True) as radio:
    print("Starting loop...")

    rx_counter = 0
    tx_counter = 6

    while True:

        # Every 5 seconds send a message
        if tx_counter > 5:
            tx_counter = 0

            r = random.randrange(255).to_bytes(1, byteorder='big')[0]
            g = random.randrange(255).to_bytes(1, byteorder='big')[0]
            b = random.randrange(255).to_bytes(1, byteorder='big')[0]

            ba = list([r, g, b])

            # Send
            print("Sending")
            if radio.send(2, ba, attempts=3, waitTime=100):
Example #13
0
            print("Sent packet to %s. Acked: %s" % (receiver, ret))
        except ValueError:
            print("Invalid RFM69 receiver: %s" % receiver_str)


def handle_stop_signals(signum, frame):
    global running
    print("Received signal %d." % signum)
    running = False


running = True
rx_buffer = deque(maxlen = 10)

with Radio(FREQ_433MHZ, conf.node_id, conf.network_id, isHighPower=True, power=conf.radio_power,
           interruptPin=conf.interrupt_pin, resetPin=conf.reset_pin, spiBus=conf.spi_bus, spiDevice=conf.spi_device,
           autoAcknowledge=False) as radio:
    signal.signal(signal.SIGINT, handle_stop_signals)
    signal.signal(signal.SIGTERM, handle_stop_signals)

    print("rfm69-mqtt-gateway starting..")
    print("Used configuration:")
    pprint(conf.__dict__)

    mqtt = MQTT(conf.mqtt_broker, conf.tx_subs_topic)

    while running:
        forward_from_radio_to_mqtt(radio, mqtt)
        forward_from_mqtt_to_radio(mqtt, radio)
        time.sleep(0.005)
Example #14
0
temp = -999.00  #default start values
lightLevel = -999

Humidity = -999

#default state JSON object avoids rare instance of this not being initialized yet (ie if initial data takes longer than 3 seconds )
JSONPayload = '{"state":{"desired":{"Light":' + str(
    lightLevel) + ', "Temperature":  ' + str(temp) + ', "Time": "' + str(
        -999) + '"}}}'

#initialize radio transceiver------------------------------------------------------------
#---------------------------------------------------------------------------------------
with Radio(FREQ_915MHZ,
           node_id,
           network_id,
           encryptionKey=key,
           isHighPower=True,
           verbose=False) as radio:
    clear()
    print("INITIALIZING RADIO TRANSCEIVER NETWORK:\n\n")
    time.sleep(0.5)

    while True:

        # Every 1 seconds check for packets----------------------------------
        if rx_counter >= 1:
            rx_counter = 0.0  #reset counter

            if radio.has_received_packet():
                #print("\n\nData Packet Received")
Example #15
0
def test_init_success():
    radio = Radio(FREQ_433MHZ, 1)
    assert type(radio) == Radio
Example #16
0
def test_init_bad_interupt():
    with pytest.raises(ValueError) as _:
        Radio(FREQ_433MHZ, 1, interruptPin=0)
Example #17
0
def test_init_bad_spi_bus():
    with pytest.raises(IOError) as _:
        Radio(FREQ_433MHZ, 1, spiBus=-1)
Example #18
0
#!/usr/bin/env python3

from RFM69 import Radio, FREQ_433MHZ
import datetime
import time

this_node_id = 1
network_id = 100
recipient_id = 2

with Radio(FREQ_433MHZ, this_node_id) as radio:
    print("Starting loop...")

    rx_counter = 0
    tx_counter = 0

    while True:

        # every 10 seconds, get packets
        if rx_counter > 10:
            rx_counter = 0
            for packet in radio.get_packets():
                print(packet)

        # every 5 seconds, send a message
        if tx_counter > 5:
            tx_counter = 0
            print("Sending...")
            if radio.send(2, "TEST", attempts=3, waitTime=100):
                print("Acknowledgement received")
            else:
Example #19
0
    sensor_id = "sensor{}".format(packet.sender)

    for key, value in dict(volume=packet.data[0],
                           battery=packet.data[1],
                           RSSI=packet.RSSI).items():

        if not save_reading(sensor_id, key, ts, value):
            if create_sensor(sensor_id):
                create_channel(sensor_id, key)
            else:
                print("Failed to create sensor")


print("Starting 123")
with Radio(FREQ_433MHZ, 1, isHighPower=True, power=100, verbose=True) as radio:

    print("Starting loop")
    while True:

        print("loop")

        while not radio.has_received_packet():
            # radio.broadcast('advert')
            # print("Advert Send")
            time.sleep(.2)

        for packet in radio.get_packets():
            print("Packet received", packet.to_dict())
            process_packet(packet)
Example #20
0

async def send(radio, to, message):
    print("Sending")
    if radio.send(to, message, attempts=3, waitTime=100):
        print("Acknowledgement received")
    else:
        print("No Acknowledgement")


async def pinger(radio):
    print("Pinger")
    counter = 0
    while True:
        await send(radio, 2, "ping {}".format(counter))
        counter += 1
        await asyncio.sleep(5)


loop = asyncio.get_event_loop()
node_id = 1
network_id = 100
with Radio(FREQ_433MHZ, node_id, network_id, isHighPower=True,
           verbose=False) as radio:
    print("Started radio")
    loop.create_task(receiver(radio))
    loop.create_task(pinger(radio))
    loop.run_forever()

loop.close()
Example #21
0
def test_transmit():
    with Radio(FREQ_433MHZ, 1, 100, isHighPower=True, verbose=True) as radio:
        success = radio.send(2, "Banana", attempts=5, waitTime=100)
        assert success == True
Example #22
0
def test_init_bad_reset():
    with pytest.raises(ValueError) as _:
        Radio(FREQ_433MHZ, 1, resetPin=0)