def request_license(system_stub, id=None): if id == None: id = system_stub.GetLicenseInfo(common_pb2.Empty()).requestId assert id.encode("utf-8") != '', "no old id avaliable, provide your email" requestMachineId = system_stub.GetLicenseInfo(common_pb2.Empty()).requestMachineId body = {"id": id.encode("utf-8"), "machine_id": json.loads(requestMachineId)} resp_request = requests.post('https://www.beamylabs.com/requestlicense', json = {"licensejsonb64": base64.b64encode(json.dumps(body))}) assert resp_request.status_code == requests.codes.ok, "Response code not ok, code: %d" % (resp_request.status_code) print("License requested check your mail: ", id)
def run(): channel = grpc.insecure_channel('localhost:50051') stub = camera_pb2_grpc.ControllerStub(channel) msg = common_pb2.Empty() print("-----------Get Conf----------") res = stub.GetConf(msg) print(res) print("-----------Get State----------") state = stub.GetState(msg) print(state) print("-----------Turn Off----------") state.base.mode = common_pb2.BasicMutableState.Mode.Value('OFF') res = stub.SetState(state) print(res) time.sleep(5) print("-----------SHARING----------") state.base.mode = common_pb2.BasicMutableState.Mode.Value('SHARING') res = stub.SetState(state) print(res) time.sleep(5) print("-----------LocalSaving----------") state.base.mode = common_pb2.BasicMutableState.Mode.Value('LOCAL_SAVING') res = stub.SetState(state) print(res)
def run(): channel = grpc.insecure_channel('127.0.0.1:50051') network_stub = network_api_pb2_grpc.NetworkServiceStub(channel) system_stub = system_api_pb2_grpc.SystemServiceStub(channel) check_license(system_stub) # request_license(system_stub) # download_and_install_license(system_stub, "your_emailed_hash_without_quotes") upload_folder(system_stub, "configuration_udp") # upload_folder(system_stub, "configuration") reload_configuration(system_stub) # list available signals configuration = system_stub.GetConfiguration(common_pb2.Empty()) for networkInfo in configuration.networkInfo: print("signals in namespace ", networkInfo.namespace.name, system_stub.ListSignals(networkInfo.namespace)) ecu_A_thread = Thread(target = ecu_A, args = (network_stub, 1,)) ecu_A_thread.start() ecu_B_thread_read = Thread(target = ecu_B_read, args = (network_stub, 1,)) ecu_B_thread_read.start() ecu_B_thread_subscribe = Thread(target = ecu_B_subscribe, args = (network_stub,)) ecu_B_thread_subscribe.start() ecu_B_thread_subscribe_2 = Thread(target = ecu_B_subscribe_2, args = (network_stub,)) ecu_B_thread_subscribe_2.start() read_signals = [common_pb2.SignalId(name="counter", namespace=common_pb2.NameSpace(name = "ecu_A")), common_pb2.SignalId(name="TestFr06_Child02", namespace=common_pb2.NameSpace(name = "ecu_A"))] ecu_read_demo = Thread(target = read_on_timer, args = (network_stub, read_signals, 10)) ecu_read_demo.start()
def RunJob(self, request, context): self._logger.debug('Received run job request from server') jobs = [] for job_description in request.job_descriptions: jobs.append(job.Job.from_proto(job_description)) run_job_callback = self._callbacks['RunJob'] run_job_callback(jobs, request.worker_id, request.round_id) return common_pb2.Empty()
def run(): channel = grpc.insecure_channel('10.42.0.100:20000') stub = lidar_pb2_grpc.ControllerStub(channel) msg = common_pb2.Empty() print("-----------Get Conf----------") res = stub.GetConf(msg) print(res) print("-----------Get State----------") state = stub.GetState(msg) print(state)
def download_and_install_license(system_stub, hash_without_dashes, id=None): if id == None: id = system_stub.GetLicenseInfo(common_pb2.Empty()).requestId assert id.encode("utf-8") != '', "no old id avaliable, provide your email" resp_fetch = requests.post('https://www.beamylabs.com/fetchlicense', json = {"id": id, "hash": hash_without_dashes}) assert resp_fetch.status_code == requests.codes.ok, "Response code not ok, code: %d" % (resp_fetch.status_code) license_info = resp_fetch.json() license_bytes = license_info['license_data'].encode('utf-8') # you agree to license and conditions found here https://www.beamylabs.com/license/ system_stub.SetLicense(system_api_pb2.License(termsAgreement = True, data = license_bytes))
def Shutdown(self, request, context): # Handle any custom cleanup in the scheduler. shutdown_callback = self._callbacks['Shutdown'] shutdown_callback() # Indicate to the worker server that a shutdown RPC has been received. self._condition.acquire() self._condition.notify() self._condition.release() return common_pb2.Empty()
def __init__( self, channel, user_auth, verifier, is_private_account=False, validate=True): if validate: assert verifier is not None assert isinstance(verifier, EcdsaVerifier) self.user_auth = user_auth self.verifier = verifier # gateway verifier self.validate = validate self.is_private_account = is_private_account self.empty = common_pb2.Empty() self.stub = neutralservices_pb2_grpc.UserGatewayStub(channel)
def main(): market_channel = grpc.insecure_channel('113.208.112.25:57600') market_stub = broker_pb2_grpc.MarketDataStub(market_channel) pool = Pool(processes=200) broker = Broker(25, 'qWC6G7nao', '113.208.112.25:57502') data = market_stub.subscribe(common_pb2.Empty()) try: i = 0 for item in data: # print('before') all_instrument_dict = instrument_parser( item, ['A001.PSE', 'A002.PSE', 'B001.PSE', 'B002.PSE']) for sym in ['A001.PSE', 'A002.PSE', 'B001.PSE', 'B002.PSE']: long_points_ave[sym].append( all_instrument_dict[sym]['deliver_price']) short_points_ave[sym].append( all_instrument_dict[sym]['deliver_price']) if i % 15 == 14: # print('in') account_detail = position_order_parser(broker.GET_TRADER()) tasks = [] for ticker in ['A001.PSE', 'A002.PSE', 'B001.PSE', 'B002.PSE']: long_ave = np.mean(long_points_ave[ticker]) short_ave = np.mean(short_points_ave[ticker]) tasks.extend( task_generator(account_detail, all_instrument_dict, ticker, long_ave, short_ave)) t0 = time.time() print(len(tasks)) if not tasks: pass else: results = pool.map_async(order_on_task, tasks) results.wait(timeout=1.5) # pool.close() print(time.time() - t0) print(account_detail['time_stamp']) i += 1 # print('out') except KeyboardInterrupt: print('Program stop by keyboardinterupt')
def __init__(self, system_stub): self._sinfos = {} self._virtual = [] self._networks = {} namespaces = [] conf = system_stub.GetConfiguration(common_pb2.Empty()) for ninfo in conf.networkInfo: namespaces.append(ninfo.namespace) if ninfo.type == "virtual": self._virtual.append(ninfo.namespace.name) for namespace in namespaces: res = system_stub.ListSignals(namespace) self._addframes(namespace, res) for finfo in res.frame: self._add(finfo.signalInfo) for sinfo in finfo.childInfo: self._add(sinfo)
def run(): channel = grpc.insecure_channel('localhost:50051') secret = common_pb2.TaskSecret(task_name='radar_task', task_id='radar_task_id') metadata = (('task-secret-bin', secret.SerializeToString()), ) stub = radar_pb2_grpc.ControllerStub(channel) msg = common_pb2.Empty() print("-----------Get Conf----------") res = stub.GetConf(msg) print(res) print("-----------Get State----------") state = stub.GetState(msg) print(state) # print("-----------Turn Off----------") # state.base.mode = common_pb2.BasicMutableState.Mode.Value('OFF') # res = stub.SetState(state) # print(res) print("-----------SHARING----------") print(metadata) state.base.mode = common_pb2.BasicMutableState.Mode.Value('SHARING') res = stub.SetState(state, metadata=metadata) print(res) print("-----------LocalSaving----------") state.base.mode = common_pb2.BasicMutableState.Mode.Value('LOCAL_SAVING') res = stub.SetState(state) print(res) print("-----------Change Mode----------") state.base.mode = common_pb2.BasicMutableState.Mode.Value('SHARING') state.current_mode = "OUTDOOR" res = stub.SetState(state) print(res) print("-----------Write Manual Cfg-----------") manual_cfg = "sensorStop\nflushCfg\nsensorStart\n" cfg_object = radar_pb2.LadarCfg() cfg_object.data = manual_cfg res = stub.SetManualCfg(cfg_object) print(res)
def Done(self, request, context): done_callback = self._callbacks['Done'] try: if len(request.job_id) > 1: job_id = JobIdPair(request.job_id[0], request.job_id[1]) else: job_id = JobIdPair(request.job_id[0], None) self._logger.info('Received completion notification: ' 'Job ID: {job_id}, Worker ID: {worker_id}, ' 'Num steps: {num_steps}, ' 'Execution time: {execution_time}'.format( job_id=job_id, worker_id=request.worker_id, num_steps=str(request.num_steps), execution_time=str(request.execution_time))) done_callback(job_id, request.worker_id, request.num_steps, request.execution_time, request.iterator_log) except Exception as e: self._logger.error('Could not process completion ' 'notification for job {0}'.format(job_id)) traceback.print_exc() return common_pb2.Empty()
def check_license(system_stub): status = system_stub.GetLicenseInfo(common_pb2.Empty()).status assert status == system_api_pb2.LicenseStatus.VALID, ( "Check your license, status is: %d" % status)
def reload_configuration(system_stub): request = common_pb2.Empty() response = system_stub.ReloadConfiguration(request, timeout=60000) print(response)
def Subscribe(self): b = Broker() #b.Register() #b.Info() i = 0 A000 = [] for response in self.stub.subscribe(common_pb2.Empty()): # print(response.instruments) i += 1 if i > 100: break for ins in response.instruments: # print('ok') symbol = ins.symbol last_price = ins.last_price # volume = ins.traded_volume # deliver = ins.deliver_price if symbol == 'A001.PSE': A000.append(last_price) if symbol == 'A000.PSE' or symbol == 'B000.PSE': continue # print('================BID {} at price {}'.format(symbol, last_price)) ret = b.NewOrder(side='BID', symbol=symbol, volume=100, price=last_price - 0.01, is_market=False, pos_type='LONG') if ret.result_code == 0: ret = b.NewOrder(side='ASK', symbol=symbol, volume=100, price=last_price + 0.01, is_market=False, pos_type='LONG') # if ret.result_code == 260: # print('BID ' + symbol + ' SHORT ************************************') # if ret.result_code == 0: # print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') # for rec in ret.market_records: # print(rec.symbol) # print(rec.percent) # print('================ASK {} at price {}'.format(symbol, last_price)) ret = b.NewOrder(side='ASK', symbol=symbol, volume=100, price=last_price - 0.01, is_market=False, pos_type='SHORT') if ret.result_code == 0: ret = b.NewOrder(side='BID', symbol=symbol, volume=100, price=last_price + 0.01, is_market=False, pos_type='SHORT') # if ret.result_code == 260: # print('ASK ' + symbol + ' SHORT ************************************') # if ret.result_code == 0: # print('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') # for rec in ret.market_records: # print(rec.symbol) # print(rec.percent) # time.sleep(1) b.GetTrader() return A000
def ListInstruments(self): ret = self.stub.list_instruments(common_pb2.Empty()) for instrument in ret.instruments: print(instrument)
def Info(self): ret = self.stub.info(common_pb2.Empty()) print(ret) return ret
def KillJob(self, request, context): self._logger.debug('Received kill job request from server') kill_job_callback = self._callbacks['KillJob'] kill_job_callback(request.job_id) return common_pb2.Empty()
def run(ip, port): """Main function, checking arguments passed to script, setting up stubs, configuration and starting Threads.""" # Setting up stubs and configuration channel = grpc.insecure_channel(ip + ":" + port) network_stub = network_api_pb2_grpc.NetworkServiceStub(channel) system_stub = system_api_pb2_grpc.SystemServiceStub(channel) check_license(system_stub) upload_folder(system_stub, "configuration_udp") # upload_folder(system_stub, "configuration_lin") # upload_folder(system_stub, "configuration_can") # upload_folder(system_stub, "configuration_canfd") reload_configuration(system_stub) global signal_creator signal_creator = SignalCreator(system_stub) # Lists available signals configuration = system_stub.GetConfiguration(common_pb2.Empty()) for networkInfo in configuration.networkInfo: print( "signals in namespace ", networkInfo.namespace.name, system_stub.ListSignals(networkInfo.namespace), ) # Starting Threads # ecu b, we do this with lambda refering to double_and_publish. ecu_b_client_id = common_pb2.ClientId(id="id_ecu_B") ecu_B_sub_thread = Thread( target=act_on_signal, args=( ecu_b_client_id, network_stub, [ signal_creator.signal("counter", "ecu_B"), # here you can add any signal from any namespace # signal_creator.signal("TestFr04", "ecu_B"), ], True, # True: only report when signal changes lambda signals: double_and_publish( network_stub, ecu_b_client_id, signal_creator.signal("counter", "ecu_B"), signals, ), lambda subscripton: (q.put(("id_ecu_B", subscripton))), ), ) ecu_B_sub_thread.start() # wait for subscription to settle ecu, subscription = q.get() # ecu a, this is where we publish, and ecu_A_thread = Thread( target=ecu_A, args=( network_stub, 1, ), ) ecu_A_thread.start() # ecu b, bonus, periodically, read using timer. signals = [ signal_creator.signal("counter", "ecu_B"), # add any number of signals from any namespace # signal_creator.signal("TestFr04", "ecu_B"), ] ecu_read_on_timer = Thread(target=read_on_timer, args=(network_stub, signals, 1)) ecu_read_on_timer.start()
def metrics(): """Agent execution function""" # tags definition registry = CollectorRegistry(auto_describe=False) service_status = Gauge("Node_Get_ServiceStatus", SERVICE_STATUS_TITLE, ["NodeIP", "NodePort"], registry=registry) genesis_block_details = Gauge("Node_Get_GenesisBlockNumberDetails", GENESIS_BLOCK_DETAILS_TITLE, ["NodeIP", "NodePort", "GenesisBlockNumberHash"], registry=registry) chain_info = Gauge("Node_Get_ChainInfo", CHAIN_INFO_TITLE, ["NodeIP", "NodePort", "ChainName", "Operator", "TokenName", "TokenSymbol", "Version"], registry=registry) node_peers = Gauge("Node_Get_NodePeers", NODE_PEERS_TITLE, ["NodeIP", "NodePort"], registry=registry) chain_nodes = Gauge("Node_Get_ChainNodes", CHAIN_NODES_TITLE, ["NodeIP", "NodePort"], registry=registry) last_block_number = Gauge("Node_Get_LastBlockNumber", LAST_BLOCK_NUMBER_TITLE, ["NodeIP", "NodePort", "GenesisBlockNumberHash", "NodeID", "NodeAddress"], registry=registry) check_proposer = Gauge("Node_CheckProposer", CHECK_PROPOSER_TITLE, ["NodeIP", "NodePort"], registry=registry) last_block_details = Gauge("Node_Get_LastBlockNumberDetails", LAST_BLOCK_DETAILS_TITLE, ["NodeIP", "NodePort", "LastBlocknumber", "LastBlockProposer", "LastBlockHash", "NodeID", "HostPlatform", "HostName", "ConsensusStatus", "SoftVersion"], registry=registry) vote_node = Gauge("Node_Get_VoteNode", VOTE_NODE_TITLE, ["NodeIP", "NodePort", "NodeID", "Voter"], registry=registry) block_height_difference = Gauge("Node_Get_BlockDifference", BLOCK_HEIGHT_DIFFERENCE_TITLE, ["NodeIP", "NodePort", "CurrentHeight", "PreviousHeight"], registry=registry) block_interval = Gauge("Node_Get_BlockTimeDifference", BLOCK_INTERVAL_TITLE, ["NodeIP", "NodePort"], registry=registry) last_block_transactions = Gauge("Node_Get_LastBlockNumberTransactions", LAST_BLOCK_TRANSACTIONS_TITLE, ["NodeIP", "NodePort"], registry=registry) last_block_quota_used = Gauge("Node_Get_LastBlockNumberQuotaUsed", LAST_BLOCK_QUOTA_USED_TITLE, ["NodeIP", "NodePort"], registry=registry) chain_quota_price = Gauge("Node_Get_QuotaPrice", CHAIN_QUOTA_PRICE_TITLE, ["NodeIP", "NodePort"], registry=registry) block_quota_limit = Gauge("Node_Get_BlockQuotaLimit", BLOCK_QUOTA_LIMIT_TITLE, ["NodeIP", "NodePort"], registry=registry) local_voter = Gauge("Node_Get_LocalVoter", LOCAL_VOTE_TITLE, ["NodeIP", "NodePort"], registry=registry) vote_number = Gauge("Block_Vote_Number", BLOCK_VOTE_NUMBER_TITLE, ["NodeIP", "NodePort"], registry=registry) # run exporter grpc_wrapper = GrpcWrapper(GRPC_HOST, GRPC_PORT) node_address = grpc_wrapper.get_node_address() logger.debug("Node Address: %s" % (node_address)) ## Exporter Status service_status.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(1) ## Genesis Block genesis_block_info = grpc_wrapper.GetBlockByNumber(0) genesis_block_hash = base64.b64decode(genesis_block_info['header']['prevhash']).hex() genesis_block_time = genesis_block_info['header']['timestamp'] genesis_block_details.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, GenesisBlockNumberHash=genesis_block_hash).set(genesis_block_time) logger.debug("Genesis Block - Hash: %s, Time: %s" % (genesis_block_hash, genesis_block_time)) ## Last Block block_number_info = grpc_wrapper.block_number() last_block_number_int = int(block_number_info["blockNumber"]) prev_block_number_int = last_block_number_int - 1 last_block_number.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, NodeID=node_address, GenesisBlockNumberHash=genesis_block_hash, NodeAddress=node_address).set(last_block_number_int) logger.debug("Block Number - Last: %s, Previous: %s" % (last_block_number_int, prev_block_number_int)) ## Metadata metadata_info = grpc_wrapper.metadata() chain_name = None # TODO metadata_info['chainName'] operator = None # TODO metadata_info['operator'] token_name = None # TODO metadata_info['tokenName'] token_symbol = None # TODO metadata_info['tokenSymbol'] economical_model = 0 # TODO metadata_info['economicalModel'] chain_version = metadata_info['version'] chain_info.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, ChainName=chain_name, Operator=operator, TokenName=token_name, TokenSymbol=token_symbol, Version=chain_version).set(economical_model) ## Chain Nodes consensus_node_list = [ base64.b64decode(validator).hex() for validator in metadata_info['validators']] consensus_node_count = len(consensus_node_list) chain_nodes.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(consensus_node_count) ## block_info = grpc_wrapper.GetBlockByNumber(last_block_number_int) previous_block_info = grpc_wrapper.GetBlockByNumber(prev_block_number_int) block_head_info = block_info['header'] block_commits = [] # TODO list(block_info['header']['proof']['Bft']['commits'].keys()) consensus_nodes_count = len(consensus_node_list) for i in range(consensus_nodes_count): voter_address = consensus_node_list[i] vote_status = 1 if voter_address in block_commits else 0 vote_node.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, NodeID=node_address, Voter=voter_address).set(vote_status) is_committer = 1 if node_address in block_commits else 0 local_voter.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(is_committer) block_vote_number = len(block_commits) vote_number.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(block_vote_number) logger.debug("Vote Number - block_vote_number: %s " % (block_vote_number)) last_block_hash_base64 = grpc_wrapper.cli_request("GetBlockHash", CitaCloudController.BlockNumber(block_number=last_block_number_int))['hash'] last_block_hash = base64.b64decode(last_block_hash_base64).hex() block_time = int(block_head_info['timestamp']) block_proposer = base64.b64decode(block_head_info['proposer']).hex() previous_block_time = int(previous_block_info['header']['timestamp']) consensus = 1 if node_address in consensus_node_list else 0 node_software_version=grpc_wrapper.cli_request("GetVersion", common.Empty())["version"] last_block_details.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, NodeID=node_address, LastBlocknumber=last_block_number_int, LastBlockProposer=block_proposer, LastBlockHash=last_block_hash, HostPlatform=EXPORTER_PLATFORM, HostName=AGENT_NAME, ConsensusStatus=consensus, SoftVersion=node_software_version).set(block_time) logger.debug("Last Block Details - Last Block Hash: %s " % (last_block_hash)) interval = abs(block_time - previous_block_time) block_height_difference.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT, CurrentHeight=last_block_number_int, PreviousHeight=prev_block_number_int).set(interval) block_interval.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(interval) ## Last Block Transactions block_transactions = len(block_info.get('body').get('txHashes')) last_block_transactions.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(block_transactions) ## Last Block Quota Used if block_head_info.get('quotaUsed'): block_quota_used = int(block_head_info['quotaUsed'], 16) else: block_quota_used = 0 # TODO int(block_head_info['gasUsed'], 16) #Get the previous version of CITA v0.19.1 gasUsed last_block_quota_used.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(block_quota_used) ## Check Proposer proposer = 1 if node_address == block_proposer else 0 check_proposer.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(proposer) logger.debug("CheckProposer - Node Address: %s, Block Proposer: %s" % (node_address, block_proposer)) # Peer Info peer_count = grpc_wrapper.cli_request("GetPeerCount", common.Empty())["peerCount"] node_peers.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(peer_count) ## Quota Price # quota_price = grpc_wrapper.quota_price() # price = quota_price # chain_quota_price.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(int(price, 16)) ## Block Limit # block_limit = grpc_wrapper.block_limit() # limit = block_limit # block_quota_limit.labels(NodeIP=GRPC_HOST, NodePort=GRPC_PORT).set(int(limit, 16)) # Response return Response(prometheus_client.generate_latest(registry), mimetype="text/plain")
# main if __name__ == "__main__": # parse command line arguments. parser = argparse.ArgumentParser() parser.add_argument("--exporter-host", default="0.0.0.0", help="Exporter listen address") parser.add_argument("--exporter-port", default="9349", help="Exporter listen port") parser.add_argument("--node-grpc-host", required=True, help="CITA Cloud Node gRPC host") parser.add_argument("--node-grpc-port", required=True, help="CITA Cloud Node gRPC port") parser.add_argument("--node-data-folder", required=True, help="CITA Cloud Node Data Folder") args = parser.parse_args() # initialize global params EXPORTER_HOST = args.exporter_host EXPORTER_PORT = args.exporter_port GRPC_HOST = args.node_grpc_host GRPC_PORT = args.node_grpc_port NODE_DATA_FOLDER = args.node_data_folder # for debugging channel = grpc.insecure_channel("%s:%s" % (GRPC_HOST, GRPC_PORT)) stub = CitaCloudControllerGrpc.RPCServiceStub(channel) response = stub.GetSystemConfig(common.Empty()) json_object = MessageToJson(response, including_default_value_fields=True) print(json_object) # start the exporter NODE_FLASK.run(host=EXPORTER_HOST, port=EXPORTER_PORT)
def Reset(self, request, context): reset_callback = self._callbacks['Reset'] reset_callback() return common_pb2.Empty()
def run(argv): """Main function, checking arguments passed to script, setting up stubs, configuration and starting Threads. Parameters ---------- argv : list Arguments passed when starting script """ global ip global port global playbacklist # Checks argument passed to script, playback.py will use below ip-address if no argument is passed to the script ip = "127.0.0.1" # Keep this port port = ":50051" try: opts, args = getopt.getopt(argv, "h", ["ip="]) except getopt.GetoptError: print("Usage: playback.py --ip <ip_address>") sys.exit(2) for opt, arg in opts: if opt == "-h": print("Usage: playback.py --ip <ip_address>") sys.exit(2) elif opt == "--ip": ip = arg # To do a clean exit of the script on CTRL+C signal.signal(signal.SIGINT, exit_handler) # Setting up stubs and configuration channel = grpc.insecure_channel(ip + port) network_stub = network_api_pb2_grpc.NetworkServiceStub(channel) traffic_stub = traffic_api_pb2_grpc.TrafficServiceStub(channel) system_stub = system_api_pb2_grpc.SystemServiceStub(channel) # check_license(system_stub) upload_folder(system_stub, "configuration_custom_udp") reload_configuration(system_stub) # Give us some time to see it all went according to plan time.sleep(1) # Lists available signals configuration = system_stub.GetConfiguration(common_pb2.Empty()) for networkInfo in configuration.networkInfo: print( "signals in namespace ", networkInfo.namespace.name, system_stub.ListSignals(networkInfo.namespace), ) # Optonally start threads # ecu_B_thread_subscribe = Thread(target=ecu_B_subscribe_, args=(network_stub,)) # ecu_B_thread_subscribe.start() # ecu_B_thread_read = Thread( # target=ecu_B_read, # args=( # network_stub, # 1, # ), # ) # ecu_B_thread_read.start() upload_file( system_stub, "recordings/traffic.log", "recordings/candump_uploaded.log", ) recordlist = [ { "namespace": "custom_can", "path": "recordings/candump_uploaded_recorded.log", "mode": traffic_api_pb2.Mode.RECORD, }, ] status_record = traffic_stub.PlayTraffic( traffic_api_pb2.PlaybackInfos( playbackInfo=list(map(create_playback_config, recordlist)))) print("record traffic result is ", status_record) playbacklist = [ { "namespace": "custom_can", "path": "recordings/candump_uploaded.log", "mode": traffic_api_pb2.Mode.PLAY, }, { "namespace": "ecu_A", "path": "recordings/candump.log", "mode": traffic_api_pb2.Mode.PLAY, }, { "namespace": "ecu_C", "path": "recordings/candump_.log", "mode": traffic_api_pb2.Mode.PLAY, }, ] # expect candump_.log does not exist, thus error string will be returned status = traffic_stub.PlayTraffic( traffic_api_pb2.PlaybackInfos( playbackInfo=list(map(create_playback_config, playbacklist)))) print("play traffic result is ", status) time.sleep(5) recordlist = [ { "namespace": "custom_can", "path": "recordings/candump_uploaded_recorded.log", "mode": traffic_api_pb2.Mode.STOP, }, ] status_record = traffic_stub.PlayTraffic( traffic_api_pb2.PlaybackInfos( playbackInfo=list(map(create_playback_config, recordlist)))) # now stop recording and download the recorded file download_file( system_stub, "recordings/candump_uploaded_recorded.log", "candump_uploaded_recorded_downloaded.log", ) print("file is now downloaded")
def run(argv): """Main function, checking arguments passed to script, setting up stubs, configuration and starting Threads. Parameters ---------- argv : list Arguments passed when starting script """ # Checks argument passed to script, ecu.py will use below ip-address if no argument is passed to the script ip = "127.0.0.1" # Keep this port port = ":50051" try: opts, args = getopt.getopt(argv, "h", ["ip="]) except getopt.GetoptError: print("Usage: ecu.py --ip <ip_address>") sys.exit(2) for opt, arg in opts: if opt == "-h": print("Usage: ecu.py --ip <ip_address>") sys.exit(2) elif opt == "--ip": ip = arg # Setting up stubs and configuration channel = grpc.insecure_channel(ip + port) network_stub = network_api_pb2_grpc.NetworkServiceStub(channel) system_stub = system_api_pb2_grpc.SystemServiceStub(channel) check_license(system_stub) upload_folder(system_stub, "configuration_udp") # upload_folder(system_stub, "configuration_lin") # upload_folder(system_stub, "configuration_can") reload_configuration(system_stub) # Lists available signals configuration = system_stub.GetConfiguration(common_pb2.Empty()) for networkInfo in configuration.networkInfo: print( "signals in namespace ", networkInfo.namespace.name, system_stub.ListSignals(networkInfo.namespace), ) # Starting Threads ecu_A_thread = Thread( target=ecu_A, args=( network_stub, 1, ), ) ecu_A_thread.start() ecu_B_thread_read = Thread( target=ecu_B_read, args=( network_stub, 1, ), ) ecu_B_thread_read.start() ecu_B_thread_subscribe = Thread(target=ecu_B_subscribe, args=(network_stub, )) ecu_B_thread_subscribe.start()
def shutdown(self): with grpc.insecure_channel(self._server_loc) as channel: stub = s2w_pb2_grpc.SchedulerToWorkerStub(channel) response = stub.Shutdown(common_pb2.Empty())
def metadata(self): """Get metadate""" return self.cli_request("GetSystemConfig", common.Empty())
def Subscribe(self): print('-----------------Subscribe-----------------------') for response in self.stub.subscribe(common_pb2.Empty()): print(response) print('-------------------------------------------------')
def run(argv): """Main function, checking arguments passed to script, setting up stubs, configuration and starting Threads. Parameters ---------- argv : list Arguments passed when starting script """ # Checks argument passed to script, ecu_advanced.py will use below ip-address if no argument is passed to the script ip = "127.0.0.1" # Keep this port port = ":50051" try: opts, args = getopt.getopt(argv, "h", ["ip="]) except getopt.GetoptError: print("Usage: ecu_advanced.py --ip <ip_address>") sys.exit(2) for opt, arg in opts: if opt == "-h": print("Usage: ecu_advanced.py --ip <ip_address>") sys.exit(2) elif opt == "--ip": ip = arg # Setting up stubs and configuration # allows to custom set message max size. (default 4Mb, 4194304) # MAX_MESSAGE_LENGTH = 6000000 # channel = grpc.insecure_channel('127.0.0.1:50051', options=[ # ('grpc.max_send_message_length', MAX_MESSAGE_LENGTH), # ('grpc.max_receive_message_length', MAX_MESSAGE_LENGTH), # ], # ) channel = grpc.insecure_channel(ip + port) network_stub = network_api_pb2_grpc.NetworkServiceStub(channel) system_stub = system_api_pb2_grpc.SystemServiceStub(channel) check_license(system_stub) # request_license(system_stub) # download_and_install_license(system_stub, "your_emailed_hash") upload_folder(system_stub, "configuration_udp") # upload_folder(system_stub, "configuration_lin") # upload_folder(system_stub, "configuration_can") reload_configuration(system_stub) # Lists available signals configuration = system_stub.GetConfiguration(common_pb2.Empty()) for networkInfo in configuration.networkInfo: print( "signals in namespace ", networkInfo.namespace.name, system_stub.ListSignals(networkInfo.namespace), ) # Starting Threads ecu_A_thread = Thread( target=ecu_A, args=( network_stub, 1, ), ) ecu_A_thread.start() ecu_B_thread_read = Thread( target=ecu_B_read, args=( network_stub, 1, ), ) ecu_B_thread_read.start() ecu_B_thread_subscribe = Thread(target=ecu_B_subscribe, args=(network_stub,)) ecu_B_thread_subscribe.start() ecu_B_thread_subscribe_2 = Thread(target=ecu_B_subscribe_2, args=(network_stub,)) ecu_B_thread_subscribe_2.start() read_signals = [ common_pb2.SignalId( name="counter", namespace=common_pb2.NameSpace(name="ecu_A") ), common_pb2.SignalId( name="TestFr06_Child02", namespace=common_pb2.NameSpace(name="ecu_A") ), ] ecu_read_on_timer = Thread( target=read_on_timer, args=(network_stub, read_signals, 10) ) ecu_read_on_timer.start()
def SendHeartbeat(self, request, context): send_heartbeat_callback = self._callbacks['SendHeartbeat'] send_heartbeat_callback() return common_pb2.Empty()