def __init__(self, id, name, conn_string, listening_port=8080): self.id = id self.port = listening_port self.name = name self.messaging = Messaging(port=listening_port) self.is_running = False self.iothub_client = IoTHubClient(conn_string, PROTOCOL) logging.info("Station was created successfully.")
def __init__(self): # Make data dir if not os.path.isdir(".blockchain"): os.makedirs(".blockchain") self.logger = self.init_logger() self.logger.log(20, "Start Blockchain Service") self.tx = Transaction(self.logger) self.bc = Blockchain(self.logger, self.tx) self.msg = Messaging(self.logger, self.bc, self.tx)
def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # self.sleep_ms = self.SLEEP_MS_DEFAULT # ------------------------------------------------------------------------------------------------------------ # # Initialise required services # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['led'] is None: from led import MockLed self.led = MockLed() else: from led import Led self.led = Led(self.config['pinout']['led']['pin'], self.config['pinout']['led']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['button'] is None: from button import MockButton self.button = MockButton() else: from button import Button self.button = Button(self.config['pinout']['button']['pin'], self.config['pinout']['button']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['relay'] is None: from relay import MockRelay self.relay = MockRelay() else: from relay import Relay self.relay = Relay(self.config['pinout']['relay']['pin'], self.config['pinout']['relay']['on_level']) # ------------------------------------------------------------------------------------------------------------ # self.wifi = WiFi(self.config) # , verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) # ------------------------------------------------------------------------------------------------------------ # # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected(be_verbose=False) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['type'], self.device_id)) print(self.led) print(self.button) print(self.relay) print(self.wifi) print(self.messaging)
def get(cls, user_id, ext, personal_data=False): (user_id, ext) = cls.sanitize(user_id, ext) from messaging import Messaging filename = User.user_filename(user_id, ext) if not os.path.isfile(filename): return None with open(filename) as f: dict = json.load(f) user = cls() user.user_id = user_id user.ext = ext user.salutation = dict.get("salutation", "") user.first_name = dict.get("first_name", "") user.last_name = dict.get("last_name", "") user.org_name = dict.get("org_name", "") user.org_add_name = dict.get("org_add_name", "") user.personal_data = personal_data if (personal_data): user.street = dict.get("street", "") user.zip = dict.get("zip", "") user.city = dict.get("city", "") user.country = dict.get("country", "") user.stats = Stats(user) user.messaging = Messaging(user) return user
class BlockchainService: def __init__(self): # Make data dir if not os.path.isdir(".blockchain"): os.makedirs(".blockchain") self.logger = self.init_logger() self.logger.log(20, "Start Blockchain Service") self.tx = Transaction(self.logger) self.bc = Blockchain(self.logger, self.tx) self.msg = Messaging(self.logger, self.bc, self.tx) def init_logger(self): # logging logger = logging.getLogger("blcokchainlog") logger.setLevel(10) fh = logging.FileHandler('.blockchain/logger.log') logger.addHandler(fh) formatter = logging.Formatter( '%(asctime)s | %(levelname)s | %(message)s') fh.setFormatter(formatter) return logger def make_block(self, score): # take score is for debug block = self.bc.generate_block(score) res, code = self.bc.add_new_block(block) if not res: print("Block is not generated") else: print("Block is generated") # send generated block blkmsg = {"type": "block", "body": block} for peer in self.msg.peers: self.msg.send(blkmsg, peer) def make_tx(self): transaction = self.tx.generate_tx() if not self.tx.add_tx_pool(transaction): print("Transaction is not generated") else: print("Transaction is generated") # send generated block txmsg = {"type": "tx", "body": transaction} for peer in self.msg.peers: self.msg.send(txmsg, peer)
def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # # Initialise required services if self.config['pinout']['led'] is None: self.led = led.MockLed() else: self.led = led.Led(self.config['pinout']['led']) self.wifi = WiFi(self.config, verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) if self.config['pinout']['ultrasound'] is None: self.water_level = MockWaterLevel() else: self.water_level = WaterLevel(self.config, verbose=self.verbose) if self.config['pinout']['flow_meter'] is None: self.flow_rate = MockFlowRate() else: self.flow_rate = FlowRateFallingEdge(self.config, verbose=self.verbose) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['name'], self.device_id)) print(self.led) print(self.wifi) print(self.messaging) print(self.water_level) print(self.flow_rate) # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) time.sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected()
class Station: """ Models a Bike Station. """ def __init__(self, id, name, conn_string, listening_port=8080): self.id = id self.port = listening_port self.name = name self.messaging = Messaging(port=listening_port) self.is_running = False self.iothub_client = IoTHubClient(conn_string, PROTOCOL) logging.info("Station was created successfully.") def notify_iothub(self, msg): json_msg = msg.to_json() iot_hub_msg = IoTHubMessage(json_msg) self.iothub_client.send_event_async(iot_hub_msg, self.iothub_callback, None) logging.info("Station notified hub") def iothub_callback(self, message, result, user_context): logging.info ( "IoT Hub responded to message with status: %s" % (result) ) def run(self): self.is_running = True logging.info("Station {} is now running! Listening on port {}".format(self.name, self.port)) msg_thread = threading.Thread(target=self.messaging.start_listening) msg_thread.daemon = True msg_thread.start() while self.is_running: msg = self.messaging.get_message() logging.info("Processing new message...") if msg.type == Message.MessageType.BIKE_TAKE: self.notify_iothub(msg) elif msg.type == Message.MessageType.BIKE_RETURN: self.notify_iothub(msg) elif msg.type == Message.MessageType.SHUTDOWN: self.is_running = False pass else: #TODO bad message logging.warn("Encountered unknown message type :" + msg.type) pass logging.info("Station {} shutdown.".format(self.name))
class RunLoop: SLEEP_MS_DEFAULT = 20 LED_TOGGLE_DEFAULT = 500 def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # self.sleep_ms = self.SLEEP_MS_DEFAULT # ------------------------------------------------------------------------------------------------------------ # # Initialise required services # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['led'] is None: from led import MockLed self.led = MockLed() else: from led import Led self.led = Led(self.config['pinout']['led']['pin'], self.config['pinout']['led']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['button'] is None: from button import MockButton self.button = MockButton() else: from button import Button self.button = Button(self.config['pinout']['button']['pin'], self.config['pinout']['button']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['relay'] is None: from relay import MockRelay self.relay = MockRelay() else: from relay import Relay self.relay = Relay(self.config['pinout']['relay']['pin'], self.config['pinout']['relay']['on_level']) # ------------------------------------------------------------------------------------------------------------ # self.wifi = WiFi(self.config) # , verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) # ------------------------------------------------------------------------------------------------------------ # # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected(be_verbose=False) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['type'], self.device_id)) print(self.led) print(self.button) print(self.relay) print(self.wifi) print(self.messaging) def on_wifi_connected(self, be_verbose=True): if be_verbose and self.verbose: print(self.wifi) self.led.toggle(self.LED_TOGGLE_DEFAULT) if not self.messaging.connected(): self.messaging.connect() def run(self): if self.verbose: print('Run loop ' 'started') while not self.exit: # ======================================================================================================== # self.led.poll() self.button.poll() # -------------------------------------------------------------------------------------------------------- # if self.relay.state( ) == self.relay.STATE_OFF and self.button.pressed( ) == self.button.SHORT_PRESS: if self.verbose: print('<Button: SHORT_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'on' '>' }) self.relay.on() self.button.clear() elif self.relay.state( ) == self.relay.STATE_ON and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: SHORT_PRESS ' '1' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'off' '>' }) self.relay.off() self.button.clear() elif self.led.enabled() is True and self.button.pressed( ) == self.button.LONG_PRESS: if self.verbose: print('<Button: LONG_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: LONG_PRESS ' 'led enabled: ' 'off' '>' }) self.led.enable(False) self.led.off() self.button.clear() elif self.led.enabled() is False and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: LONG_PRESS ' '2' '>') self.messaging.publish( {'state': '<Button: LONG_PRESS ' 'led enabled: ' 'on' '>'}) self.led.enable(True) self.led.toggle(self.LED_TOGGLE_DEFAULT) self.button.clear() # -------------------------------------------------------------------------------------------------------- # if self.wifi.connected(): if self.messaging.connected() is False: self.on_wifi_connected() if self.messaging.poll(): if 'action' in self.messaging.msg: if self.messaging.msg['action'] == 'on': if self.verbose: print('<Relay: ' 'on' '>') self.relay.on() elif self.messaging.msg['action'] == 'off': if self.verbose: print('<Relay: ' 'off' '>') self.relay.off() elif self.messaging.msg['action'] == 'exit': if self.verbose: print('<Application: ' 'exit' '>') self.exit = True self.messaging.completed() elif self.wifi.connected() is False: if self.wifi.connecting() is False: self.led.toggle(250) self.led.on(poll=True, save_state=True) if self.wifi.connect() is True: self.led.off(poll=True, restore_state=True) # ======================================================================================================== # sleep_ms(self.sleep_ms) # Reduce the tightness of the run loop # ======================================================================================================== # if self.verbose: print('Run loop ' 'exited') def close(self): self.exit = True if self.led: self.led.close() if self.button: self.button.close() if self.relay: self.relay.close() if self.messaging: self.messaging.disconnect() # if self.wifi: # self.wifi.disconnect() # Don't do this, you will loose connection to the REPL if self.verbose: print('Run loop ' 'closed')
#!/usr/bin/env python3 from messaging import Messaging message_handler = Messaging() message_handler.set_smtpsrv("smtp.office365.com") message_handler.set_recipients(["*****@*****.**"]) message_handler.set_originator("*****@*****.**") message_handler.set_subject("Testing Messaging Class") message_handler.set_body("Test Message") message_handler.set_attachments(["attachment.txt"]) message_handler.process()
class RunLoop: def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # # Initialise required services if self.config['pinout']['led'] is None: self.led = led.MockLed() else: self.led = led.Led(self.config['pinout']['led']) self.wifi = WiFi(self.config, verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) if self.config['pinout']['ultrasound'] is None: self.water_level = MockWaterLevel() else: self.water_level = WaterLevel(self.config, verbose=self.verbose) if self.config['pinout']['flow_meter'] is None: self.flow_rate = MockFlowRate() else: self.flow_rate = FlowRateFallingEdge(self.config, verbose=self.verbose) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['name'], self.device_id)) print(self.led) print(self.wifi) print(self.messaging) print(self.water_level) print(self.flow_rate) # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) time.sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected() # ------------------------------------------------------------------------------------------------------------ # def on_wifi_connected(self): self.led.toggle(500) if not self.messaging.connected(): self.messaging.connect() def run(self): if self.verbose: print('Run loop started') while not self.exit: # ======================================================================================================== # self.led.poll() # -------------------------------------------------------------------------------------------------------- # if self.wifi.connected(): if not self.water_level.calibrated(): self.water_level.calibrate() elif self.water_level.read(): self.messaging.publish(self.water_level.level()) if not self.flow_rate.calibrated(): self.flow_rate.calibrate() elif self.flow_rate.read(): self.messaging.publish(self.flow_rate.rate()) elif self.wifi.connecting(): self.led.toggle(250) elif not self.wifi.connected(): self.wifi.connect() if self.wifi.connected(): self.on_wifi_connected() # ======================================================================================================== # if self.flow_rate.reading(): time.sleep_ms(1) else: time.sleep_ms(20) # Reduce the tightness of the run loop # ======================================================================================================== # if self.verbose: print('Run loop exited') def close(self): self.exit = True if self.led: self.led.close() if self.water_level: self.water_level.close() if self.flow_rate: self.flow_rate.close() if self.messaging: self.messaging.disconnect() # if self.wifi: # self.wifi.disconnect() # Don't do this, you will loose connection to the REPL if self.verbose: print('Run loop closed')