#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Example program to receive packets from the radio link
#

import time
from nrf24 import NRF24
import RPi.GPIO as GPIO
import spidev
GPIO.setmode(GPIO.BCM)

pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]

radio2 = NRF24(GPIO, spidev.SpiDev())
radio2.begin(0, 17)

radio2.setRetries(15, 15)

radio2.setPayloadSize(32)
radio2.setChannel(0x60)
radio2.setDataRate(NRF24.BR_2MBPS)
radio2.setPALevel(NRF24.PA_MIN)

radio2.setAutoAck(True)
radio2.enableDynamicPayloads()
radio2.enableAckPayload()

radio2.openWritingPipe(pipes[0])
radio2.openReadingPipe(1, pipes[1])
Esempio n. 2
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from nrf24 import NRF24
import time

pipes = [[0x34, 0x43, 0x10, 0x10, 0x01], [0x34, 0x43, 0x10, 0x10, 0x01]]

radio = NRF24()
radio.begin(0, 0, 22, 18)  #Set CE and IRQ pins

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.setRetries(15, 15)
radio.setPayloadSize(32)
radio.setChannel(0x28)

radio.setDataRate(NRF24.BR_2MBPS)
radio.setPALevel(NRF24.PA_MAX)

radio.openWritingPipe(pipes[1])
radio.openReadingPipe(0, pipes[0])

#radio.startListening()
#radio.stopListening()

radio.printDetails()

while True:
Esempio n. 3
0
import virtGPIO as GPIO
from nrf24 import NRF24
import time

pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]

# Comment re multiple SPIDEV devices:
# Official spidev documentation is sketchy. Implementation in virtGPIO allows multiple SpiDev() objects.
# This may not work on RPi? Probably RPi uses alternating open() / xfer2() /close() within one SpiDev() object???
# On virtGPIO each of multiple SpiDev() stores its own mode and cePin. Multiple RF24 used here becomes easy.
# This issue affects only using MULTIPLE Spi devices.

##################################################################
# SET UP RADIO1 - PTX

radio1 = NRF24(GPIO, GPIO.SpiDev())
radio1.begin(9)  # SPI-CE=RF24-CSN=pin9, no RF24-CE pin
time.sleep(1)
radio1.setRetries(15, 15)
radio1.setPayloadSize(32)
radio1.setChannel(0x62)
radio1.setDataRate(NRF24.BR_2MBPS)
radio1.setPALevel(NRF24.PA_MIN)
radio1.setAutoAck(True)
radio1.enableDynamicPayloads()
radio1.enableAckPayload()

radio1.openWritingPipe(pipes[1])
radio1.openReadingPipe(1, pipes[0])

if not radio1.isPVariant():
Esempio n. 4
0
#
# Example program to send packets to the radio
#
# João Paulo Barraca <*****@*****.**>
#

from nrf24 import NRF24
import time

pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]

radio = NRF24.NRF24()
radio.begin(1, 0, "P9_15", "P9_16")  #Set CE and IRQ pins
radio.setRetries(15, 15)
radio.setPayloadSize(8)
radio.setChannel(0x60)

radio.setDataRate(NRF24.NRF24.BR_250KBPS)
radio.setPALevel(NRF24.NRF24.PA_MAX)

radio.openWritingPipe(pipes[1])
radio.openReadingPipe(1, pipes[0])

radio.startListening()
radio.stopListening()

radio.printDetails()

buf = ['P', 'I', 'N', 'G']
while True:
    radio.write(buf)
Esempio n. 5
0
# RADIO CONFIGURATION
NAMES = {
    32: 'Student 1',
    33: 'Student 2'
}  # Device ID Alias for teacher interface

devices = [32, 33]

pipes = {
    32: [0xc2, 0xc2, 0xc2, 0xc2, 0xc2],
    33: [0xe7, 0xe7, 0xe7, 0xe7, 0xe7]
}

answers = []

r = NRF24()
rf_lock = threading.Lock()  # Regulates access to RF Radio
CLASS_ID = 0x00
device_id = 32
polling = False


@app.route('/')
def index():
    return flask.render_template('index.html')


@app.route('/question_start')
def start_question():
    poll_thread = threading.Thread(target=poll_student)
    poll_thread.start()
Esempio n. 6
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Example program to send packets to the radio link
#

import virtGPIO as GPIO
from nrf24 import NRF24
import time

pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]

radio = NRF24(GPIO, GPIO.SpiDev())
radio.begin(10, 8)  # Set spi-ce pin10, and rf24-CE pin 8
time.sleep(1)
radio.setRetries(15, 15)
radio.setPayloadSize(32)
radio.setChannel(0x60)

radio.setDataRate(NRF24.BR_2MBPS)
radio.setPALevel(NRF24.PA_MIN)
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[1])
radio.openReadingPipe(1, pipes[0])
radio.printDetails()

c = 1
while True:
Esempio n. 7
0
def main(argv):
   print '##################################################################'
   print '#                         NRF24 gateway                          #'
   print '##################################################################'


   # Wait while internet appear
   import urllib2 
   loop_value = 1
   while (loop_value < 10):
      try:
           urllib2.urlopen("http://google.com")
      except:
           print( "Network: currently down." )
           time.sleep( 10 )
           loop_value = loop_value + 1
      else:
           print( "Network: Up and running." )
           loop_value = 10


   pipes = [[0xf0, 0xf0, 0xf0, 0xf0, 0xd2], [0xf0, 0xf0, 0xf0, 0xf0, 0xe1]]
   configFileName = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
   debugMode = 0

   try:
      opts, args = getopt.getopt(argv,"hd:f:",["debug=","configFile="])
   except getopt.GetoptError:
      print 'smart_gateway.py -d <debugMode:0/1>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'Example for call it in debug mode: smart_gateway.py -d 1 -f config.json'
         sys.exit()
      elif opt in ("-d", "--debug"):
         debugMode = arg
      elif opt in ("-f", "--configFile"):
         configFileName = arg

   print 'Start Parameters:'
   print '       debugMode:', debugMode
   print '  configFileName:', configFileName 

   json_data=open(configFileName)
   config_data = json.load(json_data)
   json_data.close()

   print '      Server URL:', config_data["Server"]["url"]
   print '      Company ID:', config_data["Server"]["id"]
   print '      Gateway ID:', config_data["Server"]["Deviceid"]
   print '     Service Bus:', config_data["Servicebus"]["namespace"]

   print ''
   nowPI = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")

   href = config_data["Server"]["url"] + 'API/Device/GetServerDateTime'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ':' + token
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Authentication': authentication}
   #r = requests.get(href, headers=headers, verify=False)
   r = requests.get(href, headers=headers)
   if r.status_code == 200:
       nowPI = r.json()
       print ("Setting up time to: " + nowPI)
       os.popen('sudo -S date -s "' + nowPI + '"', 'w').write("123")
   else:
       print 'Error in setting time. Server response code: %i' % r.status_code
	   
   href = config_data["Server"]["url"] + 'api/Device/DeviceConfigurationUpdate'
   token = config_data["Server"]["key"]
   authentication = config_data["Server"]["id"] + ":" + token


   if debugMode==1: print(authentication)
   headers = {'Content-Type': 'application/json; charset=utf-8', 'Accept': 'application/json', 'Timestamp': nowPI, 'Authentication': authentication}
    
   deviceDetail = {}
   deviceDetail["DeviceIdentifier"] = config_data["Server"]["Deviceid"]
   deviceDetail["DeviceType"] = "Custom"
   deviceDetail["DeviceConfigurations"] = [{'Key':'IPPrivate','Value':[(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]},
                                           {'Key':'IPPublic','Value': requests.get('http://icanhazip.com/').text},
                                           {'Key': 'Configuration', 'Value': json.dumps(config_data) },
                                           {'Key':'MAC','Value': ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2))}
                                          ]

   payload = {'Device': deviceDetail}
   if debugMode == 1: print 'Request Content: {0}'.format(json.dumps(payload))
   #r = requests.post(href, headers=headers, data=json.dumps(payload), verify=False)
   r = requests.post(href, headers=headers, data=json.dumps(payload))


   if r.status_code == 200:
      if debugMode == 1: print 'Configuration Response Content: {0}'.format(r.content)
      data = json.loads(r.text)    
      for entry in data['Device']['DeviceConfigurations']:
          if entry['Key'] == 'Configuration':     
             with open(configFileName, 'w') as outfile:
                json.dump(json.loads(entry['Value']), outfile)
      print 'Device configuration Successfully updated'
   else:
      print 'Error in Device configuration update. Server response code: {0} {1}'.format(r.status_code, r.content)

   
   queue_name = 'custom_' + config_data["Server"]["id"] + '_' + config_data["Server"]["Deviceid"]
   bus_service = ServiceBusService( service_namespace=config_data["Servicebus"]["namespace"], 
                                    shared_access_key_name=config_data["Servicebus"]["shared_access_key_name"], 
                                    shared_access_key_value=config_data["Servicebus"]["shared_access_key_value"])
   try:
      bus_service.receive_queue_message(queue_name, peek_lock=True)
      print '  Succesfully connected to queue'
      print '  Actuator queue: ' + queue_name
   except:
      queue_options = Queue()
      queue_options.max_size_in_megabytes = '1024'
      queue_options.default_message_time_to_live = 'PT15M'
      bus_service.create_queue(queue_name, queue_options)
      print '  Succesfully created queue'
      print '  Actuator queue: ' + queue_name + ' (Created)'

   GPIO.setwarnings(False)

   radio = NRF24()
   radio.begin(0, 0, 25, 18) #set gpio 25 as CE pin
   radio.setRetries(15,15)
   radio.setPayloadSize(32)
   radio.setChannel(0x4c)
   radio.setDataRate(NRF24.BR_250KBPS)
   radio.setPALevel(NRF24.PA_MAX)
   radio.setAutoAck(1)
   radio.openWritingPipe(pipes[1])
   radio.openReadingPipe(1, pipes[0])

   radio.startListening()
   radio.stopListening()

   print ''
   print 'NRF24 Module Configuration Details:'
   radio.printDetails()
   radio.startListening()

   print ''
   cloudCommandLastCheck = datetime.now()

   # List to hold all commands that was send no ACK received
   localCommandSendAckWaitList = []
   while True:
       pipe = [0]
       cloudCommand = ''
       nowPI = datetime.now()
       while not radio.available(pipe, True):
           radioTime = datetime.now()
           tdelta = nowPI-radioTime
           time.sleep(1)
           if (abs(tdelta.total_seconds()) > 10): break

       recv_buffer = []
       radio.read(recv_buffer)
       out = ''.join(chr(i) for i in recv_buffer)

       nowPI = datetime.now()

       if debugMode == 1: print localCommandSendAckWaitList

       if out.find(';')>0:
          out = out.split(';')[0]
          print 'L: Received: ' + out

          temp =out.split("_")
          if debugMode == 1: print (temp)
    
          if temp[0] in config_data["Devices"]:
             if temp[1] == 'ack':
               # Clean list once ACK from SN is received
                localCommandSendAckWaitList= [x for x in localCommandSendAckWaitList if x != temp[2]]
                print '<- Broadcast complete, ACK received for: ' + temp[2]
             else:
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), temp[1], temp[2], config_data["Devices"][temp[0]], debugMode)
                print 'L: Generated selfok'
                sendMeasure(config_data, nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'live', 1, config_data["Server"]["Deviceid"], debugMode)
          else:
             if temp[0] == '???':
                 print 'New Device Registration, HandshakeID=' + temp[2]
                 localId = sendSensorRegistration(config_data,  nowPI.strftime("%Y-%m-%dT%H:%M:%S"), 'new custom device (' + temp[2] + ')')
                 if localId != 0:
                      localCommandSendAckWaitList.append('???_v02_' + temp[2] + '_' + localId) 
                      # Reload config data as we succesfully registered new device
                      json_data=open(configFileName)
                      config_data = json.load(json_data)
                      json_data.close()
             else:
                 print '-> ignore'

       if queue_name <> '':
          # if check timeout is gone go to Azure and grab command to execute
          tdelta = nowPI-cloudCommandLastCheck
          manager = ThreadManager(bus_service, queue_name, localCommandSendAckWaitList, config_data)
          thread = manager.new_thread()
          if (abs(tdelta.total_seconds()) > 10) and thread is not None:
             cloudCommandLastCheck = datetime.now()
             thread.run()

          if debugMode == 1: print localCommandSendAckWaitList
          # Repeat sending/span commands while list is not empty
          for localCommand in localCommandSendAckWaitList:
             radio.stopListening()
             buf = list(localCommand)
             radio.write(buf)
             print 'L: Broadcast Command: ' + localCommand 
             time.sleep(1)
             radio.startListening()
Esempio n. 8
0
class iotp2pran:

    # Pipes in use.
    # P0 is the TX pipe, others are RX
    pipes = []

    # The radio, supports NRF24L01P
    radio = NRF24()

    # Signal the network to go down
    SHUTDOWN_SIGNAL = False

    def __init__(self):
        pipes = [[0x70, 0x70, 0x70, 0x70, 0x71],
                 [0x70, 0x70, 0x70, 0x70, 0x70]]

        # We have CE on GPIO 22 (pin 15) and IRQ on GPIO 24 (pin 18)
        self.radio.begin(0, 0, 15, 18)

        # Default iotp2p RAN parameters
        self.radio.setCRCLength(NRF24.CRC_8)
        self.radio.setRetries(15, 15)
        self.radio.setPayloadSize(4)
        self.radio.setChannel(0x0A)
        self.radio.setDataRate(NRF24.BR_250KBPS)
        self.radio.setPALevel(NRF24.PA_MAX)
        self.radio.setAutoAck(1)

        self.radio.openWritingPipe(pipes[0])
        self.radio.openReadingPipe(1, pipes[1])

        self.radio.startListening()

    #
    # Reads one command from the specified pipe
    # TODO: timeout missing, if someone sends one block and drops off net
    #   that stuff will stick to the next caller start of message.
    #
    def readMessage(self, pipe):
        recv_str = ""
        self.radio.startListening()
        while (not recv_str.endswith('\n')):
            recv_buf = []
            while not self.radio.available(pipe, False):
                time.sleep(1000 / 1000000.0)
            self.radio.read(recv_buf)
            for c in recv_buf:
                if (c != 0):
                    recv_str += str(unichr(c))
        return recv_str[0:-1]

    def sendMessage(self, command):
        send_buf = [0] * self.radio.payload_size
        command += "\n"
        # We must align the string to payload size boundary, so we pad with nulls
        for cx in range(
                0,
                len(command) + (self.radio.payload_size -
                                (len(command) % self.radio.payload_size))):
            send_buf[cx % self.radio.payload_size] = command[cx] if cx < len(
                command) else 0
            if ((cx % self.radio.payload_size) == self.radio.payload_size - 1):
                self.radio.stopListening()
                self.radio.write(send_buf)
                self.radio.startListening()
                bx = 0

    def broadcastBCH(self):
        while not self.SHUTDOWN_SIGNAL:
            self.radio.stopListening()
            self.sendMessage("BCH:IOT0.0")
            self.radio.startListening()
            time.sleep(1)

    def startNetwork(self):
        self.SHUTDOWN_SIGNAL = False
        thread = Thread(target=self.broadcastBCH)
        thread.start()

    def stopNetwork(self):
        self.SHUTDOWN_SIGNAL = True
Esempio n. 9
0
from nrf24 import NRF24
import time

pipes = [[0xe7, 0xe7, 0xe7, 0xe7, 0xe7], [0xc2, 0xc2, 0xc2, 0xc2, 0xc2]]

radio = NRF24(15, 24)
radio.begin(0, 0, 17)
#radio.begin(1, 0, "P8_23", "P8_24")

radio.setRetries(15, 15)

radio.setPayloadSize(32)
radio.setChannel(0x60)
radio.setDataRate(NRF24.BR_2MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])

radio.startListening()
radio.stopListening()

radio.printDetails()

radio.startListening()

c = 1