def read_pkt(pkt, dest_addr_filter, emit_addr_filter): ''' One function to read different kinds of packet. Returns a string to be printed. ''' try: # Packets in the format given by radiobit repo if len(pkt) >= 13: dest_filter_size = len(dest_addr_filter) emit_filter_size = len(emit_addr_filter) dest_addr, emit_addr, pkt_str = _packet_to_string_rb_format(pkt) # Filter packets regarding the destination address and emiter address filters if dest_addr[: dest_filter_size] == dest_addr_filter and emit_addr[: emit_filter_size] == emit_addr_filter: if REPEAT_FIRST_PACKET: while True: print('Sending pkt {}'.format(pkt_str)) radio.send_bytes(pkt) return pkt_str else: return None # Other formats else: pkt_str = _packet_to_string_unknown_format(pkt) return pkt_str # Some packets look too long to display except MemoryError as e: return 'Error : packet is too long, couldnt display'
def esb_send_bytes(radio, payload): cks = esb_checksum(payload) pkt = payload + [cks] print('pkt: %s' % pkt) radio.send_bytes(bytes(bytearray(pkt))) del cks del pkt
def _send(bytes, to_int): radio.send_bytes(bytes) sleep(10) _res.clear() tmp = radio.receive_bytes() while tmp != None: if to_int: tmp = int.from_bytes(tmp, 'big') _res.append(tmp) tmp = radio.receive_bytes()
def send_string(self, message): if len(message) > 19: message = message[:19] packet_type = int(2).to_bytes(1, 'little') time_stamp = microbit.running_time().to_bytes(4, 'little') serial_num = int(0).to_bytes(4, 'little') message_bytes = bytes(str(message), 'utf8') message_length = len(message_bytes).to_bytes(1, 'little') raw_bytes = (self.dal_header + packet_type + time_stamp + serial_num + message_length + message_bytes) radio.send_bytes(raw_bytes)
def processMessages(str_buf, group=None): msgs = str_buf.split( splitChar ) #splits the string in the buffer into commands separated by splitChar for msg in msgs: sendToUnity(msg) #first, check if the message received is a 'setter' - for ex. 'SD=40' str_val = 0 if msg.find( setValueChar ) != -1: #if the message contains the setValueChar character splitMsg = msg.split(setValueChar) msg = splitMsg[ 0] #the command itself is always on the left hand side of the splitChar str_val = splitMsg[1] #the value is always on the right hand side #CHECK FOR RECOGNIZED MESSAGES if msg == "": #ignore this message - it occurs when splitting for ex "SD=10#". #The result of that splitting will be "SD=10" and "" pass #set the writeToPcDelay elif msg == "SD": writeToPcDelay = int(str_val) str_val = '0' sendToUnity("the write to pc delay is now " + str(writeToPcDelay)) #acknowledge that Unity is now communicating with us elif msg == "RECV_OK": global isCommunicatingWithUnity isCommunicatingWithUnity = True sendToUnity("Established succesful bi-directional communication.") #add this group to the groups list elif msg == "AG": sendToUnity("Added " + str_val + " to my list of groups I should listen to.") groups.append(int(str_val)) #for the current group, set that player's value (letter choice) elif msg == "SV": sendToUnity("set group " + str(group) + " to " + str_val) #send back a confirmation message to the sender, so they can stop sending the letter radio.send_bytes(bytes(str_msg_received, 'ascii')) else: sendToUnity("Received an unrecognized message: <" + msg + ">")
def send_number(self, number): time_stamp = microbit.running_time().to_bytes(4, 'little') serial_num = int(0).to_bytes(4, 'little') if number <= 2147483647 and number >= -2147483648 and\ type(number) is int: number_bytes = number.to_bytes(4, 'little') packet_type = int(0).to_bytes(1, 'little') else: number_bytes = ustruct.pack('<d', number) packet_type = int(4).to_bytes(1, 'little') raw_bytes = (self.dal_header + packet_type + time_stamp + serial_num + number_bytes) radio.send_bytes(raw_bytes)
def send(): display.clear() radio.on() radio.config(channel=90, power=4) if "sample.raw" in os.listdir(): gen = sample_generator("sample.raw") else: gen = sawtooth_generator() start = running_time() sent = 0 for f in gen: # One frame every 4ms = 8kHz while sent > ((running_time() - start) >> 2) + 3: sleep(1) radio.send_bytes(f) sent += 1 print(sent)
def echolocate(me): configure_radio(7) radio.send_bytes(bytes([me, 255])) for power in range(8): configure_radio(power) radio.send_bytes(bytes([me, power])) microbit.sleep(10) message = radio.receive_bytes() while message: try: user, payload = message yield user, payload except ValueError: pass message = radio.receive_bytes()
def send_value(self, name, value): if len(name) > 8: name = name[:8] time_stamp = microbit.running_time().to_bytes(4, 'little') serial_num = int(0).to_bytes(4, 'little') if value <= 2147483647 and value >= -2147483648 and\ type(value) is int: number = int(value).to_bytes(4, 'little') packet_type = int(1).to_bytes(1, 'little') else: number = ustruct.pack('<d', value) packet_type = int(5).to_bytes(1, 'little') name_bytes = bytes(str(name), 'utf8') name_length = len(name_bytes).to_bytes(1, 'little') raw_bytes = (self.dal_header + packet_type + time_stamp + serial_num + number + name_length + name_bytes) radio.send_bytes(raw_bytes)
x = 0 if y > -30 and y < 30: y = 0 # arcade style steering signed_spd_left = y + x signed_spd_right = y - x # convert to motor command arguments if signed_spd_left >= 0: dir_left = DIR_FORWARD spd_left = map(signed_spd_left, 0, 511, 0, 255) else: dir_left = DIR_BACKWARD spd_left = map(signed_spd_left, -512, 0, 255, 0) # also convert right motor command if signed_spd_right >= 0: dir_right = DIR_FORWARD spd_right = map(signed_spd_right, 0, 511, 0, 255) else: dir_right = DIR_BACKWARD spd_right = map(signed_spd_right, -512, 0, 255, 0) # load motor command arguments into buffer message[0] = dir_left message[1] = spd_left message[2] = dir_right message[3] = spd_right # send the buffered message out via radio radio.send_bytes(message)
chr(Globals.CHANNEL) + pkt) else: uart.write(b'p' + chr(0)) elif cmd == 0x74: found = False for i in range(1, 100): radio.config(channel=i) if radio.ping(): uart.write(b't' + chr(i)) found = True break if not found: uart.write(b't' + chr(101)) elif cmd == 0x73: data = bytes(payload[2:]) radio.send_bytes(data) uart.write(b's') elif cmd == 0x6D and size >= 2: mode = payload[1] if mode == 0: reset() elif mode == 1: Globals.MODE = 1 # disable scan else: Globals.MODE = 2 uart.write(b'm') elif cmd == 0x62 and size >= 2: rate = payload[1] if rate >= 0 and rate <= 2: Globals.RATE = rate uart.write(b'b')
timer-=5000 update_cache() gid=i2c.read(0x20,1)[0] radio.config(channel=gid%32) seq=radio.receive_bytes() if seq==None: continue seq=seq.split(b'\r') if len(seq)==2: grp,bseq=seq grp=int(grp) if grp==-1 or grp==gid//32: try: res=eval(bseq) if res!=None: radio.send_bytes(b'%r\r%d'%(res,gid//32)) except:pass if len(seq)==3: id,size,bseq=seq size=int(size) if len(id)==8: try: if id_a==id: i2c.write(22,bseq) if size: radio.send_bytes(i2c.read(22,size)) except:pass try: if id_b==id: i2c.write(23,bseq) if size:
def send_valid(packet): # Appends packet header to packet bytes object and transmits on the radio radio.send_bytes(packet_header + packet)
self_brightness = 5 if self_cur_reload_delay > 0 else 9 other_brightness = 5 if other_cur_reload_delay > 0 else 9 display.set_pixel(self_pos, 4, self_brightness) display.set_pixel(4 - other_pos, 0, other_brightness) # Handle shoot events, torpedo movement, and win conditions if self_shoot is not None: display.set_pixel(self_shoot[0], self_shoot[1], 9) # Display the torpedo self_shoot = self_shoot[0], self_shoot[1] - 1 # Move the torpedo if self_shoot[1] < 0: if self_shoot[0] == 4 - other_pos: show_explosion(4 - other_pos, 0) self_score += 1 game_over = True radio.send_bytes(b'\xfd' + bytes([self_score])) else: self_shoot = None if other_shoot is not None: display.set_pixel(other_shoot[0], other_shoot[1], 9) other_shoot = other_shoot[0], other_shoot[1] + 1 if other_shoot[1] == 4: if other_shoot[0] == self_pos: show_explosion(self_pos, 4) other_score += 1 game_over = True else: other_shoot = None # Decrement reload delays if self_cur_reload_delay > 0:
def message_send(m): radio.send_bytes(struct.pack(MESSAGE_FORMAT, *m))
def send_dice(id, seq, msg): id_bytes = id.to_bytes(1, 'little') seq_bytes = seq.to_bytes(1, 'little') msg_bytes = msg.to_bytes(1, 'little') raw_bytes = (id_bytes + seq_bytes + msg_bytes) radio.send_bytes(raw_bytes)
# record close contact contactID = received_id + ( contacts[received_id][0] // 60000).to_bytes( 2, 'big' ) # "4 bytes serial, then 2 bytes for first timestamp" close_contacts[contactID] = ( contacts[received_id][1] // 60000).to_bytes( 2, 'big') + (b"!" if received_infected else b"" ) # (last timestamp, infected) if not infected and received_infected: infected = 1 open(INFECTED_FILENAME, "w").close() d = radio.receive_full() # get next message from queue #send message radio.send_bytes( ID + "!" if infected else ID) # append ! to ID if we're infected sleep(DELAY_BETWEEN_BROADCASTS) #save data to file if close_contacts and last_data_save + TIME_BETWEEN_DATA_SAVES < time.ticks_ms( ): f = open(DATA_FILENAME, "wb") for contactID, contact in close_contacts.items(): f.write(contactID + contact + "\n") # line format: IIIIFFLL!\n # IIII = ID of other device # FF = initial contact timestampe # LL = last contact timestamp # ! = optional infected indicator # \n end of record f.close()
radio.on() radio.config(length=65) buffer = bytearray(65) display.show(Image.DIAMOND_SMALL) value = 0 counter = 0 while (True): if button_b.was_pressed(): value = value + 1 buffer[1] = value radio.send_bytes(bytes([0, value, 0, 0])) if button_a.was_pressed(): value = value - 1 buffer[1] = value radio.send_bytes(bytes([0, value, 0, 0])) dat = uart.read(33) if dat is not None: uart.write(dat[0:1]) if len(dat) == 33: if (dat[0] == 0): display.clear() radio.send_bytes(dat)
display.set_pixel(x, y, rmp) matrix = Matrix(2, 2) empty_matrix = Matrix(2, 2) guest_matrix = empty_matrix.bytes() radio.on() radio.config(channel=42, queue=10, length=32, data_rate=radio.RATE_2MBIT) failed_count = 0 while True: for num in range(2): if num == 0: matrix.fading() new_pos = get_accelerometer() matrix.set_position(new_pos) radio.send_bytes(matrix.bytes()) message = radio.receive_bytes() if message and len(message) == 25: failed_count = 0 guest_matrix = message else: failed_count += 1 if failed_count == 50: guest_matrix = empty_matrix.bytes() matrix.show_direct(guest_matrix)
################# # Initiate radio, chan, rate_nb = init_radio(RADIO_MODE, CHAN_MIN) # Loop while True: # Update channel and datarate cfg_str, chan, rate_nb = increment_cfg(radio, chan, rate_nb, CHAN_MIN, CHAN_MAX, DATARATES) # Receive packets pkt = radio.receive_bytes() # Display packets if pkt is not None: if RESEND_MODE: print('>> Resent') radio.send_bytes(pkt) pkt_str = read_pkt(pkt, DEST_ADDR_FILTER, EMIT_ADDR_FILTER) if pkt_str: try: if DISPLAY_RAW: print('Raw :\n {} \n {} || {}'.format( pkt, cfg_str, pkt_str)) else: print('{} || {}'.format(cfg_str, pkt_str)) except MemoryError as e: print('Error : packet is too long, couldnt display')
else: sat = 255 elif touch.touchstates[3]: if sat < 254: sat += 1 else: sat = 0 #aim to update state once every 100 miliseconds. if utime.ticks_ms() % 1000 == 0: # remap values to 8 bit ints for transfer - not efficient or accurate... hue = trunc(remap(hue, 0, 360, 0, 255)) sat = trunc(remap(sat, 0, 255, 0, 255)) hsvtuple = (hue, sat) radio.send_bytes(bytes(hsvtuple)) try: hsvtuple = tuple(radio.receive_bytes()) hue = hsvtuple[0] sat = hsvtuple[1] except: pass finally: #bring values back to correct ranges hue = trunc(remap(hue, 0, 255, 0, 360)) rgbw = hsvToRgb(hue, remap(sat, 0, 255, 0, 1), 1) + (0, ) for i in range(0, len(np)): np[i] = rgbw
i2c.read(int(params[1]), int(params[2]), params[3] == 'True').hex()) elif cmd == 'i2c.write': i2c.write(bytes.fromhex(params[1]), params[2] == 'True') confirm() elif cmd == 'radio.on': radio.on() confirm() elif cmd == 'radio.off': radio.off() confirm() elif cmd == 'radio.reset': radio.reset() confirm() elif cmd == 'radio.send_bytes': radio.send_bytes(to_bytes(params[1])) confirm() elif cmd == 'radio.receive_bytes': msg = radio.receive_bytes() print(from_bytes(msg) if msg else '') elif cmd == 'speech.translate': print(escape(speech.translate(unescape(params[1])))) elif cmd == 'speech.pronounce': speech.pronounce(unescape(params[1]), \ pitch=int(params[2]), speed=int(params[3]), \ mouth=int(params[4]), throat=int(params[5])) confirm() elif cmd == 'speech.say': gc.collect() speech.say(unescape(params[1]), \ pitch=int(params[2]), speed=int(params[3]), \
from microbit import * import radio radio.on() while True: radio_msg = radio.receive_bytes() if radio_msg: uart.write(radio_msg) pc_msg = uart.read() if pc_msg: radio.send_bytes(pc_msg)
def send_update(self): msg = "%s" % "".join(self.state) radio.send_bytes(msg)
Message = microbit_read_UART() if Message and wait_4_send == 0: uart.write("ready to send... press button A to transmit, B to clear") uart.write("\r\n") uart.write(Message) # echo while using the FTDI uart.write("\r\n") display.show(Image.BUTTERFLY) wait_4_send = 1 if button_a.is_pressed(): wait_4_send = 2 display.clear() if wait_4_send == 2: # and button_a.was_pressed(): uart.write("... sending") uart.write("\r\n") radio.send_bytes(Message) display.show(Image.HAPPY) sleep(2000) Message = "" display.clear() wait_4_send = 0 if button_b.is_pressed() and wait_4_send == 1: Message = "" uart.write("... message cleared. enter a new one") uart.write("\r\n") display.clear() wait_4_send = 0
for freq in range(1760, 880, -16): music.pitch(freq, 4) # start here radio.on() radio.config(channel=43, queue=10, length=128, power=4, data_rate=radio.RATE_2MBIT) while True: cnt_must_send = cnt_must_send + 1 if must_send == cnt_must_send: radio.send_bytes('flash') cnt_must_send = 0 must_send = random.randint(60000, 180000) # forced flash at random delay # Button A sends a "flash" message. if button_a.was_pressed(): # radio.send_bytes('flash') # a-ha cnt_must_send = 0 display.set_pixel(2, 1, 5) sleep(100) display.set_pixel(2, 1, 0) msg = radio.receive_bytes() if not msg: display.set_pixel(2, 2, 3) else: display.set_pixel(2, 3, 5)
now = running_time() # Shift to the next channel if (now - last_channel_shift) > TIMEOUT and channel_shift_state: last_channel_shift = now channel_i += 1 if channel_i == len(M_CHANNELS): channel_i = 0 radio.config(data_rate=radio.RATE_2MBIT, channel=M_CHANNELS[channel_i]) radio.esb() if create_fake_mouse: radio.send_bytes(b'\xa4\xc2\x00\x00\xfe\xff\xff\x00\x00\x9e') pkt = radio.receive_bytes() if pkt is not None: if pkt[0] == 0x00: print('[+] Receive ACK, sending paket now...') channel_shift_state = False send_attack_state = True sleep(500) del pkt del now del channel_i del last_channel_shift
for freq in range(1760, 880, -16): music.pitch(freq, 4) # start here radio.on() radio.config(channel=43, queue=10, length=128, power=7, data_rate=radio.RATE_2MBIT) while True: cnt_must_send = cnt_must_send + 1 if must_send == cnt_must_send: radio.send_bytes('flash') cnt_must_send = 0 must_send = random.randint(60000, 180000) # forced flash at random delay # Button A sends a "flash" message. if button_a.was_pressed(): # radio.send_bytes('BGDG Zürich was here') display.show(Image.DUCK) cnt_must_send = 0 display.set_pixel(2, 1, 5) sleep(100) display.set_pixel(2, 1, 0) if button_b.was_pressed(): # radio.send_bytes('BMake a break and have a kitkat') display.show(Image.GHOST) cnt_must_send = 0
received_id = received_id[:-1] if rssi > RSSI_THRESHOLD: if received_id in contacts: if contacts[received_id][1] + TIMEOUT < timestamp: contacts[received_id] = (timestamp, timestamp) else: contacts[received_id] = (contacts[received_id][0], timestamp) else: contacts[received_id] = (timestamp, timestamp) if contacts[received_id][1] - contacts[received_id][ 0] > CLOSE_CONTACT_TIME: contactID = received_id + (contacts[received_id][0] // 60000).to_bytes(2, 'big') close_contacts[contactID] = ( contacts[received_id][1] // 60000).to_bytes( 2, 'big') + (b"!" if received_infected else b"") if not infected and received_infected: infected = 1 open(INFECTED_FILENAME, "w").close() d = radio.receive_full() radio.send_bytes(ID + "!" if infected else ID) sleep(DELAY_BETWEEN_BROADCASTS) if close_contacts and last_data_save + TIME_BETWEEN_DATA_SAVES < time.ticks_ms( ): f = open(DATA_FILENAME, "wb") for contactID, contact in close_contacts.items(): f.write(contactID + contact + "\n") f.close() # Created by pyminifier (https://github.com/liftoff/pyminifier)
def send(msg): radio.send_bytes(msg)
def ping(self): """ Sends a ping, which any devices with pongs left will respond to. """ radio.send_bytes(b'ping')