def test_import_full_file_name(self): """ :return: """ from cp_lib.app_base import CradlepointAppBase print() # move past the '.' if True: return name = "network.tcp_echo" obj = CradlepointAppBase(name) # here, INIT is used, it exists and is larger than trivial (5 bytes) # we want the tcp-echo.py to exist, but won't use expect = os.path.join("network", "tcp_echo", "tcp_echo.py") self.assertTrue(os.path.exists(expect)) expect = os.path.join("network", "tcp_echo", "__init__.py") self.assertTrue(os.path.exists(expect)) logging.info("TEST names when {} can be run_name".format(expect)) self.assertEqual(obj.run_name, expect) expect = os.path.join("network", "tcp_echo") + os.sep self.assertEqual(obj.app_path, expect) self.assertEqual(obj.app_name, "tcp_echo") self.assertEqual(obj.mod_name, "network.tcp_echo") name = "RouterSDKDemo" obj = CradlepointAppBase(name) # here, the app name is used (the INIT is empty / zero bytes) expect = os.path.join("RouterSDKDemo", "__init__.py") self.assertTrue(os.path.exists(expect)) logging.info( "TEST names when {} is too small to be run_name".format(expect)) expect = os.path.join(name, name) + ".py" self.assertTrue(os.path.exists(expect)) logging.info("TEST names when {} can be run_name".format(expect)) self.assertEqual(obj.run_name, expect) expect = name + os.sep self.assertEqual(obj.app_path, expect) self.assertEqual(obj.app_name, "RouterSDKDemo") self.assertEqual(obj.mod_name, "RouterSDKDemo") return
def test_startup(self): """ :return: """ global USE_UUID print() # move past the '.' app_base = CradlepointAppBase("simple.do_it") if USE_UUID is None: USE_UUID = str(uuid.uuid4()) app_base.logger.debug("UUID:{}".format(USE_UUID)) obj = StatusTreeData(app_base) try: obj.set_uuid(USE_UUID) except ValueError: app_base.logger.error("No APPS installed") raise obj.clear_data() # if True: # return # if this is a FRESH system, then first get will be NULL/NONE result = obj.get_data() self.assertEqual(obj.data, dict()) result = obj.put_data(force=True) app_base.logger.debug("data:{}".format(result)) self.assertEqual(obj.clean, True) obj.set_data_value('health', 100.0) self.assertEqual(obj.clean, False) result = obj.put_data(force=True) app_base.logger.debug("data:{}".format(result)) return
if save_file is not None: # if am_running_on_router(): if sys.platform != "win32": pass # app_base.logger.error( # Skip save to file - am running on router.") else: app_base.logger.debug("Save file:{}".format(save_file)) file_han = open(save_file, "w") for line in report_lines: file_han.write(line + '\n') file_han.close() return 0 if __name__ == "__main__": import logging # get this started, else we don't see anything for a while logging.basicConfig(level=logging.DEBUG) my_app = CradlepointAppBase("gps/probe_gps") _result = probe_gps(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
# our fake data, time-fixed to me NOW request = fix_time_sentence("$GPGGA,094013.0,4334.784909,N,11612.7664" + "48,W,1,09,0.9,830.6,M,-11.0,M,,*60") request = request.encode() base_app.logger.debug("Req({})".format(request)) sock.send(request) # this message has NO response! time.sleep(2.0) sock.close() return 0 if __name__ == '__main__': from cp_lib.app_base import CradlepointAppBase import tools.make_load_settings app_name = 'demo.gps_gate' # we share the settings.ini in demo/gps_gate/settings.ini base_app = CradlepointAppBase(full_name=app_name, call_router=False) # force a full make/read of {app_path}/settings.ini base_app.settings = tools.make_load_settings.load_settings( base_app.app_path) run_client()
if result_out in (1, "1"): value = 0 else: value = 1 # self.client.put('/control/gpio', {self.name: self.state}) result = app_base.cs_client.put("control/gpio", {"CGPIO_CONNECTOR_OUTPUT": value}) if value != int(result): app_base.logger.error("BAD - change failed {}".format(result)) # else app_base.logger.info("Change was GOOD {}".format(result)) break else: app_base.logger.debug( "Looping - delay {} seconds".format(loop_delay)) time.sleep(loop_delay) return 0 if __name__ == "__main__": my_app = CradlepointAppBase("gpio/power") _result = run_router_app(my_app, loop=False) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
app_base.logger.debug("result({})".format(result)) return result # Required keys # ['smtp_tls] = T/F to use TLS, defaults to True # ['smtp_url'] = URL, such as 'smtp.gmail.com' # ['smtp_port'] = TCP port like 587 - be careful, as some servers have more # than one, with the number defining the security demanded. # ['username'] = your smtp user name (often your email acct address) # ['password'] = your smtp acct password # ['email_to'] = the target email address, as str or list # ['subject'] = the email subject # Optional keys # ['email_from'] = the from address - any smtp server will ignore, and force # this to be your user/acct email address; def = ['username'] # ['body'] = the email body; def = ['subject'] if __name__ == "__main__": import sys my_app = CradlepointAppBase("network/send_email") _result = send_one_email(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
result = app_base.cs_client.get_bool("status/system/gpio_actions/") app_base.logger.debug("GET: status/system/gpio_actions/ = [{}]".format(result)) if result is None: # then the serial GPIO function is NOT enabled app_base.logger.error("The Serial GPIO is NOT enabled!") app_base.logger.info("Router Application is exiting") return -1 while loop_delay: # loop as long as not None or zero result1 = app_base.cs_client.get(DEF_SERIAL_NAME_1) result2 = app_base.cs_client.get(DEF_SERIAL_NAME_2) result3 = app_base.cs_client.get(DEF_SERIAL_NAME_3) app_base.logger.info("Inp = ({}, {}, {})".format(result1, result2, result3)) app_base.logger.debug("Looping - delay {} seconds".format(loop_delay)) time.sleep(loop_delay) app_base.logger.info("Router Application is exiting") return 0 if __name__ == "__main__": my_app = CradlepointAppBase("gpio/serial_gpio") _result = read_gpio(my_app, loop=False) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
app_base.logger.info( "CTS changed to {}, setting RTS".format(cts_was)) ser.setRTS(cts_was) else: if dsr_was != ser.dsr: dsr_was = ser.dsr app_base.logger.info( "DSR changed to {}, setting DTR".format(dsr_was)) ser.dtr = dsr_was if cts_was != ser.cts: cts_was = ser.cts app_base.logger.info( "CTS changed to {}, setting RTS".format(cts_was)) ser.rts = cts_was # if you lose the serial port - like disconnected, then # ser.getDSR() will throw OSError #5 Input/Output error finally: ser.close() return if __name__ == "__main__": my_app = CradlepointAppBase("serial/serial_echo") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
def test_get_settings(self): """ :return: """ from cp_lib.app_base import CradlepointAppBase print() # move past the '.' # we'll just use this as example, assuming .config/setting.ini # and name = "network.tcp_echo" obj = CradlepointAppBase(name, call_router=False) # just slam in a known 'data tree' obj.settings = { 'application': { 'firmware': '6.1', 'name': 'make', 'restart': 'true', 'reboot': True, 'sleeping': 'On', 'explosion': 'enabled', }, 'router_api': { 'user_name': 'admin', 'interface': 'ENet USB-1', 'password': '******', 'local_ip': '192.168.1.1' }, 'logging': { 'syslog_ip': '192.168.1.6', 'pc_syslog': 'false', 'level': 'debug' }, 'startup': { 'boot_delay_for_wan': 'True', 'exit_delay': '30 sec', 'boot_delay_max': '5 min', 'bomb_delay': 17, 'rain_delay': '19', 'boot_delay_for_time': 'True' }, 'glob_dir': 'config', 'base_name': 'settings', 'app_dir': 'network\\tcp_echo\\', } logging.info("TEST simple get_setting(), without force_type") self.assertEqual("make", obj.get_setting("application.name")) self.assertEqual("6.1", obj.get_setting("application.firmware")) self.assertEqual(True, obj.get_setting("application.reboot")) logging.info("TEST get_setting(), with force_type=bool") self.assertEqual("true", obj.get_setting("application.restart")) self.assertEqual( True, obj.get_setting("application.restart", force_type=bool)) self.assertEqual(True, obj.get_setting("application.reboot")) self.assertEqual( True, obj.get_setting("application.reboot", force_type=bool)) self.assertEqual(1, obj.get_setting("application.reboot", force_type=int)) self.assertEqual("On", obj.get_setting("application.sleeping")) self.assertEqual( True, obj.get_setting("application.sleeping", force_type=bool)) self.assertEqual("enabled", obj.get_setting("application.explosion")) self.assertEqual( True, obj.get_setting("application.explosion", force_type=bool)) # doesn't exist, but force to String means "None" self.assertEqual( None, obj.get_setting("application.not_exists", force_type=bool)) with self.assertRaises(ValueError): # string 'true' can't be forced to int, bool True can obj.get_setting("application.name", force_type=bool) logging.info("TEST get_setting(), with force_type=str") # [restart] is already string, but [reboot] is bool(True) self.assertEqual( "true", obj.get_setting("application.restart", force_type=str)) self.assertEqual("True", obj.get_setting("application.reboot", force_type=str)) # doesn't exist, & force to String does not means "None" self.assertEqual(None, obj.get_setting("application.not_exists")) self.assertEqual( None, obj.get_setting("application.not_exists", force_type=str)) logging.info("TEST get_setting_time_secs()") self.assertEqual("30 sec", obj.get_setting("startup.exit_delay")) self.assertEqual(30.0, obj.get_setting_time_secs("startup.exit_delay")) self.assertEqual("5 min", obj.get_setting("startup.boot_delay_max")) self.assertEqual(300.0, obj.get_setting_time_secs("startup.boot_delay_max")) self.assertEqual(17, obj.get_setting("startup.bomb_delay")) self.assertEqual(17.0, obj.get_setting_time_secs("startup.bomb_delay")) self.assertEqual("19", obj.get_setting("startup.rain_delay")) self.assertEqual(19.0, obj.get_setting_time_secs("startup.rain_delay")) with self.assertRaises(ValueError): # string 'true' can't be forced to int, bool True can obj.get_setting("application.restart", force_type=int) return
def probe_directory(app_base, base_dir): """ dump a directory in router FW :param CradlepointAppBase app_base: resources: logger, settings, etc :param str base_dir: the directory to dump """ import os app_base.logger.debug("Dump Directory:{}".format(base_dir)) result = os.access(base_dir, os.R_OK) if result: app_base.logger.debug("GOOD name:{}".format(base_dir)) else: app_base.logger.debug("BAD name:{}".format(base_dir)) if result: result = os.listdir(base_dir) for name in result: app_base.logger.debug(" file:{}".format(name)) return if __name__ == "__main__": my_app = CradlepointAppBase("serial_port/list_ports") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
message = json_get_put.jsonrpc_get(my_base.data, message) elif method == "put_data": my_base.logger.debug("PutData:{}".format(message["params"])) message = json_get_put.jsonrpc_put(my_base.data, message) else: message["error"] = { "code": -32601, "message": "Unknown \"method\": {}".format(method) } # else, if request["error"] is already true, then return error message = json_get_put.jsonrpc_prep_response(message, encode=True) """ :type message: str """ my_base.logger.debug("returning:{}".format(message)) self.request.sendall(message.encode()) my_base.logger.debug("") return if __name__ == "__main__": import sys my_app = CradlepointAppBase("network/simple_jsonrpc") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
data = data.encode('utf-8') app_base.logger.debug("Sent:{}".format(data)) server_address = (DEF_HOST_IP, DEF_HOST_PORT) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: # Connect to server and send data sock.connect(server_address) sock.sendall(data) # Receive data from the server and shut down received = str(sock.recv(1024), "utf-8") finally: sock.close() app_base.logger.debug("Recv:{}".format(received)) return json.loads(received) if __name__ == "__main__": my_app = CradlepointAppBase("data/jsonrpc_settings") _result = run_client(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
else: # for RTU, we want HEX form logger_buffer_dump(self.logger, "RTU-REQ", data) self.ser.write(data) # we have 1 second response timeout in the Serial() open time.sleep(0.25) response = self.ser.read(256) if self.logger.getEffectiveLevel() <= logging.DEBUG: if response is None or response == b'': self.logger.debug("SER-RSP:None/No response") elif self.serial_protocol == IA_PROTOCOL_MBASC: # for ASCII, just print as string self.logger.debug("ASC-RSP:{}".format(response)) else: # for RTU, we want HEX form logger_buffer_dump(self.logger, "RTU-RSP", response) return response if __name__ == "__main__": import sys my_app = CradlepointAppBase("serial_port/mbus_simple_bridge", call_router=False) _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
:param CradlepointAppBase app_base: resources: logger, settings, etc """ app_base.logger.info("Send ALERT to ECM via CSClient") # user may have passed in another path alert = "Default Message - All is well!" if "send_alert" in app_base.settings: if "alert" in app_base.settings["send_alert"]: alert = app_base.settings["send_alert"]["alert"] # here we send to Syslog using our OWN facility/channel app_base.logger.info('LOG: Sending alert to ECM=[{}].'.format(alert)) # this line will be sent via Router's Syslog facility/channel app_base.cs_client.log('RouterSDKDemo', 'CS: Sending alert to ECM=[{}].'.format(alert)) app_base.cs_client.alert('RouterSDKDemo', alert) return 0 if __name__ == "__main__": import sys my_app = CradlepointAppBase("simple/send_alert") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
if not result: break gps.publish() app_base.logger.debug("See({})".format( gps.get_attributes())) # client.send(data) else: break time.sleep(1.0) app_base.logger.info("Client disconnected") client.close() # since this server is expected to run on a small embedded system, # free up memory ASAP (see MEMORY note) del client gc.collect() return 0 if __name__ == "__main__": import sys my_app = CradlepointAppBase("gps/gps_localhost") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
self.assertFalse(obj.enabled("fifth_port")) return def test_probe_if_serial_available(self): global base_app print("") # skip paste '.' on line result = probe_serial.probe_if_serial_available(base_app) if PPRINT_RESULT: print(json.dumps(result, indent=4, sort_keys=True)) # these would only be true in some situations expect_port = "ttyS1" result = probe_serial.probe_if_serial_available(base_app, expect_port) if PPRINT_RESULT: print(json.dumps(result, indent=4, sort_keys=True)) return if __name__ == '__main__': from cp_lib.app_base import CradlepointAppBase base_app = CradlepointAppBase() unittest.main()
print("Write to file:{}".format(file_name)) file_han = open(file_name, "w") file_han.write(pretty) file_han.close() if False: print("Output:{}".format(pretty)) return def test_object(self): global base_app obj = GpsConfig(base_app) self.assertIsNotNone(obj) self.assertIsNotNone(obj.data) base_app.logger.debug("GPS Enabled:{}".format(obj.is_enabled())) base_app.logger.debug("Keepalive Enabled:{}".format( obj.keepalive_is_enabled())) base_app.logger.debug("GPS to Server:{}".format(obj.get_client_info())) return if __name__ == '__main__': from cp_lib.app_base import CradlepointAppBase base_app = CradlepointAppBase(call_router=False) unittest.main()
else: raise IOError except IOError: self.send_error(404, 'File Not Found: %s' % self.path) return if send_reply: # Send response status code self.send_response(200) # Send headers self.send_header('Content-type', mime_type) self.end_headers() # Send message back to client # Write content as utf-8 data self.wfile.write(web_message) return if __name__ == "__main__": import sys my_app = CradlepointAppBase("network/simple_web") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
from cp_lib.app_base import CradlepointAppBase from cp_lib.cs_ping import cs_ping # this name "run_router_app" is not important, reserved, or demanded # - but must match below in __main__ and also in __init__.py def run_router_app(app_base, ping_ip=None): """ :param CradlepointAppBase app_base: prepared resources: logger, cs_client :param str ping_ip: the IP to ping :return: """ if ping_ip is None: # then try settings.ini if "ping" in app_base.settings: ping_ip = app_base.settings["ping"].get("ping_ip", '') # else, just assume passed in value is best result = cs_ping(app_base, ping_ip) return result if __name__ == "__main__": import sys my_app = CradlepointAppBase("network/send_ping") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
if line_in is None or len(line_in) == 0: break if line_in[0] == '{': # then assume like {"offset":1, "data":$GPGGA,094013.0 ... }, if line_in[-1] == ',': line_in = line_in[:-1] return eval(line_in) # else, get next line return None if __name__ == "__main__": import sys from cp_lib.load_settings_ini import copy_config_ini_to_json, \ load_sdk_ini_as_dict copy_config_ini_to_json() app_path = "demo/gps_replay" my_app = CradlepointAppBase(app_path, call_router=False) # force a heavy reload of INI (app base normally only finds JSON) my_app.settings = load_sdk_ini_as_dict(app_path) _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
break time.sleep(1.0) app_base.logger.info("Client disconnected") client.close() # since this server is expected to run on a small embedded system, # free up memory ASAP (see MEMORY note) del client gc.collect() return 0 if __name__ == "__main__": import sys from cp_lib.load_settings_ini import copy_config_ini_to_json, \ load_sdk_ini_as_dict copy_config_ini_to_json() app_path = "demo/gps_replay" my_app = CradlepointAppBase(app_path) # force a heavy reload of INI (app base normally only finds JSON) my_app.settings = load_sdk_ini_as_dict(app_path) _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
"Bad NMEA sentence:[{}]".format(line)) raise # gps.publish() # app_base.logger.debug( # "See({})".format(gps.get_attributes())) # client.send(data) else: break time.sleep(1.0) app_base.logger.info("Client disconnected") client.close() # since this server is expected to run on a small embedded system, # free up memory ASAP (see MEMORY note) del client gc.collect() return 0 if __name__ == "__main__": import sys my_app = CradlepointAppBase("gps/gps_gate") _result = run_router_app(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)
return -1 # note: sock.send('Hello, world') will fail, because Python 3 socket() # handles BYTES (see BYTES and STR note) data = b'Hello, world' app_base.logger.debug("Request({})".format(data)) sock.send(data) data = sock.recv(buffer_size) app_base.logger.debug("Response({})".format(data)) sock.close() time.sleep(1.0) return 0 if __name__ == "__main__": import sys my_app = CradlepointAppBase("network/tcp_echo") if len(sys.argv) == 1: # if no cmdline args, we assume SERVER _result = tcp_echo_server(my_app) else: _result = tcp_echo_client(my_app) my_app.logger.info("Exiting, status code is {}".format(_result)) sys.exit(_result)