def reset_update_for_test(subpath): """ Dumps current state to update directory so update will be idempotent, and resets updates status Example: hw.power_peripherals(True) hw.mount_sd_card() import co2unit_update co2unit_update.wdt = wdt co2unit_update.reset_update_for_test("/sd/updates/update-2019-07-26") import os os.remove("/sd/var/updates-state.json") """ import machine _logger.info("Clearing update subdirectory %s", subpath) fileutil.rm_recursive(subpath, wdt=wdt) _logger.info("Copying current code to %s", subpath) fileutil.copy_recursive("/flash", subpath + "/flash", wdt=wdt) rand_site_code = "rand_site_%04x" % (machine.rng() % (16**4)) _logger.info("Adding a randomized conf_patch: %s", rand_site_code) fileutil.mkdirs(subpath + "/conf_patch") with open(subpath + "/conf_patch/ou-id.json", "w") as f: patch = {"site_code": rand_site_code} f.write(json.dumps(patch))
def get_random_time(self): # get random number of seconds within interval, add one so it cannot be zero s_to_next_lora = int( machine.rng() / (2**24) * int(float(config.get_config("interval")) * 60)) + 1 return s_to_next_lora
def select_new_frequency(): global hop_num global start_freq r_num = (machine.rng() % hop_num) + 1 hop = r_num * 100000 frequency = start_freq + hop return frequency
def rng(): r0 = machine.rng() if r0 > rng_max: # raise Exception("rand(): r0=({}) > rng_max=({})".format(hex(r0), hex(rng_max))) print("ERROR: rand(): r0=({}) > rng_max=({}), retrying".format(hex(r0), hex(rng_max))) return rng() else: return r0
def make_header(self, message_type): now = self.rtc.now() ts = utime.mktime(now) ms = int(now[6]) mid = machine.rng() return pack(HEADER_PACK_FORMAT, ts, ms, mid, int(self.dev_ID), message_type)
def sha_test(lenght=100): import machine import hashlib buf = bytearray() for x in range(lenght // 3): buf += machine.rng().to_bytes(3, 'big') # print(buf) h = hashlib.sha256(buf) # print(hex(buf[0]), hex(buf[-1]), h.digest()) return h.digest()
def get_random_time(): """ Get random number of seconds within interval :return: s_to_next_lora :rtype: int """ # get random number of seconds within (interval - lora_timeout) and add one so it cannot be zero s_to_next_lora = int((machine.rng() / (2**24)) * (int(float(config.get_config("interval")) * 60) - int(config.get_config("lora_timeout")))) + 1 return s_to_next_lora
def sock_send_repeat(packt_len, num_packts, delay_secs, fhss=False): global sock global lora if delay_secs <= 0: delay_secs = 0.1 for i in range(num_packts): packet = bytes([machine.rng() & 0xFF for b in range(packt_len)]) print("Sending packet number {}: {}".format(i, packet)) if fhss: lora.frequency(select_new_frequency()) sock.send(packet) time.sleep(delay_secs)
def selfTest(self): i = 0 while i < self.capacity: save = self.readEEPROM(i) out = machine.rng() & 0xFF self.writeEEPROM(i, out) check = self.readEEPROM(i) if out == check: print(("00000000" + hex(i)[2:])[-8:], "passed") else: print(("00000000" + hex(i)[2:])[-8:], "failed") break i += 1024 print("Capacity:", i, "vs", self.capacity, "declared.")
def LoRaFun(): lora = LoRa(mode=LoRa.LORA, region=LoRa.US915) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # send some data s.setblocking(True) s.send('Hello from Node1') # get any data received... s.setblocking(False) data = s.recv(64) print(data) # wait a random amount of time time.sleep(machine.rng() & 0x0F)
def _reset(self, alarm=None): now = time.ticks_ms() for addr, node in self._nodes.items(): if node._reset_next != None and time.ticks_diff( node._reset_next, now) >= 0: print("_reset", node._unit_addr) node._reset_next = time.ticks_add( now, node._reset_trial * 5000 + (machine.rng() % 5000)) if node._reset_trial < 30: node._reset_trial += 1 self._reset_timeout = Timer.Alarm(self._reset, 5) node._reset_session = crypto.getrandbits(64) self._send_with_session(node, node._reset_session, _MSG_RST_1, None) return Timer.Alarm(self._reset, 2)
def sock_send_all_channels(packt_len, delay_secs=0.1): global sock global lora global start_freq global end_freq start = start_freq end = end_freq if delay_secs <= 0: delay_secs = 0.1 for i in range((end - start) / 100000): packet = bytes([machine.rng() & 0xFF for b in range(packt_len)]) print("Sending packet number {}: {}".format(i, packet)) lora.frequency(start + (i * 100000)) sock.send(packet) time.sleep(delay_secs)
def drawForTicks(ticks, numPRs): global rgbData global highlightPixel if numPRs < 0: blynk(ticks, [0, 255, 255]) return clrIndex = min(numPRs, len(colorsForNumPRs) - 1) color = colorsForNumPRs[clrIndex] if ticks % 10 == 0: highlightPixel = (machine.rng() >> 16) % CHAIN_LEN factor = 10 + (10 - ((ticks - 1) % 10)) rgbData[highlightPixel] = [(color[0] * factor) // 10, (color[1] * factor) // 10, (color[2] * factor) // 10] chain.show(rgbData)
def GPS_run(): print('GPS_run') pycom.heartbeat( False) # turn off the heartbeat LED so that it can be reused pycom.rgbled(0x000000) # turn LED off print('GPS start') f = open('device_name') #get device name from file dev_ID = f.read() print(dev_ID) # connect to GPS device com = GPS_UART_start() # initialize LoRa in LORA mode # more params can also be given, like frequency, tx power and spreading factor print("LoRa start") lora = LoRa(mode=LoRa.LORA, frequency=925000000, tx_power=20) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: if (com.any()): data = com.readline() #print (data) if (data[0:6] == b'$GPGGA'): place = NmeaParser() place.update(data) print("place", place.longitude, ":", place.latitude, ":", place.fix_time) sendtoLoRa(s, dev_ID, place) # f_log = open('Lora_log','a') # careful that log file fills up the memory # f_log.write(data + ' ' + str(lora.rssi()) + '\n\n') # f_log.close() # wait a random amount of time time.sleep(10 + (machine.rng() & 0x3f) / 10)
def descubrir(the_sock, SND_ADDR, RCV_ADDR): seqnum = 0 acknum = 0 sent = 0 retrans = 0 cuenta = 0 last_pkt = True n = 1 dispositivos = {} text = SND_ADDR packet = make_packet(SND_ADDR, ANY_ADDR, seqnum, acknum, DATA_PACKET, last_pkt, text) send_time = time.time() sent += 1 the_sock.settimeout(2) while True: try: print("buscando") the_sock.send(packet) data = the_sock.recv(MAX_PKT_SIZE) source_addr, dest_addr, seqnum, acknum, ack, final, content = unpack( data) ips = dispositivos.values() if (data != b'') and (content not in ips): print(data) dispositivos[n] = [source_addr] n += 1 # wait a random amount of time rat = machine.rng() & 0x05 time.sleep(rat) except socket.timeout: the_sock.send(packet) cuenta += 1 print(cuenta) if (cuenta == 10): break return dispositivos
def RandomFloat(): if 'rng' in globals(): return rng() / (2**24) return random()
def __random_slot(self): return machine.rng() % (len(self._values) + 1)
mch = os.uname().machine if not 'LaunchPad' in mch and not 'WiPy' in mch: raise Exception('Board not supported!') wifi = WLAN() print(machine) machine.idle() print(machine.freq() == (80000000, )) print(machine.unique_id() == wifi.mac()) machine.main('main.py') rand_nums = [] for i in range(0, 100): rand = machine.rng() if rand not in rand_nums: rand_nums.append(rand) else: print('RNG number repeated') break for i in range(0, 10): machine.idle() print("Active") print(machine.reset_cause() >= 0) print(machine.wake_reason() >= 0) try:
def get_random_0_1(): return (machine.rng() % 16777215) / 16777215
print('[0]Received gateway broadcast...') gateway_addr = rcvd[3:7] #fetch gateway addr #header = rcvd[0:3] #fetch header register_raw = header[1:3] + dev_addr + b'\x01' + rcvd[ 8:10] + b'\x00\x02\x0D\x00\x01' crc = 0x00 for bit in register_raw: crc = crc + bit crc = crc & 0xFF # calculate checksum register_pac = gateway_addr[ 2:4] + b'\x17\x7E' + make_special_char( register_raw) + bytes([crc]) + b'\x21' duration = struct.unpack('>H', rcvd[13:15])[0] slot = struct.unpack('>H', rcvd[15:17])[0] rand_sleep = round( machine.rng() / int(0xFFFFFF) * (duration / slot)) * slot / 100 + 0.01 print('[0]CA Wait for ' + ('%.2f' % rand_sleep) + ' secs...') time.sleep(rand_sleep) uart_as62.write(register_pac) print('[0]Responded gateway broadcast...') time.sleep(0.01) elif (rcvd[11] == 0x02 ): #gateway register_success response if (rcvd[13:15] == b'\x4F\x4B'): print( '[0]Received gateway response... Device registered!' ) state = 1 p_out_led.value(0)
def main(): start_delay_ms = 0 time_ms = time.ticks_ms() last_sent_ms = time_ms state = 'IDLE' # States are: 'IDLE', 'RUNNING', 'FINISHED' Pin('G4', mode=Pin.IN, pull=Pin.PULL_DOWN) crank = PulseCounter('G5', Pin.PULL_DOWN, Pin.IRQ_RISING, 250) # initialize LoRa as a node (with Rx IQ inversion) lora = LoRa(tx_iq=False, rx_iq=True) # LCD pin configuration: lcd_rs = 'G11' lcd_en = 'G12' lcd_d4 = 'G15' lcd_d5 = 'G16' lcd_d6 = 'G13' lcd_d7 = 'G28' lcd_columns = 16 lcd_rows = 1 lcd = LCD.CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6, lcd_d7, lcd_columns, lcd_rows) rider = Rider(lcd) print("Ready for first rider.") lcd.clear() lcd.message("Ready fo\nr first rider.") while True: if state == 'IDLE': packet_rx = lora.recv() if packet_rx: try: parsed_json = json.loads(packet_rx.decode('ascii')) cmd = parsed_json['cm'] id = parsed_json['id'] if cmd == 's' and id == config.id: print('Going to running state') start_delay_ms = ((machine.rng() % 30) * 100) + time.ticks_ms() # send 's' (started) state over LoRa packet_tx = json.dumps({'id': config.id, 'cr':0, 'ds':int(rider.distance()), 'sp':int(rider.avg_speed()), 'st':'s'}) lora.send(packet_tx, True) rider.countdown() crank.counter = 0 # change to the running state and notify the gateway state = 'RUNNING' packet_tx = json.dumps({'id': config.id, 'cr':0, 'ds':int(rider.distance()), 'sp':int(rider.avg_speed()), 'st':'r'}) lora.send(packet_tx, True) except Exception: print('Corrupted LoRa packet') else: time.sleep_ms(50) elif state == 'RUNNING': if rider.ride(crank): print('Going to finished state') state = 'FINISHED' packet_tx = json.dumps({'id': config.id, 'cr':crank.counter, 'ds':int(rider.distance()), 'sp':int(rider.avg_speed()), 'st':'f'}) lora.send(packet_tx, True) time_ms = time.ticks_ms() if time_ms < start_delay_ms: pass elif time_ms > last_sent_ms + LORA_SEND_PERIOD_MS: last_sent_ms = time_ms packet_tx = json.dumps({'id':config.id, 'cr':crank.counter, 'ds':int(rider.distance()), 'sp':int(rider.avg_speed()), 'st':'r'}) print(packet_tx + ' {}'.format(last_sent_ms)) lora.send(packet_tx, True) else: print('attempt to receive lora') packet_rx = lora.recv() if packet_rx: print(packet_rx) try: # I've seen this failing sometimes parsed_json = json.loads(packet_rx.decode('ascii')) # check the packet received and process the commands except Exception: print('Corrupted LoRa packet') time.sleep(1.0 - (((time.ticks_ms() / 1000) - rider.starttime) % 1.0)) else: print('finishing ride') rider.finish() # change to the running state and notify the gateway state = 'IDLE' packet_tx = json.dumps({'id': config.id, 'cr':crank.counter, 'ds':int(rider.distance()), 'sp':int(rider.avg_speed()), 'st':'i'}) lora.send(packet_tx, True) crank.counter = 0
import machine import binascii import os uid = binascii.hexlify(machine.unique_id()) name = os.uname().sysname.lower() + '-' + uid.decode("utf-8")[-4:] def uprint(uart, *values): for v in values: uart.write(str(v)) uart.write(' ') uart.write('\r\n') ##################################################### m = hex(machine.rng()) # uart 0, repl # reinitializing uart0 in the following way, breaks the REPL in pymakr # however you can connect, e.g., with minicom -b 9600 # it will receive stdout, e.g. print() AND uart0.write() # uart0 = UART(0, baudrate=9600) # uart0.write("Hello UART 0 (") # uart0.write(r) # uart0.write(")\n\r") print("uart1") # uart1 = UART(1, baudrate=9600, timeout_chars=10) # pins=(TXD, RXD, RTS, CTS) uart1 = UART(1, baudrate=9600 ) # pins=('P23', 'P22'))
def rand_int(self, min, max): return int(min + (max - min) * (machine.rng() / (2 << 24)))
# print("... done. Click on \"Start send GFSK\" in RSA now") # sleep(2) # print("Run test_mode(GFSK) ...") test_mode(SFX_TEST_MODE_RX_GFSK, 30) # 30 seconds timeout # print("... done.") print("rssi", sigfox.rssi()) ################################################################################ ####################### Network Emulator tests ####################### ################################################################################ elif test == "NE-Uplink": # print("a") # #send(bytes([1,2,3,4,5,6,7,8,9,0xa,0xb,0xc])) # send(bytes([7])) # print("b") r = machine.rng() & 0xff print("reconfiguring sigfox to use public key") sigfox.public_key(True) num_messages = 1 for b in range(0, num_messages): x = utime.time() d = b % (0xff + 1) print("sending message nr", b, "of", num_messages) try: retval = send(bytes([0xac, r, d])) print("sent after", utime.time() - x, "seconds") print("retval", retval) except OSError as e: pycom.rgbled(0x550000) print("Exception caught:") # , e)
def add_random_minutes(tt, upperbound): yy, mo, dd, hh, mm, ss, wd, yd = tt rand_ss = machine.rng() % (upperbound * 60) return (yy, mo, dd, hh, mm, ss + rand_ss, wd, yd)
def ping(host, count=4, timeout=5000, interval=1000, quiet=False, size=64): raise Exception('Unsupported! Leaks memory!') # print('ping') import utime import uselect import uctypes import usocket import ustruct import machine # round up fractional values interval = max(1, int(interval)) # avoid count==0 count = max(count, 1) # prepare packet assert size >= 16, "pkt size too small" pkt = b'Q' * size pkt_desc = { "type": uctypes.UINT8 | 0, "code": uctypes.UINT8 | 1, "checksum": uctypes.UINT16 | 2, "id": uctypes.UINT16 | 4, "seq": uctypes.INT16 | 6, "timestamp": uctypes.UINT64 | 8, } # packet header descriptor h = uctypes.struct(uctypes.addressof(pkt), pkt_desc, uctypes.BIG_ENDIAN) h.type = 8 # ICMP_ECHO_REQUEST h.code = 0 h.checksum = 0 h.id = machine.rng() h.seq = 1 # init socket sock = usocket.socket(usocket.AF_INET, 3, 1) # usocket.SOCK_RAW, 1) sock.setblocking(0) sock.settimeout(timeout / 1000) addr = usocket.getaddrinfo(host, 1)[0][-1][0] # ip address sock.connect((addr, 1)) not quiet and print("PING %s (%s): %u data bytes" % (host, addr, len(pkt))) seqs = list(range(1, count + 1)) # [1,2,...,count] c = 1 t = 0 n_trans = 0 n_recv = 0 time_s = 0 finish = False # print('ping2') while t < timeout: if t == interval and c <= count: # send packet h.checksum = 0 h.seq = c h.timestamp = utime.ticks_us() h.checksum = _checksum(pkt) if sock.send(pkt) == size: n_trans += 1 t = 0 # reset timeout else: seqs.remove(c) c += 1 # recv packet while 1: socks, _, _ = uselect.select([sock], [], [], 0) if socks: resp = socks[0].recv(4096) resp_mv = memoryview(resp) h2 = uctypes.struct(uctypes.addressof(resp_mv[20:]), pkt_desc, uctypes.BIG_ENDIAN) # TODO: validate checksum (optional) seq = h2.seq if h2.type == 0 and h2.id == h.id and ( seq in seqs): # 0: ICMP_ECHO_REPLY t_elasped = (utime.ticks_us() - h2.timestamp) / 1000 ttl = ustruct.unpack('!B', resp_mv[8:9])[0] # time-to-live n_recv += 1 not quiet and print( "%u bytes from %s: icmp_seq=%u, ttl=%u, time=%.2f ms" % (len(resp), addr, seq, ttl, t_elasped)) time_s += t_elasped seqs.remove(seq) if len(seqs) == 0: finish = True break else: break if finish: break #utime.sleep_ms(1) t += 1 sock.close() loss = 0 try: loss = (n_trans - n_recv) / n_trans * 100 except: pass avg_ms = 0 try: avg_ms = time_s / n_recv except: pass ret = (n_trans, n_recv, loss, avg_ms) not quiet and print( "%u packets transmitted, %u packets received, %.2f%% packet loss, %.2f ms avg" % ret) return ret
def _create_mbap_hdr(self, slave_id, modbus_pdu): trans_id = machine.rng() & 0xFFFF mbap_hdr = struct.pack('>HHHB', trans_id, 0, len(modbus_pdu) + 1, slave_id) return mbap_hdr, trans_id
def TIME(min_wait): min_wait = min_wait + ( rng() / 10000000 ) # if problem occurs try to import machine and use ... + (machine.rng/10000000) time.sleep(min_wait)
def random_integer(upper_bound): return machine.rng() % upper_bound
mch = os.uname().machine if not 'LaunchPad' in mch and not'WiPy' in mch: raise Exception('Board not supported!') wifi = WLAN() print(machine) machine.idle() print(machine.freq() == (80000000,)) print(machine.unique_id() == wifi.mac()) machine.main('main.py') rand_nums = [] for i in range(0, 100): rand = machine.rng() if rand not in rand_nums: rand_nums.append(rand) else: print('RNG number repeated') break for i in range(0, 10): machine.idle() print("Active") print(machine.reset_cause() >= 0) print(machine.wake_reason() >= 0) try:
from network import LoRa import socket import machine import time # Initialize the lora object and set the region to USA lora = LoRa(mode=LoRa.LORA, region=LoRa.US915) # Set up a simple python socket to handle the LoRa packets lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # Set the socket to blocking and send a simple string lora_sock.setblocking(True) print('Sending Hello') lora_sock.send('Hello') # Set the socke to non-blocking and wait for 64 bytes of data lora_sock.setblocking(False) print('Waiting for data...') data = lora_sock.recv(64) # Then, print that data to the REPL print('Received: {}'.format(data)) # Sleep for a random amount of time. This will allow two LoPys to run this # exact version of the code, reducing the possibility of multiple colliding # packets time.sleep(machine.rng() & 0x0F)
# more params can also be given, like frequency, tx power and spreading factor lora = LoRa(mode=LoRa.LORA) # get LoRa MAC address loramac = binascii.hexlify(network.LoRa().mac()) print(loramac) loramac2 = binascii.unhexlify(loramac) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # get any data received... s.setblocking(False) data = s.recv(64) data2 = str(data) if data != b'': macorigen, sender, receiver, message = data2.split(",") print(data) largo = len(message) messagef = message[:largo - 1] print(messagef) LoraStats = lora.stats() # get lora stats (data is tuple) print(LoraStats) if messagef.lower() == "rojo": flash_led_to(RED) time.sleep(5) # wait a random amount of time rat = machine.rng() & 0x05 time.sleep(rat)