def test_heartbeat_and_challenge(self): file1 = Heartbeat(self.file_path, "mysecret") file1.generate_challenges(10, self.root_seed) challenge = file1.random_challenge() # Create hash_response from seed and duplicate file file2 = Heartbeat(self.file_path2) answer = file2.meet_challenge(challenge) self.assertTrue(file1.check_answer(answer)) # Create hash_answer from seed and edited file file3 = Heartbeat(self.file_path3) answer = file3.meet_challenge(challenge) # This should not match self.assertFalse(file1.check_answer(answer))
def make_kernel(namespace, kernel_factory, out_stream_factory=None, display_hook_factory=None): """ Creates a kernel, redirects stdout/stderr, and installs a display hook and exception handler. """ # If running under pythonw.exe, the interpreter will crash if more than 4KB # of data is written to stdout or stderr. This is a bug that has been with # Python for a very long time; see http://bugs.python.org/issue706263. if sys.executable.endswith('pythonw.exe'): blackhole = file(os.devnull, 'w') sys.stdout = sys.stderr = blackhole sys.__stdout__ = sys.__stderr__ = blackhole # Install minimal exception handling sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', ostream=sys.__stdout__) # Create a context, a session, and the kernel sockets. io.raw_print("Starting the kernel at pid:", os.getpid()) context = zmq.Context() # Uncomment this to try closing the context. # atexit.register(context.close) session = Session(username=u'kernel') reply_socket = context.socket(zmq.XREP) xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep) io.raw_print("XREP Channel on port", xrep_port) pub_socket = context.socket(zmq.PUB) pub_port = bind_port(pub_socket, namespace.ip, namespace.pub) io.raw_print("PUB Channel on port", pub_port) req_socket = context.socket(zmq.XREQ) req_port = bind_port(req_socket, namespace.ip, namespace.req) io.raw_print("REQ Channel on port", req_port) hb = Heartbeat(context, (namespace.ip, namespace.hb)) hb.start() hb_port = hb.port io.raw_print("Heartbeat REP Channel on port", hb_port) # Helper to make it easier to connect to an existing kernel, until we have # single-port connection negotiation fully implemented. io.raw_print("To connect another client to this kernel, use:") io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format( xrep_port, pub_port, req_port, hb_port)) # Redirect input streams and set a display hook. if out_stream_factory: sys.stdout = out_stream_factory(session, pub_socket, u'stdout') sys.stderr = out_stream_factory(session, pub_socket, u'stderr') if display_hook_factory: sys.displayhook = display_hook_factory(session, pub_socket) # Create the kernel. kernel = kernel_factory(session=session, reply_socket=reply_socket, pub_socket=pub_socket, req_socket=req_socket) kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port, req_port=req_port, hb_port=hb_port) return kernel
def make_kernel(namespace, kernel_factory, out_stream_factory=None, display_hook_factory=None): """ Creates a kernel, redirects stdout/stderr, and installs a display hook and exception handler. """ # Re-direct stdout/stderr, if necessary. if namespace.no_stdout or namespace.no_stderr: blackhole = file(os.devnull, 'w') if namespace.no_stdout: sys.stdout = sys.__stdout__ = blackhole if namespace.no_stderr: sys.stderr = sys.__stderr__ = blackhole # Install minimal exception handling sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', ostream=sys.__stdout__) # Create a context, a session, and the kernel sockets. io.raw_print("Starting the kernel at pid:", os.getpid()) context = zmq.Context() # Uncomment this to try closing the context. # atexit.register(context.close) session = Session(username=u'kernel') reply_socket = context.socket(zmq.XREP) xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep) io.raw_print("XREP Channel on port", xrep_port) pub_socket = context.socket(zmq.PUB) pub_port = bind_port(pub_socket, namespace.ip, namespace.pub) io.raw_print("PUB Channel on port", pub_port) req_socket = context.socket(zmq.XREQ) req_port = bind_port(req_socket, namespace.ip, namespace.req) io.raw_print("REQ Channel on port", req_port) hb = Heartbeat(context, (namespace.ip, namespace.hb)) hb.start() hb_port = hb.port io.raw_print("Heartbeat REP Channel on port", hb_port) # Helper to make it easier to connect to an existing kernel, until we have # single-port connection negotiation fully implemented. io.raw_print("To connect another client to this kernel, use:") io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format( xrep_port, pub_port, req_port, hb_port)) # Redirect input streams and set a display hook. if out_stream_factory: sys.stdout = out_stream_factory(session, pub_socket, u'stdout') sys.stderr = out_stream_factory(session, pub_socket, u'stderr') if display_hook_factory: sys.displayhook = display_hook_factory(session, pub_socket) # Create the kernel. kernel = kernel_factory(session=session, reply_socket=reply_socket, pub_socket=pub_socket, req_socket=req_socket) kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port, req_port=req_port, hb_port=hb_port) return kernel
def main(): shared.init() receiver_ev = Event() receiver_ev.set() receiver_thread = SerialReceiver(receiver_ev) heartbeat_ev = Event() heartbeat_ev.set() heartbeat_thread = Heartbeat(heartbeat_ev) time.sleep(2) START = '1' shared.comm.send(START) rcv=shared.comm.receive() print(rcv) with shared.camera: try: receiver_thread.start() heartbeat_thread.start() server = StreamingServer(shared.address, StreamingHandler) print('Server started on port ' + str(shared.address[1])) server.serve_forever() except Exception as err: print(err) finally: heartbeat_ev.clear() heartbeat_thread.join() END = '9' shared.comm.send(END) receiver_ev.clear() receiver_thread.join()
def __init__(self): load_dotenv() self.config = get_envvar_configuration('AMQP') self.heartbeat = Heartbeat(self.config) self.devices = DeviceManager(self.config['DEVICES']['devices'], self.config) loop = asyncio.get_event_loop() loop.run_forever()
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i" % self.hb_port) self.heartbeat.start()
def _run(self): self.is_running = True self._debug('started') self.heartbeat_count = 0 heartbeat = Heartbeat(self._monitor) heartbeat_class = heartbeat.__class__ keep_running = True while keep_running: notifier, msg = self._monitor.notification() if notifier == heartbeat_class: self.heartbeat_count += 1 else: self._debug( 'hb count %d, from %s, received - %s' % (self.heartbeat_count, str(notifier).split('.')[-1], msg)) if msg == self.STOP_COMMAND: keep_running = False elif notifier == self._search_commands.__class__: if msg == SearchCommands.FINISHED_UPDATE_INMATES_STATUS: self._debug('initiate search for new inmates') self._find_new_inmates() elif msg == SearchCommands.FINISHED_FIND_INMATES: self._debug('fetch recently discharged inmate ids') self._recently_discharged_inmates_ids() elif msg == SearchCommands.FINISHED_CHECK_OF_RECENTLY_DISCHARGED_INMATES: self._debug('initiate inmates scraper finish') self._inmate_scraper.finish() else: self._debug( 'Unknown notification from %s, received - %s' % (notifier, msg)) elif notifier == self._inmate_scraper.__class__: self._debug('inmates finish') self._inmates.finish() elif notifier == self._inmates.__class__: keep_running = False elif notifier == self.__class__: if msg == self._START_COMMAND: self._debug('find active inmates') self._active_inmates() elif msg == self._RECEIVED_ACTIVE_IDS_COMMAND: self._debug('update inmates status') self._active_inmate_ids = self._inmates_response self._search_commands.update_inmates_status( self._inmates_response) elif msg == self._RECEIVED_RECENTLY_DISCHARGED_INMATES_IDS_COMMAND: self._debug( 'initiate confirmation search of recently discharged inmates' ) self._search_commands.check_if_really_discharged( self._inmates_response) else: self._debug('Unknown notification from %s, received - %s' % (notifier, msg)) self.is_running = False self._debug('stopped')
def job_heartbeat(): global id heartbeat = Heartbeat(id) t1 = threading.Thread(target=job_heartbeat_failure, args=(heartbeat, )) t1.start() t = threading.Thread(target=expose_function_heartbeat, args=( heartbeat, id, )) t.start() return heartbeat, t, t1
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.transport, self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port) self.heartbeat.start() # Helper to make it easier to connect to an existing kernel. # set log-level to critical, to make sure it is output self.log.critical("To connect another client to this kernel, use:")
def __start_agent(self): server_ip = self.config.get("server","ip") server_port = int(self.config.get("server","port")) sensor_id= self.config.get("agent","id") priority = 1 system_id_file = "" Worker(self.recv_packet_queue,self.send_packet_queue).start() self.server_connection = ServerConn( server_ip, server_port, priority, sensor_id,system_id_file) server_socket = self.server_connection.connect() if server_socket == None : print "connect failed !" exit(0); Sender(self.send_packet_queue,self.server_connection).start() Heartbeat(self.send_packet_queue).start() server_socket.setblocking(False) read_buff = "" print "====" while True: readable, writable, exceptional = select.select([self.server_connection.get_connectsocket()], [], [self.server_connection.get_connectsocket()]) #handle read event try: if server_socket in readable : #construct packet chunk= server_socket.recv(1024*1024) read_buff += chunk read_buff_len = len(read_buff) print read_buff_len while( read_buff_len > 4) : packet, read_buff = self.get_bson_packet(read_buff,read_buff_len) if packet: print "push a packet" self.recv_packet_queue.put(packet) read_buff_len = len(read_buff) else : break except Exception as e: print e for s in exceptional: print "socket --has exceptional"
def _find_missing_inmates(self): self.is_running = True self._debug('find_missing_inmates started') self.heartbeat_count = 0 heartbeat = Heartbeat(self._monitor) heartbeat_class = heartbeat.__class__ keep_running = True while keep_running: notifier, msg = self._monitor.notification() if notifier == heartbeat_class: self.heartbeat_count += 1 else: self._debug( 'hb count %d, from %s, received - %s' % (self.heartbeat_count, str(notifier).split('.')[-1], msg)) if msg == self.STOP_COMMAND: keep_running = False elif notifier == self._search_commands.__class__: if msg == SearchCommands.FINISHED_FIND_INMATES: self._debug('inmates scraper finish') self._inmate_scraper.finish() else: self._debug( 'Unknown notification from %s, received - %s' % (notifier, msg)) elif notifier == self._inmate_scraper.__class__: self._debug('inmates finish') self._inmates.finish() elif notifier == self._inmates.__class__: keep_running = False elif notifier == self.__class__: if msg == self._START_COMMAND: self._debug('find known inmates') self._known_inmates() elif msg == self._RECEIVED_KNOWN_INMATES_COMMAND: self._debug('find missing inmates') self._search_commands.find_inmates( exclude_list=self._inmates_response, start_date=self._start_date_missing_inmates) else: self._debug('Unknown notification from %s, received - %s' % (notifier, msg)) self._start_date_missing_inmates = None self.is_running = False self._debug('find_missing_inmates stopped')
def __init__(self): """ Constructor """ global SVM_PATH self.my_x = 0 self.my_y = 0 self.my_theta = 0 self.other_x = 0 self.other_y = 0 self.other_theta = 0 self.speed = 0 rospy.init_node('g3') self.i2c = I2CHandler() self.vs = VideoStream().start() self.posData = [[-1, -1], [-1, -1], [-1, -1], [-1, -1], [ -1, -1 ]] #-1 represents no data --> from the start no data has received self.followingData = [ -1, -1, -1, -1, -1 ] #-1 represents leader --> from start everyone is the leader self.fanOutData = [-1, -1, -1, -1, -1] #-1 represents no data has received self.laneToGoTo = -1 self.fanOutFlag = False self.foundLaneTime = -1 self.robot_follower = RobotFollower(100, k_p=0.5) #self.serial = SerialHandler('/dev/ttyUSB0', 9600) self.turnC = TurnCheck([640, 480], "segImage.png") #self.gps_other = GpsClient(self.position_callback_other, color='green') self.heartbeat = Heartbeat(self.heartbeat_callback, self.platoon_pos_callback, self.fan_out_callback, self.lane_change_callback) self.gps = GpsClient(self.position_callback) self.image_recognizer = ImageRecognizer(SVM_PATH) self.get_ultrasound() time.sleep(2)
def test_usage(self): beat = Heartbeat() public_beat = beat.get_public() with open('files/test.txt', 'rb') as file: (tag, state) = beat.encode(file) challenge = beat.gen_challenge(state) with open('files/test.txt', 'rb') as file: proof = public_beat.prove(file, challenge, tag) is_valid = beat.verify(proof, challenge, state) if (is_valid): print('file is stored by the server') else: print('file proof invalid') self.assertTrue(is_valid)
def __init__(self, platform): sys_clk_freq = int(75e6) SoCSDRAM.__init__(self, platform, clk_freq=sys_clk_freq, cpu_type="picorv32", integrated_rom_size=0x6000, integrated_sram_size=8192) self.submodules.crg = crg = _CRG(platform, sys_clk_freq) self.submodules.bridge = UARTWishboneBridge(platform.request("dbgserial"), sys_clk_freq, baudrate=115200) self.add_wb_master(self.bridge.wishbone) self.submodules.heartbeat = Heartbeat(sys_clk_freq, 0.5, platform.request("user_led")) self.submodules.j600io = J600IO( platform.request("U600"), platform.request("U601"), platform.request("U604"), platform.request("U605"), None) self.add_wb_slave(mem_decoder(self.mem_map["j600io"]), self.j600io.bus) self.add_memory_region("j600io", self.mem_map["j600io"] | self.shadow_base, 0x10) self.submodules.ethphy = LiteEthPHYRGMII(platform.request("eth_clocks", 1), platform.request("eth", 1)) self.submodules.ethmac = LiteEthMAC(phy=self.ethphy, dw=32, interface="wishbone", endianness=self.cpu.endianness) self.add_wb_slave(mem_decoder(self.mem_map["ethmac"]), self.ethmac.bus) self.add_memory_region("ethmac", self.mem_map["ethmac"] | self.shadow_base, 0x2000) self.ethphy.crg.cd_eth_rx.clk.attr.add("keep") platform.add_period_constraint(self.ethphy.crg.cd_eth_rx.clk, period_ns(75e6)) platform.add_false_path_constraints(crg.cd_sys.clk, self.ethphy.crg.cd_eth_rx.clk) if not self.integrated_main_ram_size: self.submodules.sdrphy = GENSDRPHY(platform.request("sdram")) sdram_module = M12L64322A(sys_clk_freq, "1:1") self.register_sdram(self.sdrphy, sdram_module.geom_settings, sdram_module.timing_settings, controller_settings=ControllerSettings( with_refresh=False))
from heartbeat import Heartbeat from timer import Timer # #class Clock(object): # """Clock class # """ # def __init__(self, name, ) timerDebug = True heartbeat = Heartbeat('basic heart beat') heartbeatTimer = Timer('heartbeat timer', 5, timerDebug) heartbeatTimer.set_repeat(False) heartbeatTimer.set_repeat(True) heartbeatTimer.add_master(heartbeat, 'low-high', 'tick') heartbeatTimer.start() for i in range(50): heartbeat.execute('none') #print heartbeat
from RPi import GPIO import time from settings import Settings from event_publisher import EventPublisher from screen_controller import ScreenController from sound_listener import SoundListener from menu import Menu from heartbeat import Heartbeat from distance_measurer import DistanceMeasurer if __name__ == '__main__': event_publisher = EventPublisher() queue_events = event_publisher.queue Heartbeat('sound-level-detector', event_publisher) screen_controller = ScreenController() DistanceMeasurer(screen_controller).start() sound_listener = SoundListener(Settings.INITIAL_THRESHOLD, Settings.INITIAL_BUFFER_SIZE, queue_events) queue_listen = sound_listener.queue menu = Menu(screen_controller, queue_listen) # initial state menu.update_screen() screen_controller.turn_off_light()
motorController = MotorController(config, gpio, audioManager) alsa = Alsa(gpio, config) servoController = ServoController(gpio, config, audioManager) lightsController = LightsController(gpio, config) tts = TTSSpeaker(config, alsa, audioManager) powerPlant = PowerPlant(config) startupController = StartupSequenceController(config, servoController, lightsController, tts) heartbeat = Heartbeat(config, servoController, motorController, alsa, lightsController, powerPlant) offCharger = OffCharger(config, tts, motorController) janus = ExternalProcess(videoConfig["JanusStartCommand"], False, False, "janus.log") videoStream = ExternalProcess(videoConfig["GStreamerStartCommand"], True, False, "video.log") janusEventHandler = JanusEventHandler() mainApp = web.Application() mainApp.add_routes(routes) mainApp.router.add_static('/js/', path=os.path.join(homePath, 'js')) loop.create_task(start_site(mainApp, '0.0.0.0', 5000, sslctx))
retries=RETRIES, ) logger.debug('creating Composer object') composer = Composer( weather=weather, aircon=aircon, on_threshold=ON_THRESHOLD, off_threshold=OFF_THRESHOLD ) logger.debug('running Composer once to ensure everything works') composer.run() logger.debug('creating Heartbeat object with priority {0}'.format(HA_PRIORITY)) heartbeat = Heartbeat(priority=HA_PRIORITY) heartbeat.start() logger.debug('sleeping for 5 seconds') time.sleep(5) logger.debug('creating BackgroundScheduler object') sched = BackgroundScheduler() sched.start() composer_run_job = None while 1: try: if heartbeat.active and composer_run_job is None: logger.info('going into active')
def run(self): Heartbeat(self._device_id, self._mqtt_publish).start() self._mqtt_client.loop_forever()
def __init__(self, file_path): self.target_file = Heartbeat(file_path, "mysecret")
def __init__(self, file_path, num_challenges, root_seed): self.secret = "mysecret" self.target_file = Heartbeat(file_path, self.secret) self.target_file.generate_challenges(num_challenges, root_seed)
otherSideReceiver=receiverRC_MCU) globalvars.msgConsumers = [ senderPC_MCU, senderMCU_PC, senderMCU_RC, senderRC_MCU, receiverMCU_PC, receiverPC_MCU, receiverRC_MCU, receiverMCU_RC, VolumeOperator(dispatcherOnMCU), WebUI(id=ModuleID.WEBUI_PC, name='WebUI PC', dispatcher=dispatcherOnPC, port=8081), InputConsoleUI(id=ModuleID.UI_CONSOLE, dispatcher=dispatcherOnRC), AnalogSource(dispatcherOnMCU), FileSource(dispatcherOnPC), RadioSource(dispatcherOnPC), CDSource(dispatcherOnPC), Heartbeat(dispatcher=dispatcherOnMCU) ] if globalvars.startSecondWebUI: globalvars.msgConsumers.append( WebUI(id=ModuleID.WEBUI_RC, name='WebUI RC', dispatcher=dispatcherOnRC, port=8082)) globalvars.consumersReadyEvent.set() while True: time.sleep(5) # dispatcherOnPC.printStats() # dispatcherOnMCU.printStats() pass except Exception as e: logging.error(e, exc_info=True)
def test_type(self): b = Heartbeat() self.assertIsInstance(b, heartbeat.Swizzle.Swizzle)
from time import sleep import sys sys.path.append('src') from heartbeat import Heartbeat from pulseDetect import PulseDetect from accumulator import Accumulator from ftpLocalSave import FtpLocalSave from timedCallback import TimedCallback from readSensorDht import ReadSensorDht ## Heartbeat L2B1 = Heartbeat(300) L2B2 = FtpLocalSave() L2B1.connect_output(L2B2) ## Temperature sensor L3B1 = TimedCallback(delay=600) L3B2 = ReadSensorDht('Box_temperature', 21) L3B3 = FtpLocalSave() L3B2.connect_output(L3B3) L3B1.callback = L3B2.read L3B1.start() ## Humidity sensor L4B1 = TimedCallback(delay=600) L4B2 = ReadSensorDht('Box_humidity', 21, read_humid=True) L4B3 = FtpLocalSave() L4B2.connect_output(L4B3) L4B1.callback = L4B2.read L4B1.start()
class Securities_Factorty: def const_etf(ts_code, heartbeat): secObj = Fund(ts_code=ts_code, heartbeat=heartbeat, tags='etf') if secObj.anchor_tscode is not None: anchorObj = Indice(secObj.anchor_tscode, secObj._heartbeat) secObj.anchorObj = anchorObj else: # if no underlying instrument, then use the ETF itself as the underlying instrument secObj.anchorObj = secObj return secObj if __name__ == '__main__': from heartbeat import Heartbeat # dpc.init() hb = Heartbeat() # hb = Heartbeat(startend={'start':'20180811', 'end':'20201231', 'freq':'1y'}) # etf = Securities_Factorty.const_etf(ts_code='159915.SZ',heartbeat=hb) # print(etf.anchorObj.sec_name) idx = Indice(ts_code='399001.SZ', heartbeat=hb) fnd = Fund(ts_code='159915.SZ', heartbeat=hb) idx.generate_kchart(MA=[5, 10, 21], renderfile=True) fnd.generate_mchart(lst_tscode=['000001.SH'], lst_macro=[ 'shibor.1w', 'pimon.nt_yoy', 'pimon.ppi_yoy', 'pimon.m1_yoy', 'pimon.m2_yoy', 'pimon.allstock_circ_mv_sum' ], lst_findmedian=['pe', ()], renderfile=True)
config.read(os.path.join(homePath, "rover.conf")) audioConfig = config["AUDIO"] videoConfig = config["VIDEO"] loop = asyncio.get_event_loop() loop.set_exception_handler(loopExceptionHandler) motorController = MotorController(config) alsa = Alsa(config) servoController = ServoController(config) tts = TTSSpeaker(config, alsa) heartbeat = Heartbeat(config, servoController, motorController, alsa) heartbeat.start() janus = ExternalProcess(videoConfig["JanusStartCommand"], False, False, "janus.log") videoStream = ExternalProcess(videoConfig["GStreamerStartCommand"], True, False, "video.log") audioStream = ExternalProcess(audioConfig["GStreamerStartCommand"], True, False, "audio.log") audioSink = ExternalProcess(audioConfig["AudioSinkCommand"], True, True, "audiosink.log") janusMonitor = JanusMonitor() janusMonitor.start() app = web.Application()
from config import Config from display import Display from ewh_net import Network from heartbeat import Heartbeat from name import Name from mqtt import MQTT from task import Scheduler import ntptime network = Network() MQTT.init(network) board = Board(network) board.init() heartbeat = Heartbeat(board.display) scheduler = Scheduler() config = Config(board, network, scheduler) name = Name(config, board.display) scheduler.register(board.display) scheduler.register(heartbeat) scheduler.register(network) scheduler.register(MQTT.task) print("Starting scheduler of version {0}".format(config.version)) scheduler.start(100)
def __init__(self, client_id, server_host, server_port, mc_address, mc_port, send_interval=5, chunk_size=10000000, file_size=10000000 * 2, run_time=30, test_path='./', dd_method=False): """ :param client_id: string, unique id for the client :param server_host: string, ip address/hostname for sever :param server_host: string, port server will listen on :param mc_address: string, multicast group address to publish heartbeat :param mc_port: int, port for multicast group :param send_interval: int, heartbeat send interval :param chunk_size: int, in bytes, the size to data size to write to a file at a time :param file_size: int, maximum file size for the writer :param run_time: int, self explanatory, ya know :param test_path: string, path to write the data files :param dd_method: bool, use dd or not for the file writing """ self.client_id = client_id self.server_host = server_host self.chunk_size = chunk_size self.file_size = file_size self.run_time = run_time self.mc_group = mc_address, mc_port self.send_interval = send_interval self.test_path = test_path # if dd_method is True, dd will be used # if dd_method is False, python file object will be used self.dd_method = dd_method logging.basicConfig(filename=client_id + '.log', format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO) # Unsure on requirements, going to assume worst case # Need to check to see if the chunk size and # run time will allow two instances of the time to be written try: # check to see if two chunks can be written to the file assert self.file_size / self.chunk_size >= 2 except AssertionError: print "Client chunk size is too small for max file size." \ "Please reconfigure" exit(1) # Create the initial TCP connection self.tcp = TCPClient((server_host, server_port)) self.hb1 = Heartbeat(self.mc_group[0], self.mc_group[1], self.client_id, self.send_interval) self.kill_sig = Queue(1) self.hb_process = Process(target=self.hb1.run, args=(self.kill_sig, )) self.hb_process.daemon = True self.queue1 = Queue() dw1 = DataWriter(self.chunk_size, self.file_size, self.dd_method, self.test_path) self.dw_process = Process(target=dw1.run, args=(self.queue1, self.kill_sig)) self.dw_process.daemon = True self.dw_process_pid = None
from heartbeat import Heartbeat from time import sleep a = Heartbeat("192.168.1.40", 5432) while True: sleep(1)
def num_challenges(number): file1 = Heartbeat(self.size_path, "mysecret") file1.generate_challenges(number, self.root_seed)