def GetTemperature(sock): now = datetime.datetime.today() foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) try: myfile = open(foldername,'rb') except FileNotFoundError: #if file not present, try previous day's file now = now - datetime.timedelta(days=1) foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) myfile = open(foldername,'rb') ss = MySocket(sock) word = tail(myfile,2) word = word.split(',')[-1] ss.mysend(word.encode('utf_8')) now = datetime.datetime.today() T = float(word)*1000. print("Temperature sent at %s, T = %f mK" % (now.strftime('%y-%m-%d %H:%M:%S'),T)) ss.sock.close()
def GetTemperature(sock): now = datetime.datetime.today() foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) try: myfile = open(foldername, 'rb') except FileNotFoundError: #if file not present, try previous day's file now = now - datetime.timedelta(days=1) foldername = now.strftime('%y-%m-%d') foldername = LOGFOLDER + foldername + '\\CH6 T ' + foldername + '.log' foldername = os.path.normpath(foldername) myfile = open(foldername, 'rb') ss = MySocket(sock) word = tail(myfile, 2) word = word.split(',')[-1] ss.mysend(word.encode('utf_8')) now = datetime.datetime.today() T = float(word) * 1000. print("Temperature sent at %s, T = %f mK" % (now.strftime('%y-%m-%d %H:%M:%S'), T)) ss.sock.close()
client.stdin.write(b + b'\n') client.stdin.flush() from_client.append(b) elif ((action < 0.55 and from_server) or len(from_server) >= MAX_FROM_SERVER): number_to_check = randint(1, len(from_server)) # print('read from server (%s of %s)' % # (number_to_check, len(from_server))) for b in from_server[:number_to_check]: actual = client.stdout.readline() assert actual == b + b'\n' from_server = from_server[number_to_check:] else: # print('send from server') b = generate_random_bytes_line() clientsocket.mysend(get_length_in_network_bytes(b) + b) from_server.append(b) for b in from_server: actual = client.stdout.readline() assert actual == b + b'\n' from_server = [] output, error = client.communicate() expected_output = b'' # .join(line + b'\n' for line in from_server) # print(expected_output) # print(output) assert output == expected_output assert not error assert client.returncode == 0
GPIO.setup(15, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) while True: try: # These three lines are usefull to debug wether to use MSB or LSB in the reading formats # for the first parameter of "hx.set_reading_format("LSB", "MSB")". # Comment the two lines "val = hx.get_weight(5)" and "print val" and uncomment the three lines to see what it prints. #np_arr8_string = hx.get_np_arr8_string() #binary_string = hx.get_binary_string() # print binary_string + " " + np_arr8_string # Prints the weight. Comment if you're debbuging the MSB and LSB issue. if GPIO.input(15) == GPIO.HIGH: hx.tare() print "Tare!" val = hx.get_weight(5) # if val < 0: # val = 0 print val soc.mysend(str(val)) hx.power_down() hx.power_up() time.sleep(0.5) except (KeyboardInterrupt, SystemExit): cleanAndExit()
def main(): # Clear any cached data because both bluez and CoreBluetooth have issues with # caching data and it going stale. mysock = MySocket() if DEBUG: print("Connecting ips socket") # mysock.connect() # mysock.mysend() # i = 0 # while True: # mysock.mysend(str(i)) # i += 1 ble.clear_cached_data() # Get the first available BLE network adapter and make sure it's powered on. adapter = ble.get_default_adapter() adapter.power_on() if DEBUG: print('Using adapter: {0}'.format(adapter.name)) # Disconnect any currently connected UART devices. Good for cleaning up and # starting from a fresh state. if DEBUG: print('Disconnecting any connected UART devices...') UART.disconnect_devices() # Scan for UART devices. if DEBUG: print('Searching for UART device...') try: adapter.start_scan() # Search for the first UART device found (will time out after 60 seconds # but you can specify an optional timeout_sec parameter to change it). device = UART.find_device() if device is None: raise RuntimeError('Failed to find UART device!') finally: # Make sure scanning is stopped before exiting. adapter.stop_scan() print("Connecting to Device") device.connect() # Will time out after 60 seconds, specify timeout_sec parameter # to change the timeout. # Once connected do everything else in a try/finally to make sure the device # is disconnected when done. try: # Wait for service discovery to complete for the UART service. Will # time out after 60 seconds (specify timeout_sec parameter to override). if DEBUG: print('Discovering services...') UART.discover(device) # Once service discovery is complete create an instance of the service # and start interacting with it. uart = UART(device) # Write a string to the TX characteristic. while True: uart.write('T ') # print("Sent 'Hello world!' to the device.") # Now wait up to one minute to receive data from the device. # print('Waiting up to 60 seconds to receive data from the device...') received = uart.read(timeout_sec=60) if received is not None: # Received data, print it out. if (received[0] is 'T'): bin_array = map(bin,bytearray(received)) # print(bin_array) if DEBUG: print("Probe 1: " + str(((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) / 100.0) + "\tProbe 2: " + str(((int(bin_array[3], 2) << 8) + int(bin_array[4], 2)) / 100.0)) mysock.mysend(str((int(bin_array[1], 2) << 8) + int(bin_array[2], 2)) + "," + str((int(bin_array[3], 2) << 8) + int(bin_array[4], 2))) else: # Timeout waiting for data, None is returned. if DEBUG: print('Received no data!') # sleep(1) finally: # Make sure device is disconnected on exit. device.disconnect()
sendall() :TCP recvfrom() :UDP recvfrom_into() :UDP sendto() :UDP ''' HOST = 'localhost' # HOST = '::1' PORT = 9999 ADDR = (HOST, PORT) if __name__ == "__main__": # s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) # s.settimeout(5) # s.connect(ADDR) # print(s.recv(1024).decode('utf-8')) # for data in [b'Tony', b'Nick', b'Ulysses']: # s.send(data) # print(s.recv(1024).decode('utf-8')) # s.send(b'exit') # s.close() s = MySocket() s.connect(HOST, PORT) print(s.myreceive(32).decode('utf-8')) for data in [b'Tony', b'Nick', b'Ulysses']: print(len(data)) s.mysend(data) print(s.myreceive(32).decode('utf-8')) s.mysend(b'exit') s.close()
client.stdin.write(b + b'\n') client.stdin.flush() from_client.append(b) elif ((action < 0.55 and from_server) or len(from_server) >= MAX_FROM_SERVER): number_to_check = randint(1, len(from_server)) # print('read from server (%s of %s)' % # (number_to_check, len(from_server))) for b in from_server[:number_to_check]: actual = client.stdout.readline() assert actual == b + b'\n' from_server = from_server[number_to_check:] else: # print('send from server') b = generate_random_bytes_line() clientsocket.mysend(get_length_in_network_bytes(b) + b) from_server.append(b) for b in from_server: actual = client.stdout.readline() assert actual == b + b'\n' from_server = [] output, error = client.communicate() expected_output = b'' # .join(line + b'\n' for line in from_server) # print(expected_output) # print(output) assert output == expected_output assert not error assert client.returncode == 0
from MaxSubArray import maxSubArraySum if __name__ == "__main__": IP = "chals3.umdctf.io" PORT = 6001 SUFFIX = '\n\n' addtuple = (IP, PORT) # create an INET, STREAMing socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client = MySocket(s) client.connect(IP, PORT) initialMessage = client.myreceive2Suffix(SUFFIX) print("{}\nMessage : {}".format(initialMessage, len(initialMessage))) response = "\n".encode() client.mysend(response) arr = client.myreceive2Suffix(SUFFIX) # Before passing the list along we have to clean the data, # becasue it is a string at this point print("{}\nArray : {}".format(arr, len(arr))) newarr = arr.lstrip("[").rstrip("]\n") listRes = list(newarr.split(", ")) listInts = list(map(int, listRes)) result = maxSubArraySum(listInts, len(listInts)) response = "{}, {}, {}".format(*result).encode() print("Response is: {} ".format(response.decode())) client.mysend(response) flag = client.myreceive() print(flag)