Esempio n. 1
0
	def receive(self,controller):
		try:
			self.lora.set_mode(MODE.RXCONT)
			message = self.lora.on_rx_done()
			if message == '$-$-$-cool$-$-$-':
				message = ''
				send2(controller)
			elif message == '!resend!':
				while (time.time() - start_time < 3): 
					for i in range(0,3):
           				self.lora.start(self.prev_msg[i])
			else:
				start_time = time.time()
				while time.time()-start_time < 3:
		    		message = message  + self.lora.on_rx_done()
		    	if len(message) < 48:
		    		self.lora.start("!resend!")
		    		return
		    	self.msg_list.insert(END, 'user : '******''


		except KeyboardInterrupt:
		    sys.stdout.flush()
		    print("Exit")
		    sys.stderr.write("KeyboardInterrupt\n")
		finally:
		    sys.stdout.flush()
		    print("Exit")
		    lora.set_mode(MODE.SLEEP)
		BOARD.teardown()
Esempio n. 2
0
    def run(self):
        BOARD.setup()
        parser = LoRaArgumentParser("Continous LoRa receiver.")

        lora = LoRaRcvCont(verbose=False)
        args = parser.parse_args(lora)

        lora.set_mode(MODE.STDBY)
        lora.set_pa_config(pa_select=1)
        lora.set_freq(434.0)
        #lora.set_rx_crc(True)
        #lora.set_coding_rate(CODING_RATE.CR4_6)
        #lora.set_pa_config(max_power=0, output_power=0)
        #lora.set_lna_gain(GAIN.G1)
        #lora.set_implicit_header_mode(False)
        #lora.set_low_data_rate_optim(True)
        #lora.set_pa_ramp(PA_RAMP.RAMP_50_us)
        #lora.set_agc_auto_on(True)

        print("lora: {0}".format(lora))
        assert (lora.get_agc_auto_on() == 1)
        time.sleep(1)
        try:
            lora.start()
        except KeyboardInterrupt:
            sys.stdout.flush()
            print("")
            sys.stderr.write("KeyboardInterrupt\n")
        finally:
            sys.stdout.flush()
            print("")
            lora.set_mode(MODE.SLEEP)
            print(lora)
            BOARD.teardown()
Esempio n. 3
0
 def on_rx_done(self):
     BOARD.led_on()
     wrkdir = '/home/pi/Desktop/'
     # print("\nRxDone")
     self.clear_irq_flags(RxDone=1)
     payload = self.read_payload(nocheck=True)
     print("Receive: ")
     dataRaw = bytes(payload).decode("utf-8", 'ignore')
     dataRec = dataRaw[2:-1].split(",")
     print(dataRec)  # Receive DATA
    # print(argLen)
     if argLen is 2:
         filename = sensorName + ".csv"
         filename = join('/home/pi/Desktop/',filename)
         with open(filename, "a+") as csvfile:
             wr = csv.writer(csvfile, quoting = csv.QUOTE_ALL)
             wr.writerow(dataRec)
         csvfile.closed
     BOARD.led_off()
     time.sleep(2)  # Wait for the client be ready
     print("Send: ACK")
     self.write_payload([255, 255, 0, 0, 65, 67, 75, 0])  # Send ACK
     self.set_mode(MODE.TX)
     self.var = 1
     time.sleep(.5)  # a tad to complete
     print("Data Sent")
     sys.stdout.flush()
     lora.set_mode(MODE.SLEEP)
     BOARD.teardown()
     sys.exit()
Esempio n. 4
0
 def on_tx_done(self):  # When Transmitting is done?
     global args
     self.set_mode(MODE.STDBY)
     self.clear_irq_flags(TxDone=1)
     if args.single:
         print("args exit")
         sys.exit(0)
     BOARD.led_off()
     print("Ending Transmission")
     BOARD.teardown()
     sys.exit(0)
Esempio n. 5
0
def tx(msg):
    BOARD.setup()
    lora = LoRaTransmit()
    lora.set_freq(868.000000)
    lora.set_pa_config(pa_select=1, max_power=5)
    lora.set_bw(8)
    lora.set_coding_rate(CODING_RATE.CR4_5)
    try:
        lora.send(msg)
    finally:
        lora.set_mode(MODE.SLEEP)
        BOARD.teardown()
Esempio n. 6
0
def main():
    BOARD.setup()

    receiver = MyLoRa()

    try:
        while True:
            sleep(0.05)
            irq_flags = receiver.get_irq_flags()
            if irq_flags['rx_done'] == 1:
                receiver.on_rx_done()

    finally:
        BOARD.teardown()
Esempio n. 7
0
def main():
	try:
		app = Godsky()
		app.geometry("1200x700+350+150")

		app.mainloop()

	except:
		raise

	finally:
	    sys.stdout.flush()
	    print("Exit")
	    lora.set_mode(MODE.SLEEP)
		BOARD.teardown()
Esempio n. 8
0
    def start(self):
        while True:
            print('----------------------------------')
            sleep(1)

            try:
                rawinput = raw_input(">>> ")
            except NameError:
                rawinput = input(">>> ")
            except KeyboardInterrupt:
                lora.set_mode(MODE.SLEEP)
                sleep(.5)
                BOARD.teardown()
                exit()

            if len(rawinput) < 200:

                data = {"id": self._id, "data": rawinput}
                _length, _payload = packer.Pack_Str(json.dumps(data))

                try:
                    # for python2
                    data = [int(hex(ord(c)), 0) for c in _payload]
                except:
                    # for python3
                    data = [int(hex(c), 0) for c in _payload]

                for i in range(3):
                    if self.rx_done is True:
                        self.rx_done = False
                        break
                    else:
                        self.set_mode(MODE.SLEEP)
                        self.set_dio_mapping([1, 0, 0, 0, 0, 0])  # TX
                        sleep(.5)
                        lora.set_pa_config(pa_select=1)
                        self.clear_irq_flags(TxDone=1)
                        self.set_mode(MODE.STDBY)
                        sleep(.5)
                        print("Raw TX: {}".format(data))

                        self.write_payload(data)
                        self.set_mode(MODE.TX)

                        ## ALOHA(1~3) ## on_tx_done
                        t = i * i + int(np.random.random() * float(_length))
                        print("ALOHA Waiting: {}".format(t))
                        sleep(t)
Esempio n. 9
0
def txRepeat(msg, num):
    BOARD.setup()
    lora = LoRaTransmit()
    lora.set_freq(868.000000)
    lora.set_pa_config(pa_select=1, max_power=5)
    lora.set_bw(8)
    lora.set_coding_rate(CODING_RATE.CR4_5)
    try:
        for i in range(0, num):
            lora.send(msg)
            try:
                with timeout(seconds=2):
                    while lora.transmitting:
                        sleep(0.1)
            except TimeoutError:
                print("Sending timed out.")
                sleep(1)
    finally:
        lora.set_mode(MODE.SLEEP)
        BOARD.teardown()
Esempio n. 10
0
def txMulti(msg):
    BOARD.setup()
    lora = LoRaTransmit()
    lora.set_freq(868.000000)
    lora.set_pa_config(pa_select=1, max_power=5)
    lora.set_bw(8)
    lora.set_coding_rate(CODING_RATE.CR4_5)
    try:
        while len(msg) > 0:
            part = msg[:256]
            msg = msg[256:]
            lora.send(part[1:])
            try:
                with timeout(seconds=3):
                    while lora.transmitting:
                        sleep(0.1)
            except TimeoutError:
                print("Sending timed out.")
    finally:
        lora.set_mode(MODE.SLEEP)
        BOARD.teardown()
Esempio n. 11
0
    def start(self):
        while True:
            print '----------------------------------'

            try:
                rawinput = raw_input(">>> ")
            except KeyboardInterrupt:
                lora.set_mode(MODE.SLEEP)
                BOARD.teardown()
                print "exit()"

            if len(rawinput) < 200:
                self.set_mode(MODE.STDBY)
                self.clear_irq_flags(TxDone=1)

                data = {"id": self._id, "data": rawinput}
                _length, _payload = packer.Pack_Str(json.dumps(data))
                data = [int(hex(ord(c)), 0) for c in _payload]
                print "data", _payload
                print "Rawinput:", data

                sleep(1)
                self.write_payload(data)
                self.set_mode(MODE.TX)

                sleep(.5)
                self.set_mode(MODE.SLEEP)
                self.set_dio_mapping([0] * 6)
                sleep(.5)
                self.set_mode(MODE.STDBY)
                sleep(.5)
                self.reset_ptr_rx()
                self.set_mode(MODE.RXCONT)

                for _ in range(t):
                    sleep(.1)

                    if self.rx_done == True:
                        self.rx_done = False
                        break
Esempio n. 12
0
def closing_function():
    LoRaThread.shutdown()
    BOARD.teardown()
    thread.join()
Esempio n. 13
0
	
	print "\rSending Message %s" % self.tx_counter
	self.set_mode(MODE.TX)  # send Message
        while True:
		sleep(0.5)

msg = "Hello"

lora = LoRaBeacon(verbose=False)

lora.set_pa_config(pa_select=0)
lora.set_coding_rate(CODING_RATE.CR4_6)
lora.set_implicit_header_mode(False)

print(lora)
try: input("Press enter to start...")
except: pass

try:
    lora.start()
except KeyboardInterrupt:
    sys.stdout.flush()
    print("")
    sys.stderr.write("KeyboardInterrupt\n")
finally:
    sys.stdout.flush() # Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal
    print("")
    lora.set_mode(MODE.SLEEP)
    print(lora)
    BOARD.teardown() # Cleanup GPIO and SpiDev
Esempio n. 14
0
# (FSK option)
#lora.set_pa_ramp(PA_RAMP.RAMP_50_us)

print(lora)
#assert(lora.get_lna()['lna_gain'] == GAIN.NOT_USED)
#assert(lora.get_agc_auto_on() == 1)

print("Beacon config:")
print("  Wait %f s" % args.wait)
print("  Single tx = %s" % args.single)
print("")
try:
    input("Press enter to start...")
except:
    pass

try:
    lora.start()
except KeyboardInterrupt:
    sys.stdout.flush()
    print("")
    sys.stderr.write("KeyboardInterrupt\n")
finally:
    sys.stdout.flush(
    )  # Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal
    print("")
    lora.set_mode(MODE.SLEEP)
    print(lora)
    BOARD.teardown()  # Cleanup GPIO and SpiDev
Esempio n. 15
0
#lora.set_implicit_header_mode(False)
#lora.set_pa_config(max_power=0x04, output_power=0x0F)
#lora.set_pa_config(max_power=0x04, output_power=0b01000000)
#lora.set_low_data_rate_optim(True)
#lora.set_pa_ramp(PA_RAMP.RAMP_50_us)


print(lora)
#assert(lora.get_lna()['lna_gain'] == GAIN.NOT_USED)
assert(lora.get_agc_auto_on() == 1)

print("Beacon config:")
print("  Wait %f s" % args.wait)
print("  Single tx = %s" % args.single)
print("")
try: input("Press enter to start...")
except: pass

try:
    lora.start()
except KeyboardInterrupt:
    sys.stdout.flush()
    print("")
    sys.stderr.write("KeyboardInterrupt\n")
finally:
    sys.stdout.flush()
    print("")
    lora.set_mode(MODE.SLEEP)
    print(lora)
    BOARD.teardown()
Esempio n. 16
0
    def start(self):
        while True:
            global number_node

            print('----------------------------------')
            sleep(1)

            try:
                # initialize request
                if number_node == len(node_list):
                    number_node = 0
                # request
                request_msg = node_list[number_node]
                #    rawinput = raw_input(">>> ")
                #except NameError:
                #    rawinput = input(">>> ")
                print(request_msg)
            except KeyboardInterrupt:
                lora.set_mode(MODE.SLEEP)
                sleep(.5)
                BOARD.teardown()
                exit()

            if len(request_msg) < 200:
                """
                # data = {"id":self._id, "data":rawinput}
                # _length, _payload = packer.Pack_Str( json.dumps(data) )
                data = {"id":self._id, "data":request_msg}
                _length, _payload = packer.Pack_Str( json.dumps(data) )
                
                try:
                    # for python2
                    data = [int(hex(ord(c)), 0) for c in _payload]
                except:
                    # for python3 
                    data = [int(hex(c), 0) for c in _payload]
                """
                try:
                    # for python2
                    data = [int(hex(ord(c)), 0) for c in request_msg]
                except:
                    # for python3
                    data = [int(hex(c), 0) for c in request_msg]

                for i in range(3):
                    if self.rx_done is True:
                        self.rx_done = False
                        break
                    else:
                        self.set_mode(MODE.SLEEP)
                        self.set_dio_mapping([1, 0, 0, 0, 0, 0])  # TX
                        sleep(.5)
                        lora.set_pa_config(pa_select=1)
                        self.clear_irq_flags(TxDone=1)
                        self.set_mode(MODE.STDBY)
                        sleep(.5)
                        # print("Raw TX: {}".format(data))
                        print("int(hex(request_msg)) TX: {}".format(data))
                        print("request_msg TX: {}".format(request_msg))
                        self.write_payload(data)
                        self.set_mode(MODE.TX)
                        """
                        ## ALOHA(1~3) ## on_tx_done
                        t = i*i + int(np.random.random() * float(_length))
                        print("ALOHA Waiting: {}".format( t))
                        """
                        t = 10
                        print("Waiting:{}".format(t))
                        sleep(t)
                # request to next node
                # number_node = number_node + 1
                number_node += 1
Esempio n. 17
0
    def start(self):
        global mode
        global pump1
        global pump2
        global temp
        global mistspray
        global pump1m
        global pump2m
        global tempm
        global mistspraym
        global i
        while True:
            print '----------------------------------', pump1, pump2
            try:
                if mode == 0:  # manual node 1
                    if (pump1m == 0 and mistspraym == 0):
                        data1 = "0"
                    elif (pump1m == 0 and mistspraym == 1):
                        data1 = "1"
                    elif (pump1m == 1 and mistspraym == 0):
                        data1 = "2"
                    else:
                        data1 = "3"
                elif mode == 1:  # auto node 1
                    if (pump1 == 0 and mistspray == 0):
                        data1 = "4"
                    elif (pump1 == 0 and mistspray == 1):
                        data1 = "5"
                    elif (pump1 == 1 and mistspray == 0):
                        data1 = "6"
                    else:
                        data1 = "7"
                if mode == 0:  # manual node 2
                    if (pump2m == 0 and tempm == 0):
                        data2 = "0"
                    elif (pump2m == 0 and tempm == 1):
                        data2 = "1"
                    elif (pump2m == 1 and tempm == 0):
                        data2 = "2"
                    else:
                        data2 = "3"
                elif mode == 1:  # auto node 2
                    if (pump2 == 0 and temp == 0):
                        data2 = "4"
                    elif (pump2 == 0 and temp == 1):
                        data2 = "5"
                    elif (pump2 == 1 and temp == 0):
                        data2 = "6"
                    else:
                        data2 = "7"
                tx_data = "AT" + data1 + data2
                print tx_data
            except KeyboardInterrupt:
                lora.set_mode(MODE.SLEEP)
                BOARD.teardown()
                print "exit()"

            if len(tx_data) < 200:
                self.set_mode(MODE.STDBY)
                self.clear_irq_flags(TxDone=1)
                datalist = list()
                datalist = []
                i = 0
                for x in tx_data:
                    datalist.insert(i, ord(x))
                    i += 1
                print "data", datalist
                print "Rawinput:", tx_data
                sleep(1)
                self.write_payload(datalist)
                self.set_mode(MODE.TX)
                sleep(.5)
                self.set_dio_mapping([0] * 6)
                sleep(.5)
                self.set_mode(MODE.STDBY)
                sleep(.5)
                self.reset_ptr_rx()
                self.set_mode(MODE.RXCONT)

                for _ in range(t2):
                    sleep(.2)

                    if self.rx_done == True:
                        self.rx_done = False
                        break
    def start(self):
        while True:
            print '----------------------------------'
            ##########
            # Initialize and start the video frame capture
            #cam = cv2.VideoCapture(0)
            flag = "0"
            dem = 0
            count = 0
            vantay = "0"
            add = "0"
            delete = "0"
            cam = cv2.VideoCapture(0)
            ##            cam.set(cv2.CAP_PROP_FPS, 30)
            while True:
                while ser.in_waiting:
                    read_serial = ser.readline()
                    s = str(int(read_serial, 16))
                    flag = "1"
                    print s
                    if s == "222":  #quet
                        read_serial = ser.readline()
                        vantay = str(int(read_serial, 16))
                        print vantay
                    elif s == "555":  #them
                        read_serial = ser.readline()
                        vantay = str(int(read_serial, 16))
                        add = "1"

                        print vantay
                    elif s == "444":  #xoa
                        read_serial = ser.readline()
                        vantay = str(int(read_serial, 16))
                        delete = "1"
                        print vantay

                # Read the video frame
                ret, im = cam.read()

                # Convert the captured frame into grayscale
                gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)

                # Get all face from the video frame
                faces = faceCascade.detectMultiScale(gray, 1.2, 5)

                # For each face in faces
                for (x, y, w, h) in faces:
                    gray_face = gray[y:y + h, x:x + w]
                    eyes = eyeCascade.detectMultiScale(gray_face)
                    for (ex, ey, ew, eh) in eyes:

                        # Create rectangle around the face
                        cv2.rectangle(im, (x - 20, y - 20),
                                      (x + w + 20, y + h + 20), (0, 255, 0), 4)

                        # Recognize the face belongs to which ID
                        Id = recognizer.predict(gray[y:y + h, x:x + w])

                        # Check the ID if exist
                        if (Id[0] == 1) and (Id[1] <= 80):
                            Id_reg = "KHANG"
                            dem = 0
                        else:
                            Id_reg = "UNKNOWN"
                            currentDT = datetime.datetime.now()
                            #cv2.imwrite("Unknown_person_data/Unknown.jpg",gray_face)
                            cv2.imwrite(
                                "Unknown_person_data/Unknown." +
                                str(currentDT.strftime("%H-%M-%S")) + '_' +
                                str(currentDT.strftime("%d-%m-%Y")) + ".jpg",
                                gray_face)
                            dem += 1

                        # Put text describe who is in the picture
                        #cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,0,255), -1)
                        #cv2.putText(im, str(Id_reg), (x,y-40), font, 1, (255,255,255), 2)
                # Display the video frame with the bounded rectangle
                cv2.imshow('Face_Recognition', im)
                # If 'q' is pressed, close program
                if dem >= 30:
                    camera = "1"
                    flag = "2"
                    count = 0
                else:
                    if count >= 50:
                        count = 0
                        dem = 0
                    else:
                        count += 1
##
                print("gia tri dem: ", dem)
                print("gia tri flag:" + flag)

                if cv2.waitKey(10) & 0xFF == ord(
                        'q') or flag == "1" or flag == "2":
                    break

            # Stop the camera
            cam.release()

            # Close all windows
            cv2.destroyAllWindows()
            ##########
            try:
                if flag == "1":
                    rawinput = vantay
                    print rawinput
                elif flag == "2":
                    rawinput = camera
            except KeyboardInterrupt:
                lora.set_mode(MODE.SLEEP)
                BOARD.teardown()
                print "exit()"

            if len(rawinput) < 200:
                self.set_mode(MODE.STDBY)
                self.clear_irq_flags(TxDone=1)
                if flag == "1":
                    data = {"d": rawinput, "del": delete, "a": add, "ty": flag}
                elif flag == "2":
                    data = {"d": rawinput, "ty": flag}
                _length, _payload = packer.Pack_Str(json.dumps(data))
                print "Rawinput:", data
                data = [int(hex(ord(c)), 0) for c in _payload]
                print "data", _payload

                sleep(1)
                self.write_payload(data)
                self.set_mode(MODE.TX)

                sleep(.5)
                self.set_mode(MODE.SLEEP)
                self.set_dio_mapping([0] * 6)
                sleep(.5)
                self.set_mode(MODE.STDBY)
                sleep(.5)
                self.reset_ptr_rx()
                self.set_mode(MODE.RXCONT)

                for _ in range(t):
                    sleep(.1)

                    if self.rx_done == True:
                        self.rx_done = False
                        break
Esempio n. 19
0
        self.assertEqual(get_reg(REG.LORA.DIO_MAPPING_2), 0b00000000)
        self.assertEqual(lora.get_dio_mapping(), dio_mapping)

        dio_mapping = [0, 1, 2, 0, 1, 2]
        lora.set_dio_mapping(dio_mapping)
        self.assertEqual(get_reg(REG.LORA.DIO_MAPPING_1), 0b00011000)
        self.assertEqual(get_reg(REG.LORA.DIO_MAPPING_2), 0b01100000)
        self.assertEqual(lora.get_dio_mapping(), dio_mapping)

        dio_mapping = [1, 2, 0, 1, 2, 0]
        lora.set_dio_mapping(dio_mapping)
        self.assertEqual(get_reg(REG.LORA.DIO_MAPPING_1), 0b01100001)
        self.assertEqual(get_reg(REG.LORA.DIO_MAPPING_2), 0b10000000)
        self.assertEqual(lora.get_dio_mapping(), dio_mapping)


#    def test_set_lna_gain(self):
#        bkup_lna_gain = lora.get_lna()['lna_gain']
#        for target_gain in [GAIN.NOT_USED, GAIN.G1, GAIN.G2, GAIN.G6, GAIN.NOT_USED, bkup_lna_gain]:
#            print(target_gain)
#            lora.set_lna_gain(target_gain)
#            actual_gain = lora.get_lna()['lna_gain']
#            self.assertEqual(GAIN.lookup[actual_gain], GAIN.lookup[target_gain])

if __name__ == '__main__':

    BOARD.setup()
    lora = LoRa(verbose=False)
    unittest.main()
    BOARD.teardown()
Esempio n. 20
0
 def shutdown(self):
     self.set_mode(MODE.SLEEP)
     BOARD.teardown()