def __init__(self): # Define main algorithm object self.m_webServer = WebServer() # Define variables to publish topic # variables for remote_control_publisher # topic name="RemoteControl", message=RemoteControlMsg self.remote_control_msg = RemoteControlMsg() # Initialization rospy.init_node('server_node', anonymous=True) print(tstamp() + '\033[32m[Server]Node launched\033[0m') rospy.on_shutdown(self.shutdown) self.header_seq = 0 # Define publisher and rate self.remote_control_publisher = rospy.Publisher('remote_control', RemoteControlMsg, queue_size=10, latch=True) self.image_subscriber = rospy.Subscriber('/front_camera/compressed', CompressedImage, self.callback_image_received) self.rate = rospy.Rate(20)
class ServerNode: def __init__(self): # Define main algorithm object self.m_webServer = WebServer() # Define variables to publish topic # variables for remote_control_publisher # topic name="RemoteControl", message=RemoteControlMsg self.remote_control_msg = RemoteControlMsg() # Initialization rospy.init_node('server_node', anonymous=True) print(tstamp() + '\033[32m[Server]Node launched\033[0m') rospy.on_shutdown(self.shutdown) self.header_seq = 0 # Define publisher and rate self.remote_control_publisher = rospy.Publisher('remote_control', RemoteControlMsg, queue_size=10, latch=True) self.image_subscriber = rospy.Subscriber('/front_camera/compressed', CompressedImage, self.callback_image_received) self.rate = rospy.Rate(20) def publishing(self): success = True while success and not rospy.is_shutdown(): # Update remote control topic self.remote_control_msg = self.m_webServer.control_update( self.remote_control_msg) msg_header = Header() msg_header.seq = self.header_seq msg_header.stamp = rospy.Time.now() # Publish remote control topic self.remote_control_msg.header = msg_header self.remote_control_publisher.publish(self.remote_control_msg) # ROS sleep self.header_seq += 1 # ROS sleep self.rate.sleep() def callback_image_received(self, compressed_image): self.m_webServer.image_update(compressed_image.data) def shutdown(self): print(tstamp() + '\033[31m[Server]Node shutdown\033[0m') self.m_webServer.web_shutdown() # self.wlk_canbus.canbus_shutdown() rospy.sleep(0.1)
def main(): log.basicConfig(format='[ %(levelname)s ] %(message)s', level=log.INFO, stream=sys.stdout) args = build_argparser().parse_args() text_detector = TextDetector(args) document_identifier = DocumentIdentifier(args.config) document_aligner = DocumentAligner(args) web_server = WebServer() web_server.start() try: input_source = int(args.input_source) except ValueError: input_source = args.input_source if os.path.isdir(input_source): cap = FolderCapture(input_source) else: cap = cv2.VideoCapture(input_source) if not cap.isOpened(): log.error('Failed to open "{}"'.format(args.input_source)) if isinstance(cap, cv2.VideoCapture): cap.set(cv2.CAP_PROP_BUFFERSIZE, 1) log.info('Starting inference...') print( "To close the application, press 'CTRL+C' here or switch to the output window and press ESC key" ) while cap.isOpened(): ret, frame = cap.read() if not ret: break frame = document_aligner.preprocess(frame) text = text_detector.process(frame, True) result = document_identifier.process(text) print(json.dumps(result, indent=4)) while True: #web_server.push(result) cv2.waitKey(4000) key = cv2.waitKey(0) esc_code = 27 if key == esc_code: breaks cv2.destroyAllWindows() cap.release()
class Server: def __init__(self): Log.info("Server.init()") self.webServer = WebServer() def start(self): Log.info("Server.start()") self.webServer.start() def stop(self): Log.info("Server.stop()") self.webServer.stop()
def __init__(self): rospy.init_node('Gateway', log_level=rospy.DEBUG) server_config_file = rospy.get_param("~server_config_file") self.config = Config(server_config_file) self.pf = ProtocolFactory(self.config) self.run_id = rospy.get_param("run_id") print("runid = ", self.run_id) self.node_list = rosnode.get_node_names() self.timer = Timer() self.monitor = Monitor(self.node_list, self.timer) self._server_request = {} # stores server_request self._event_bus = Queue() self._heartbeat_timeout_job = None self._tele_report_job = None self._report_car_job = None self._report_task_job = None self._service = DrivingTaskService(self._event_bus) self.__client = Connector(self._event_bus, self.config.host, self.config.port) self._handler_map = {} self._event_handler_map = {} self._add_command_handler() self._add_event_handler() self._web_server = WebServer(self.monitor, self._service, self.config) self._tele_control_service = TeleControlService()
def run(self): self._logger.info("Starting DanDrop v" + self._globals.version + "...") # Create and start the API server if self._config.enableApi: self._api_server = ApiServer(self, self._config.tcpListenIp, self._config.tcpListenPort) # Start the web server if self._config.enableWebServer: self._web_server = WebServer() # Check if the systray should be shown #if self._config.enableSystray: if True: self._logger.debug("Creating systray...") self._systray = Systray(self._globals) # Create the file watcher self._fswatcher = FSWatcher(self._configOld) self._fswatchers = [] for share in self._config.shares: print share.sync_folder # Start watching and syncing files self._fswatcher.watch()
def __init__(self, network): self.done = False self.network = network self.in_alarm_state = False self.alarm_on = open(self.ALARM_ON_FILE).readline().rstrip() == 'true' if self.alarm_on: self.turn_alarm_on() self.web_server = WebServer(self)
def start(self): if len(sys.argv) == 1: print "Please specify local IP address" print "Then add 'webservice' to make values available via HTTP" print "" sys.exit() with_web_service = False if len(sys.argv) > 2: if sys.argv[2] == "webservice": with_web_service = True self.local_host = sys.argv[1] self.load_config() t = threading.Thread(target=self.start_raspression_server) t.daemon = True t.start() if with_web_service: ws = WebServer(self) ws.daemon = True ws.start() t.join() try: while True: print "??" pass except KeyboardInterrupt: print "Exiting..." del ws del t sys.exit()
class SecuritySystem: SENSOR = 'sensor' GLASS_BREAK = 'glass_break' CONTROLLER = 'controller' SYSTEM = 'system' SIREN = 'SIREN' ALARM_ON_FILE = './alarm_on' node_ids = {1 : {"name": "Controller", "type": CONTROLLER}, 255 : {'name': "OpenZWave System", 'type': SYSTEM}, 3 : {'name': "Living Room Right Window", 'type': SENSOR}, 4 : {'name': "Living Room Middle Window", 'type': SENSOR}, 5 : {'name': "Front Door", 'type': SENSOR}, 7 : {'name': '2nd Bedroom Window', 'type': SENSOR}, 12 : {'name': '2nd Bedroom Glass Break', 'type': GLASS_BREAK}, 13 : {'name': 'Bedroom Glass Break', 'type': GLASS_BREAK}, 14 : {'name': 'Living Room Glass Break', 'type': GLASS_BREAK}, 15 : {'name': 'Living Room Siren', 'type': SIREN}, 17 : {'name': 'Hallway Siren', 'type': SIREN}, 18 : {'name': 'Bedroom Siren', 'type': SIREN}, 19 : {'name': 'Bedroom Window', 'type': SENSOR} } nodes_in_alarm = set() def __init__(self, network): self.done = False self.network = network self.in_alarm_state = False self.alarm_on = open(self.ALARM_ON_FILE).readline().rstrip() == 'true' if self.alarm_on: self.turn_alarm_on() self.web_server = WebServer(self) def run(self): self.web_server_thread = Thread(target=self.web_server.start) self.web_server_thread.start() try: while not self.done: time.sleep(1) except KeyboardInterrupt as e: self.stop() raise e def stop(self): self.done = True self.web_server.stop() #self.web_server_thread.join() def turn_alarm_on(self): print "Turning alarm on" self.in_alarm_state = False self.alarm_on = True self.turn_sirens_off() open(self.ALARM_ON_FILE, 'w').write('true') self.nodes_in_alarm.clear() for node_id, node_info in self.node_ids.iteritems(): if node_info['type'] == self.SENSOR: if not self.network.nodes[node_id].get_values_by_command_classes()[48].values()[0].data: self.nodes_in_alarm.add(node_id) elif node_info['type'] == self.GLASS_BREAK: self.nodes_in_alarm.add(node_id) print "Nodes in alarm: " + str(self.nodes_in_alarm) def turn_alarm_off(self): print "Turning alarm off" self.turn_sirens_off() self.in_alarm_state = False self.alarm_on = False open(self.ALARM_ON_FILE, 'w').write('false') def turn_sirens_on(self): print "Turning sirens on" self.network.nodes[15].set_switch(72057594294386688, True) self.network.nodes[17].set_switch(72057594327941120, True) self.network.nodes[18].set_switch(72057594344718336, True) Timer(30.0, self.turn_sirens_off).start() def turn_sirens_off(self): print "Turning sirens off" self.network.nodes[15].set_switch(72057594294386688, False) self.network.nodes[17].set_switch(72057594327941120, False) self.network.nodes[18].set_switch(72057594344718336, False) def handle_node_event(self, network, node, value): if self.alarm_on and not self.in_alarm_state and node.node_id in self.nodes_in_alarm and self.node_ids[node.node_id]['type'] == self.SENSOR and value > 0: self.in_alarm_state = True self.turn_sirens_on() send_mail(self.node_ids[node.node_id]['name']) elif self.node_ids[node.node_id]['type'] != self.SENSOR: print('Louie signal : Node event : {0}. value: {1}'.format(node, value)) def handle_scene_event(self, network, node, scene_id): if scene_id == 1: self.turn_alarm_on() elif scene_id == 3: self.turn_alarm_off() ############################################################################################################################################### def louie_node_update(self, network, node): print('Louie signal : Node update : %s.' % node) def louie_value_update(self, network, node, value): if self.alarm_on and not self.in_alarm_state and node.node_id in self.nodes_in_alarm and self.node_ids[node.node_id]['type'] == self.GLASS_BREAK and value.label=='General' and value.data == 255: self.in_alarm_state = True self.turn_sirens_on() send_mail(self.node_ids[node.node_id]['name']) print('Louie signal : Value update : %s.' % value) def louie_ctrl_message(self, state, message, network, controller): print('Louie signal : Controller message : %s.' % message)
logging.basicConfig(level=logging.INFO) log = logging.getLogger("Main") if __name__ == "__main__": # Load config from file try: with open('config/settings.json', 'r') as settings_file: data = settings_file.read() settings = json.loads(data) except EnvironmentError: log.error("Could not open src/config/settings.json") log.error("Please fill in sample_settings.json to your needs and copy to src/config/settings.json or to your config volume!") sys.exit("Could not open settings.json") # Create plugin collection with all plugins found in the plugins folder # and install assets plugin_collection = PluginCollection( settings['common']['pluginsPackage'], settings['common']['static-assets'], settings['common']['templates'] ) # Apply settings to plugins. There must be a top level key in the # settings dict named after the plugin class. Otherwise, the plugin # default settings will be used. plugin_collection.apply_settings(settings) try: WebServer(settings, plugin_collection).run() except KeyboardInterrupt: log.info("Bye bye!")
import os import sys import platform delimiter = '/' if platform.system() == 'Linux' else '\\' common_path = delimiter.join( os.path.dirname(os.path.abspath(__file__)).split(delimiter)[:-1]) sys.path.append(common_path) import asyncio from common import Logger from web_server import WebServer try: loop = asyncio.get_event_loop() loop.run_until_complete(WebServer().run()) loop.close() except Exception as e: Logger.log_error (e)
class QueueManager: def __init__(self): self.queues = [] def subscribe(self, queue): self.queues.append(queue) def unsubscribe(self, queue): self.queues.remove(queue) def submit(self, item): for queue in self.queues: queue.put(item) if __name__ == '__main__': packet_queue = QueueManager() dns_queue = QueueManager() file_manager = FileManager('web') web_server = WebServer(file_manager, packet_queue, dns_queue) reverse_dns = ReverseDns(dns_queue) sniffer = Sniffer(packet_queue, reverse_dns) sniffer.start() WebServer(file_manager, packet_queue, dns_queue).start('0.0.0.0', 8182)
def main(): bot = Bot() webbserver = WebServer(bot) webbserver.run() time.sleep(3) print("BOT started") while True: # If not running do nothing if not bot.running: continue # Check limits set by user ret = bot.check_limits() if ret: continue # If bot is not fishing cast fishing and start restart timer if not bot.is_fishing: if bot.reset is not None: bot.reset.cancel() bot.reset = threading.Timer(25, bot.fishing_failed) bot.reset.start() bot.cast_fishing() time.sleep(0.25) bot.is_fishing = True # Take screenshot and detect bobber location try: im = bot.take_screenshot() loc = bot.detect_bobber(True) except Exception as e: print("Screen Capture Error", e) # If bobber was detected if loc is not False: # Get mouse position + bobber centroid try: mloc = pg.position() loc = (loc[0] + int(bot.bobber_template.shape[1] / 2), loc[1] + int(bot.bobber_template.shape[0] / 2)) # Generate human-like movement and move mouse along the path movement = bot.human_movement(mloc, loc, 300) for x, y in movement: pg.moveTo(x, y, 0, pause=0.1e-14 + np.random.random() * 0.9e-13) # When mouse reached the bobber move the cursor under bobber bot.move_to_no_label_spot(1, True) except Exception as e: print("Mouse Movement Error", e) # Waiting for fish while bot.is_fishing: # Fish? try: if (bot.get_current_cursor() == bot.fishing_cursor_im ).all(): # Detach reset timer and variables needed for fishing bot.detach_fishing() # Move cursor to bobber's position and click time.sleep(np.random.random() * 0.8 + 0.5) pg.moveRel(None, int(bot.bobber_template.shape[0] / 2) * -0.9, duration=0.1e-1 + np.random.random() * 0.5) pg.click() # Log item bot.item_list["Successful"] += 1 time.sleep(1.8) except Exception as e: print("Fish Detection Error", e)
def __init__(self): Log.info("Server.init()") self.webServer = WebServer()
#!/usr/bin/python3 from menu import Menu from lcd import MenuLcd from keys import Keys from player import Player from web_server import WebServer from youtube_linker import YoutubeLinker import shared_data shared_data.objects['menu'] = Menu() # m.execute('lcd/on.py') shared_data.objects['menuLcd'] = MenuLcd() shared_data.objects['keys'] = Keys() shared_data.objects['player'] = Player() shared_data.objects['webServer'] = WebServer() shared_data.objects['youtubeLinker'] = YoutubeLinker() print('Initialised, starting main loop') while True: shared_data.performMainLoop()
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), "../")) from pymongo import MongoClient from web_server import WebServer if __name__ == "__main__": client = MongoClient() database = client.get_database("test") client.close() server = WebServer(database).web_server server.run("localhost", 4444, debug=True)
'b': 0 }, 'boxThickness': 2, 'imgFileNamePrefix': 'cam', 'httpPort': 8000, 'webDir': 'web', 'imageDir': 'images', 'snapshotFile': 'snapshot.jpg', 'classificationPoll': 5, 'classificationThreshold': 0.7 } def signal_handler(sig, frame): motion_capture.stop() web_server.stop() classifier.stop() signal.signal(signal.SIGINT, signal_handler) os.chdir(config['webDir']) [os.remove(f) for f in glob.glob(os.path.join(config['imageDir'], "*.jpg"))] message_queue = Queue() motion_capture = MotionCapture(config, message_queue) motion_capture.start() web_server = WebServer(config, message_queue) web_server.start() classifier = Classifier(config) classifier.start()
from web_server import WebServer server = WebServer() server.start()
def _init_web_app(self): self._web_server = WebServer(self.SERVER_PORT, self._logger, self._embedded_application, self._remoting_client, self._world_map_service, self._local_world_map_service, self._pathfinding_service, self._video_streaming_service, self._embedded_video_streaming_service, self._game_cycle_control_service, self._motion_service, self._hardware_status_collector_service, self._secret_code_decoding_service, self._treasure_handling_service, self._camera_arm_control_service) self._web_server.run()
class MicroWifi: def __init__(self, ap_name='MicroWifi', ap_password=''): self.web_server = WebServer() self.wifi_man = WifiManager(ap_name=ap_name, ap_password=ap_password) # setup web server routes self.setup_routes(self.web_server, self.wifi_man) def start(self): # try to auto connect self.wifi_man.auto_connect() if self.wifi_man.is_access_point_mode(): # start our web server to allow the user to configure the device self.web_server.start() def stop(self): try: self.web_server.stop() except Exception as exc: print('Error stopping {}'.format(exc)) def setup_routes(self, server, wifi_manager): @server.route("/") def home(client, request): try: html = "" try: with open('www/index.html') as f: html = f.read() except OSError: pass server.send_response(client, html) except Exception as exc: print('Error in home route {}'.format(exc)) @server.route("/scan") def scan(client, request): try: network_ssids = [ network[0] for network in wifi_manager.access_point_scan() ] payload = {'networks': network_ssids} server.send_response(client, json.dumps(payload), content_type='application/json') except Exception as exc: print('Error in scan route {}'.format(exc)) @server.route("/connect", 'POST') def connect(client, request): params = server.get_form_data(request) ssid = params.get('ssid') password = params.get('password') # try to connect to the network status = wifi_manager.connect(ssid, password) payload = { 'status': status, 'msg': 'Successfully connected to {}'.format(ssid) if status else 'Error connecting to {}'.format(ssid) } server.send_response(client, json.dumps(payload), content_type='application/json')
from pymongo import MongoClient from watchdog.observers.polling import PollingObserver from file_monitor import FileMonitor from web_server import WebServer from config import config from utils import init_database from tornado.wsgi import WSGIContainer from tornado.httpserver import HTTPServer from tornado.ioloop import IOLoop if __name__ == "__main__": client = MongoClient() database = client.get_database(config["database_name"]) client.close() init_database(database) server = WebServer(database).web_server observer = PollingObserver() file_monitor = FileMonitor(database, config["content_path"]) observer.schedule(file_monitor, path=config["content_path"], recursive=True) print config["content_path"] observer.start() if (config["dev_mode"]): server.run(config["server_ip"], config["server_port"], debug=True) else: server = HTTPServer(WSGIContainer(server)) server.listen(config["server_port"], config["server_ip"]) IOLoop.instance().start()
import sys import signal from web_server import WebServer def shutdownServer(sig, unused): """ Shutsdown server from a SIGINT recieved signal """ server.shutdown() sys.exit(1) if __name__ == "__main__": signal.signal(signal.SIGINT, shutdownServer) server = WebServer("localhost", 8080) server.start() print("Press Ctrl+C to shut down server.")
class BaseStationApplication(object): LOGGING_DIRECTORY = "../data/logs" IMAGE_LOGGING_DIRECTORY = "../data/logs/images" SERVER_PORT = 8080 REMOTE_SERVER_PORT = 8081 STREAMING_SERVER_PORT = 5000 STREAMING_SERVER_IP_ADDRESS = "192.168.0.60" REMOTE_SERVER_IP_ADDRESS = "192.168.0.60" DEFAULT_STREAM_IMAGE_FILE_NAME = "../resources/default-stream-image.png" VIDEO_STREAM_BUFFER_SIZE = 1 def initialize(self): #ptvsd.enable_attach(secret = 'd3sign3') self._init_logging() self._init_services() self._embedded_application = RemotableOf(EmbeddedApplication, self._remoting_client) self._init_web_app() self._logger.close() def _init_logging(self): self._logger = Logger() self._logger.similar_log_entry_skip_interval = 0 self._csv_log_subscriber = CsvLogSubscriber(self.LOGGING_DIRECTORY) self._image_log_subscriber = ImageLogSubscriber(self.IMAGE_LOGGING_DIRECTORY) self._console_log_subscriber = ConsoleLogSubscriber() self._logger.subscribe(self._csv_log_subscriber) self._logger.subscribe(self._image_log_subscriber) self._logger.subscribe(self._console_log_subscriber) def _init_services(self): self._init_remoting_services() self._coordinate_factory = CoordinateFactory() self._world_map_service = WorldMapService(self._coordinate_factory) self._local_world_map_service = RemotableOf(LocalWorldMapService, self._remoting_client) self._pathfinding_service = PathfindingService(Pathfinder(PathSimplifier()), self._world_map_service, self._coordinate_factory) self._embedded_video_streaming_service = RemotableOf(VideoStreamingService, self._remoting_client) self._movement_executor = RemotableOf(MovementExecutor, self._remoting_client) self._path_navigator = PathNavigator(self._movement_executor, self._world_map_service, self._coordinate_factory) self._motion_service = MotionService(self._movement_executor, self._path_navigator) self._hardware_status_collector_service = RemotableOf(HardwareStatusCollectorService, self._remoting_client) self._secret_code_decoding_service = RemotableOf(SecretCodeDecodingService, self._remoting_client) self._treasure_handling_service = RemotableOf(TreasureHandlingService, self._remoting_client) self._camera_arm_control_service = RemotableOf(CameraArmControlService, self._remoting_client) self._game_cycle_control_service = GameCycleControlService(StateFactory(), self._world_map_service, self._pathfinding_service, self._motion_service, self._secret_code_decoding_service, self._treasure_handling_service, self._hardware_status_collector_service, self._local_world_map_service) self._init_video_streaming_service() def _init_video_streaming_service(self): self._original_stream_buffer = InMemoryBufferedStreamWriter(self.VIDEO_STREAM_BUFFER_SIZE) self._processed_stream_buffer = InMemoryBufferedStreamWriter(self.VIDEO_STREAM_BUFFER_SIZE) self._world_map_stream_writer = WorldMapStreamWriter(self._world_map_service, self._pathfinding_service) self._world_map_stream_writer.add_output_stream_writer(self._processed_stream_buffer) self._video_stream_dispatcher = VideoStreamDispatcher(Image.from_file(self.DEFAULT_STREAM_IMAGE_FILE_NAME)) self._video_stream_dispatcher.add_stream_writer(self._original_stream_buffer) self._video_stream_dispatcher.add_stream_writer(self._world_map_stream_writer) self._tcp_stream_reader = TcpStreamReader(self.STREAMING_SERVER_IP_ADDRESS, self.STREAMING_SERVER_PORT, self.VIDEO_STREAM_BUFFER_SIZE, False) self._video_streaming_service = VideoStreamingService(self._video_stream_dispatcher, self._original_stream_buffer, self._processed_stream_buffer, self._tcp_stream_reader) def _init_remoting_services(self): self._remote_method_invoker = RemoteMethodInvoker(JsonSerializer()) self._remoting_client = RemotingClient(self._remote_method_invoker, self.REMOTE_SERVER_IP_ADDRESS, self.REMOTE_SERVER_PORT) def _init_web_app(self): self._web_server = WebServer(self.SERVER_PORT, self._logger, self._embedded_application, self._remoting_client, self._world_map_service, self._local_world_map_service, self._pathfinding_service, self._video_streaming_service, self._embedded_video_streaming_service, self._game_cycle_control_service, self._motion_service, self._hardware_status_collector_service, self._secret_code_decoding_service, self._treasure_handling_service, self._camera_arm_control_service) self._web_server.run()
#Startup script. Just run `python start_script.py` from web_controller import WebSocketController from web_server import WebServer from threading import Thread threads = [] websocketcontroller = WebSocketController() webserver = WebServer() threads.append(Thread(target=websocketcontroller.run)) threads.append(Thread(target=webserver.run)) [thread.start() for thread in threads]
async def start_web_server(self): self.web_server = WebServer(self.on_web_msg)
from web_server import WebServer web = WebServer() if __name__ == '__main__': web.app.run()
def __init__(self, ap_name='MicroWifi', ap_password=''): self.web_server = WebServer() self.wifi_man = WifiManager(ap_name=ap_name, ap_password=ap_password) # setup web server routes self.setup_routes(self.web_server, self.wifi_man)
__name__ = "__main__" from pymongo import MongoClient from watchdog.observers import Observer from file_monitor import FileMonitor from web_server import WebServer from config import config from utils import init_database if __name__ == "__main__": client = MongoClient() database = client.get_database(config["database_name"]) client.close() init_database(database) server = WebServer(database).web_server observer = Observer() file_monitor = FileMonitor( database, config["content_path"] ) observer.schedule( file_monitor, path=config["content_path"], recursive=True ) observer.start() server.run( config["server_ip"], config["server_port"] )