def main(): c = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) c.set_callback(sub_cb) c.connect() c.subscribe(colorCommandTopic) c.subscribe(ledCommandTopic) # init input button ugfx.input_attach(ugfx.JOY_UP, lambda pressed: btn_cb(c, 'U', pressed)) ugfx.input_attach(ugfx.JOY_DOWN, lambda pressed: btn_cb(c, 'D', pressed)) ugfx.input_attach(ugfx.JOY_LEFT, lambda pressed: btn_cb(c, 'L', pressed)) ugfx.input_attach(ugfx.JOY_RIGHT, lambda pressed: btn_cb(c, 'R', pressed)) ugfx.input_attach(ugfx.BTN_MID, lambda pressed: btn_cb(c, 'M', pressed)) ugfx.input_attach(ugfx.BTN_A, lambda pressed: btn_cb(c, 'A', pressed)) ugfx.input_attach(ugfx.BTN_B, lambda pressed: btn_cb(c, 'B', pressed)) # init BH1750 bh1750 = BH1750(i2c) print("Connected, waiting for event") lumi = {'d': {'luminance': {}}} try: while True: lumi['d']['luminance'] = bh1750.luminance(BH1750.ONCE_HIRES_1) c.publish(lumiTopic, json.dumps(lumi)) time.sleep_ms(300) #c.wait_msg() c.check_msg() finally: c.disconnect() ugfx.input_init() print("Disonnected")
def main(): c = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) c.set_callback(sub_cb) c.connect() c.subscribe(colorCommandTopic) c.subscribe(ledCommandTopic) # init input button ugfx.input_attach(ugfx.JOY_UP, lambda pressed: btn_cb(c, 'U', pressed)) ugfx.input_attach(ugfx.JOY_DOWN, lambda pressed: btn_cb(c, 'D', pressed)) ugfx.input_attach(ugfx.JOY_LEFT, lambda pressed: btn_cb(c, 'L', pressed)) ugfx.input_attach(ugfx.JOY_RIGHT, lambda pressed: btn_cb(c, 'R', pressed)) ugfx.input_attach(ugfx.BTN_MID, lambda pressed: btn_cb(c, 'M', pressed)) ugfx.input_attach(ugfx.BTN_A, lambda pressed: btn_cb(c, 'A', pressed)) ugfx.input_attach(ugfx.BTN_B, lambda pressed: btn_cb(c, 'B', pressed)) print("Connected, waiting for event") status = {'d': {'sine': {}}} count = 0 try: while True: status['d']['sine'] = sineVal(-1.0, 1.0, 16, count) count += 1 c.publish(statusTopic, json.dumps(status)) time.sleep_ms(1000) #c.wait_msg() c.check_msg() finally: c.disconnect() ugfx.input_init() print("Disonnected")
def main(): # Garbage Collection gc.collect() # init MQTT c = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) c.set_callback(sub_cb) c.connect() c.subscribe(colorCommandTopic) c.subscribe(ledCommandTopic) # init input button ugfx.input_attach(ugfx.JOY_UP, lambda pressed: btn_cb(c, 'U', pressed)) ugfx.input_attach(ugfx.JOY_DOWN, lambda pressed: btn_cb(c, 'D', pressed)) ugfx.input_attach(ugfx.JOY_LEFT, lambda pressed: btn_cb(c, 'L', pressed)) ugfx.input_attach(ugfx.JOY_RIGHT, lambda pressed: btn_cb(c, 'R', pressed)) ugfx.input_attach(ugfx.BTN_MID, lambda pressed: btn_cb(c, 'M', pressed)) ugfx.input_attach(ugfx.BTN_A, lambda pressed: btn_cb(c, 'A', pressed)) ugfx.input_attach(ugfx.BTN_B, lambda pressed: btn_cb(c, 'B', pressed)) # init MPU6050 # i2c = machine.I2C(scl=machine.Pin(26), sda=machine.Pin(25)) mpu = MPU(26, 25) mpu.calibrate() print("Connected, waiting for event") accel = { 'd': { 'acceleration_x': '', 'acceleration_y': '', 'acceleration_z': '', 'temperature': '', 'gyro_x': '', 'gyro_y': '', 'gyro_z': '', } } try: while True: x, y, z, t, dx, dy, dz = mpu.read_sensors_scaled() accel['d']['acceleration_x'] = x accel['d']['acceleration_y'] = y accel['d']['acceleration_z'] = z accel['d']['temperature'] = t / 340 + 36.53 accel['d']['gyro_x'] = dx accel['d']['gyro_y'] = dy accel['d']['gyro_z'] = dz c.publish(accelTopic, json.dumps(accel)) time.sleep_ms(500) #c.wait_msg() c.check_msg() finally: c.disconnect() ugfx.input_init() print("Disonnected")
def init_iotf(self): # Show self.view_manager.open_status_box() # Check for network availability self.view_manager.set_status_text('Waiting for network') if not util.wait_network(): self.view_manager.set_status_text('Cannot connect WiFi') raise Exception('Cannot connect WiFi') sta_if = network.WLAN(network.STA_IF) mac_addr = ''.join('{:02X}'.format(c) for c in sta_if.config('mac')) orgId = iotfcfg.orgId deviceType = iotfcfg.deviceType deviceId = iotfcfg.deviceId if hasattr(iotfcfg, 'deviceId') else mac_addr user = '******' authToken = iotfcfg.authToken clientID = 'd:' + orgId + ':' + deviceType + ':' + deviceId broker = orgId + '.messaging.internetofthings.ibmcloud.com' # Check for device registration url = 'https://hongjs-nodered.mybluemix.net/api/badge2018/type/{}/register'.format( deviceType) payload = { 'deviceId': deviceId, 'authToken': authToken, 'deviceInfo': {}, 'groups': [], 'location': {}, 'metadata': {} } headers = {'token': 'helloiot'} r = urequests.post(url, json=payload, headers=headers) if r.status_code == 201: print('OK') elif r.status_code == 409: print('Already Exists') else: print(r.text) raise Exception(r.text) r.close() self.deviceId = deviceId self.mqtt = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) self.mqtt.set_callback(self.sub_cb) self.mqtt.connect() self.mqtt.subscribe(self.COMMAND_TOPIC_RPS) # Close Popup self.view_manager.close_status_box()
def init_iotf(self): # Check for network availability print('Waiting for network') if not util.wait_network(3): print('Cannot connect WiFi') raise Exception('Cannot connect WiFi') sta_if = network.WLAN(network.STA_IF) mac_addr = ''.join('{:02X}'.format(c) for c in sta_if.config('mac')) orgId = iotfcfg.orgId deviceType = iotfcfg.deviceType deviceId = iotfcfg.deviceId if hasattr(iotfcfg, 'deviceId') else mac_addr user = '******' authToken = iotfcfg.authToken clientID = 'd:' + orgId + ':' + deviceType + ':' + deviceId broker = orgId + '.messaging.internetofthings.ibmcloud.com' self.deviceId = deviceId if orgId == 'quickstart': self.mqtt = simple.MQTTClient(clientID, broker) else: self.mqtt = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) self.mqtt.set_callback(self.sub_cb) self.mqtt.connect() if orgId == 'quickstart': print( 'https://quickstart.internetofthings.ibmcloud.com/?deviceId=test#/device/{}' .format(deviceId)) else: self.mqtt.subscribe(self.COMMAND_TOPIC_LED) self.mqtt.subscribe(self.COMMAND_TOPIC_BUZZER) print('DeviceID is {}'.format(deviceId)) print('IoT Ready')
def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = simple.MQTTClient(client_id, mqtt_server, user='******', password='******') client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) return client
def connect_and_subscribe_aws(): global client_id, topic_sub, mqtt_aws client_aws = simple.MQTTClient(client_id, mqtt_aws, user="******", password="******") client_aws.set_callback(sub_cb) client_aws.connect() client_aws.subscribe(topic_sub) return client_aws
def main(): c = simple.MQTTClient(clientID, broker) c.connect() print("https://quickstart.internetofthings.ibmcloud.com/#/device/{}/sensor/".format(deviceID)) status = {'d': {'sine':{}}} count = 0 try: while True: status['d']['sine'] = sineVal(-1.0, 1.0, 16, count) count += 1 c.publish(statusTopic, json.dumps(status)) time.sleep_ms(1000) finally: c.disconnect() print("Disonnected")
def main(): # Setup begins. status_led.on() config = catbus_config.Config() if not config.device_name: # We haven't been set up and can't do anything. return topic = config.mqtt_topic.encode('utf-8') def on_message(topic, data): if data == b'on': relay.on() elif data == b'off': relay.off() else: pass mqtt = umqtt.MQTTClient(config.device_name, config.mqtt_broker) mqtt.set_callback(on_message) mqtt.connect() mqtt.subscribe(topic, qos=1) def on_button_pressed(): relay.toggle() mqtt.publish(topic, relay.value_catbus(), retain=True, qos=1) button.set_callback(on_button_pressed) # Setup finished. status_led.off() while True: try: mqtt.wait_msg() except: status_led.on() try: mqtt.connect() mqtt.subscribe(topic, qos=1) status_led.off() except: time.sleep(1)
def __init__(self, alert_timeout=10, client_name='sha2017_badge', server='catbus.eth.moe', topic_info=None): self._alert = None self._alert_time = 0 self._alert_timeout = alert_timeout self._topic_info = topic_info def on_message(topic, data): if topic == self._topic_info: self._alert = str(data.decode('utf-8')).strip() self._alert_time = utime.time() self._client = umqtt.MQTTClient(client_name, server) self._client.set_callback(on_message) self._connect()
def main(): c = simple.MQTTClient(clientID, broker, user=user, password=authToken, ssl=True) c.set_callback(sub_cb) c.connect() c.subscribe(colorCommandTopic) c.subscribe(ledCommandTopic) print("Connected, waiting for event") status = {'d': {'sine':{}}} count = 0 try: while True: status['d']['sine'] = sineVal(-1.0, 1.0, 16, count) count += 1 c.publish(statusTopic, json.dumps(status)) time.sleep_ms(1000) #c.wait_msg() c.check_msg() finally: c.disconnect() print("Disonnected")
def main(server=webapp_cfg.MQTT_SERVER, port=webapp_cfg.MQTT_PORT): global client, timer client = umqtt.MQTTClient(dev_id, server, port) client.set_callback(sub_cb) while client.connect(clean_session=True): utime.sleep_ms(500) client.subscribe(t_dev_ctrl, 1) client.subscribe(t_period, 1) client.publish(t_dev_ctrl_cb, 'esp_init', False, 1) print("New MQTT session at device {}".format(dev_id)) gc.collect() try: while 1: if not toggle or utime.ticks_diff(utime.ticks_ms(), start) > 1000: try: client.check_msg() # umqtt.simple # try: client.wait_msg() # umqtt.robust except umqtt.MQTTException as e: print("MQTTException: {}".format(e)) else: start = utime.ticks_ms() finally: gc.collect() if not toggle: utime.sleep_ms(200) finally: print("\nDisconnecting MQTT client...") timer.deinit() client.publish(t_dev_ctrl_cb, 'esp_interrupted', False, 1) client.disconnect() print("MQTT client Disconnected!") gc.collect()
def __new__(self): print(self._instance) if not self._instance: self._instance = super(MQTTManager, self).__new__(self) self.mqttSettings = cm.ConfigurationManager().getMQTTConfig() self.unitSettings = cm.ConfigurationManager().getUnitConfig() self._server = self.mqttSettings["server"] self._username = self.mqttSettings["username"] self._password = self.mqttSettings["password"] self._default_topic = self.mqttSettings["defaultTopic"] self._clientId = self.unitSettings["Name"] self._port = self.mqttSettings["port"] self._socket_timeout = self.mqttSettings["timeout"] self._mq_connection = mq.MQTTClient(client_id=self._clientId, server=self._server, port=self._port, user=self._username, password=self._password) print("Init MQTTManager " + str(self._instance)) return self._instance
d = dht.DHT11(Pin(23)) wlan = network.WLAN(network.STA_IF) wlan.active(True) wlan.connect('', '') #连接WIFI ProductKey = '' DeviceName = '' DeviceSecret = '' CLIENT_ID = '' user_name = '' #用户名 user_password = '' #用户密码 SERVER = "" #阿里云物联网平台地址 PORT = 1883 client = mqtt.MQTTClient(client_id=CLIENT_ID, server=SERVER, port=PORT, user=user_name, password=user_password, keepalive=60) client.connect() client.set_callback(recvMessage) #设置回调函数 client.subscribe(" ") #订阅主题 while True: d.measure() print(d.humidity()) print(d.temperature()) send_mseg = { "params": { "Temperature": d.temperature(), "Humidity": d.humidity() },
def __init__(self, Config): # Needed Variables ## Version Version = 300000 ### First didget = Software type 1-Production 2-Beta 3-Alpha ### Secound and third didget = Major version number ### Fourth to sixth = Minor version number ## Dict holding all configs ### Fill with config from device.json if it failes self.Config will = False self.Config = Config ## Log Queue self.Log_Queue = list() ## Variable for Pin Monitor # Remember to pass Dobby aka self self.Pin_Monitor = DobbyPinMonitor.Init(self) ## Holds all loaded modules self.Modules = {} # Holds loaded System Modules like WirePusher if enabeled self.Sys_Modules = {} # Log relies on this to check if we need to blink on errors # So needs to be set before log is used the first time self.Indicator = None # If this is set, all subscribe and publishes will be mirrored and topic replaced as folles # <System Header>/<Hostname>/ = <self.gBridge> # We have to load this before mqtt so we know if we need to mirror topics self.gBridge_Topic = self.Config.get('gBridge_Topic', None) # I havent found a good way to get hardware info. # will use machine.EXT0_WAKE in a try statement # if we get AttibuteError then we know its a ESP8266 try: if machine.EXT0_WAKE == None: pass # ESP8266 except AttributeError: self.ESP_Type = 8266 # ESP32 else: self.ESP_Type = 32 # # import and Start webrepl if esp32 # import webrepl # webrepl.start() # self.Log(0, "System/webrepl", "Starting") # Import ntp time import ntptime # List of push messages that failed to send # we retry when online again self.Push_Queue = [] # MQTT Connection status self.MQTT_State = 'init' self.MQTT_Reconnect_At = 0 self.MQTT_Subscribe_To = [] # Init message self.Log(1, 'System', 'Initializing Dobby version: ' + str(Version)) # Subscribe to Commands topic self.MQTT_Subscribe(self.Peripherals_Topic("Commands")) # Change CPU frequancy if requested if Config.get('CPU_16', False) == True: machine.freq(160000000) self.Log(1, 'System', 'CPU frequancy set to: 16MHz') # ++++++++++++++++++++++++++++++++++++++++ WiFi setup ++++++++++++++++++++++++++++++++++++++++ # Setup WiFi # ## Log event self.Log(1, 'System', 'Connecting to WiFi SSID: ' + self.Config['WiFi_SSID']) ## Disable AP self.ap0 = network.WLAN(network.AP_IF) # Check if AP is active if self.ap0.active() == True: # Disable ap if active self.ap0.active(False) ## Setup wlan0 self.wlan0 = network.WLAN(network.STA_IF) # Activate wlan0 regardless if it is no not self.wlan0.active(True) # Check if the right SSID is configured if self.wlan0.config('essid') != self.Config['WiFi_SSID']: # Disconnect from incorrect ssid self.wlan0.disconnect() # Hostname only works with version 4 + # Set wifi hostname self.wlan0.config( dhcp_hostname=str.encode(self.Config['Hostname'])) # Connect to wifi self.wlan0.connect(self.Config['WiFi_SSID'], self.Config['WiFi_Password']) else: self.Log(0, 'WiFi', 'Config ok') # Var to indicate of we have published the ip we got when wifi connected self.wlan0_Published_IP = False # ++++++++++++++++++++++++++++++++++++++++ MQTT ++++++++++++++++++++++++++++++++++++++++ # Remember to add something raondom after the hostname so the borker see a new connecton # Check if we got a user and pass for mqtt # Generate Unique Post Hostname Post_Hostname = str(os.urandom(1)[0] % 1000) # Log event self.Log( 0, 'MQTT', 'Using hostname: ' + self.Config['Hostname'] + "-" + Post_Hostname) # Stores messages so we can act on them in MQTT Loop ## List containing Topic and payload ## [[<Topic>, <Payload>]] self.MQTT_Incomming_Queue = [] # Create MQTT Client self.MQTT_Client = MQTT.MQTTClient( self.Config['Hostname'] + "-" + Post_Hostname, self.Config['MQTT_Broker'], int(self.Config.get('MQTT_Port', 1883)), self.Config.get('MQTT_Username', None), self.Config.get('MQTT_Password', None)) # Set last will self.MQTT_Client.set_last_will( self.Config['System_Header'] + "/" + self.Config['Hostname'] + "/Log/Will", "Disconnected") # try to connect to mqtt self.MQTT_Connect() # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # Loop over config names in /conf and import matching modules ## Get config names Config_List = os.listdir('/conf') # Remove device.json since we dont want to use that again Config_List.remove('device.json') # Move relay to the front of the list if present ## try to remove for Entry in ['dimmer.json', 'relay.json']: try: Config_List.remove(Entry) ## if it fails do nothing except ValueError as e: pass ## If we removed relay.json add it back at the beginning of the list else: Config_List.insert(0, Entry) ## Loop over names in config for Name in Config_List: # Import the config ## False = Config not found or error during import ## If not false the imported Module will be returned Config = DobbyConfig.Load(Config_Name=Name, Delete_On_Error=False) Error = None # Load config is False if no config is found if Config is not False: # Try to import dobbydutton Module_Name = str('dobby.' + Name.replace('.json', '')) try: Module = __import__(Module_Name.replace(".", '/')) except (AttributeError, TypeError, SyntaxError, ImportError, KeyError) as e: Error = str(e) except MemoryError as e: Error = 'Not enough free memory. Free memory: ' + str( gc.mem_free()) finally: # Check if Module import ok if Error is None: # Log event self.Log(0, "System", "Module loaded: " + str(Module_Name)) # Pass config and get perifical object # Remember to pass Dobby aka self so we can log in Button and use dobby variables try: self.Modules[Name.replace('.json', '')] = Module.Init( self, Config) except self.Module_Error as e: Error = str(e) # Log event self.Log( 4, "System", "Unable to load module: " + str(Module_Name) + " - Error: " + Error) # Remove config file os.remove("/conf/" + Name) self.Log(1, "System", "Removed config file: /conf/" + Name) else: # Log event self.Log( 4, "System", "Unable to load module: " + str(Module_Name) + " - Error: " + Error) # Remove config file os.remove("/conf/" + Name) self.Log(1, "System", "Removed config file: /conf/" + Name) else: self.Log(0, 'System', "Invalid config: /conf/" + Name + "'") # Activate indicator if 'LED' owned by Indicator aka not used for something else # on esp32 its IO2 # on esp8266 its D4 if self.Pin_Monitor.Get_Owner(self.Pin_Monitor.LED) == 'Indicator': # check if indicator is already imported and init if self.Sys_Modules.get('indicator', None) == None: # Import Indicator import dobby.indicator # Init Indicator and store in Sys_Modules to enable loop self.Sys_Modules['indicator'] = dobby.indicator.Init( self, {"System": { "Pin": "LED" }}) # Create the indicator object self.Indicator = self.Sys_Modules['indicator'].Peripherals[ "System"] # indicator already imported to add an object in stead else: # Create the indicator object self.Indicator = self.Sys_Modules['indicator'].Add( "System", {"Pin": "LED"}) # On add the indicator will be blinked 3 times # will use this as boot blink # add wifi infication if disconnected if self.wlan0.isconnected() == False: self.Indicator.Add("WiFi", 4, "0.5s", "0.75s") else: # Log we could not enable indicator led self.Log(0, 'System/Indicator', "LED Pin in use, cannot enable system indicator") # Boot done message self.Log( 0, 'System', 'Dobby - Initialization compleate - Free memory: ' + str(gc.mem_free())) # Start loop() self.Loop()
# Get online import cellular cellular.gprs("internet", "", "") # Import mqtt (download client if necessary) try: from umqtt import simple except ImportError: import upip upip.install("micropython-umqtt.simple") from umqtt import simple # Turn GPS on import gps gps.on() # Report location name = "a9g-micropython-board" server = "test.mosquitto.org" topic = "a9g-micropython-board-topic" print( "To track messages run, for example\n mosquitto_sub -h {server} -t \"{topic}\" -v" .format(server=server, topic=topic)) import json client = simple.MQTTClient(name, server) client.connect() data = json.dumps(gps.get_last_location()) print("Publishing", data) client.publish(topic, data)
'deviceID': ''.join('{:02X}'.format(c) for c in sta_if.config('mac')), 'user': '******', 'authToken': 'badge{}'.format(str(random.random()).split('.')[1]), } conf.save() clientID = 'd:' + conf.data['orgID'] + ':' + conf.data[ 'deviceType'] + ':' + conf.data['deviceID'] broker = conf.data['orgID'] + '.messaging.internetofthings.ibmcloud.com' statusTopic = b'iot-2/evt/status/fmt/json' signalTopic = b'iot-2/evt/signal/fmt/json' ledCommandTopic = b'iot-2/cmd/led/fmt/json' irCommandTopic = b'iot-2/cmd/ir/fmt/json' if conf.data['orgID'] == 'quickstart': c = simple.MQTTClient(clientID, broker, ssl=False) print( 'Quickstart URL: https://quickstart.internetofthings.ibmcloud.com/#/device/{}/sensor/' .format(conf.data['deviceID'])) else: c = simple.MQTTClient(clientID, broker, user=conf.data['user'], password=conf.data['authToken'], ssl=True) # LED led_red = machine.Pin(17, machine.Pin.OUT, value=0) #led_blue = machine.Pin(16, machine.Pin.OUT, value=0) # IR
led.off() start = time.ticks_ms() sta_if.connect(config.SSID, config.passwd) while not sta_if.isconnected(): if time.ticks_diff(time.ticks_ms(), start) > 100000: print('Fail to connect to ', config.SSID) break led.on() # Connect to SMS WIFI # szzx_connection() # Connect to server global mqclient mqclient = mqtt.MQTTClient(config.MQTT_ID,config.MQTT_SERVER,\ port=config.MQTT_PORT,user=config.MQTT_USER,password=config.MQTT_PASSWD,\ ssl=config.MQTT_SSL) led.off() res = mqclient.connect() start = time.ticks_ms() while res is not 0: res = mqclient.connect() if time.ticks_diff(time.ticks_ms(), start) > 100000: print('Fail to connect to MQTT Broker at ', config.MQTT_SERVER) break led.on() # Initializing pins global pin pin = machine.Pin(config.IN_PIN, machine.Pin.IN) global pout
import time from ubinascii import hexlify import machine import network from umqtt import simple import bme280 SERVER = "192.168.123.195" CLIENT_ID = "ESP_" + str( hexlify(network.WLAN().config('mac')).decode()[6:].upper(), "utf-8") time.sleep_ms(10000) c = simple.MQTTClient("umqtt_client_" + CLIENT_ID, SERVER) c.DEBUG = False def main(): while True: try: i2c = machine.I2C(scl=machine.Pin(0), sda=machine.Pin(2)) bme = bme280.BME280(i2c=i2c, address=119) c.connect() c.publish(b"heartbeat", CLIENT_ID) c.publish(CLIENT_ID + "/temperature", bme.values[0]) c.publish(CLIENT_ID + "/pressure", bme.values[1]) c.publish(CLIENT_ID + "/humidity", bme.values[2]) print("published msg")
def main(): # -- animations ---- # these functions need access to `screen`, which is a local variable of the main() function, so they must be defined locally as well (or, alternatively, they could take it passed as an argument) # Generator function that takes a winning row in the format returned by # check() and makes it blink by alternatingly doing nothing (leaving the # pixels in their original color) and overwriting them with black. def blink(row): # as long as a drop animation is still running, do nothing while len(animations) > 1: yield # infinite loop, the blinking does not end by itself while True: # odd iterations: do nothing -> colored pixels yield # even iterations: black pixels for x, y in row: # x, y are in board coordinates, add 2 to convert to screen coordinates screen.pixel(x, y + 2, 0) yield # Generator function that takes the color and final position of a piece and # animates it dropping from the top down to that position. # Drawn over a board where the piece is already in the final position, so # - the final pixel must be erased # - the animation ends one before the final position def drop(color, x, y): # start at 1 (because the cursor was already at 0) and run up to and excluding y for i in range(1, y): # erase final position with black screen.pixel(x, y, 0) # draw at current position screen.pixel(x, i, color) yield # -- initialization ---- pew.init() # the framebuffer screen = pew.Pix() # the board board = pew.Pix(7, 6) # x coordinate of my cursor cursor = 3 # x coordinate of opponent's cursor opcursor = 3 # color value of whose turn it is (1=green, 2=red) turn = 1 # keys pressed in the previous game loop iteration (pew.keys() value), # initialized to "all keys pressed" in binary so that there cannot be a # rising edge in the first iteration prevk = 0b111111 # whether the game has ended, expressed by the return value of check(): # either False or the winning row, which counts as "true" becaues it is a # non-empty sequence won = False # a list of generators that implement any currently running animations animations = [] # read the player name from the configuration file # open for reading ('r'), in binary mode ('b') because we want the name as bytes, not as a string with open('four-name', 'rb') as f: myname = f.read() # various common parts of MQTT topics as bytes lobbyprefix = b'fourinarow/lobby/' lobbytopic = lobbyprefix + myname joinprefix = b'fourinarow/join/' jointopic = joinprefix + myname # set up the MQTT client object client = mqtt.MQTTClient('', 'mqtt.kolleegium.ch') # last will is the "leaving the lobby" message client.set_last_will(lobbytopic, b'', True) client.connect() # Whatever happens from now on, whether we exit by an error or by a # deliberate return, we want to close the connection in the end. Use a # try-finally statement for that. try: # -- lobby initialization ---- # I am present client.publish(lobbytopic, b'1', True) # the name of the player who joined us or whom we joined, currently nobody joined = None # all the player names in the lobby, as a set so we can easily add and remove them by value without getting duplicates lobby = set() # the lobby as a list for the menu, which can't directly take a set, and with the additional "exit" entry at the end lobbylist = ['>exit'] # create the menu generator, it keeps a reference to the list and will automatically pick up changes to it menu = menugen(screen, lobbylist) # callback for handling incoming MQTT messages while we're in the lobby def onMessageLobby(topic, message): # declare variables from the outer context that we want to assign to, otherwise assignment would create them as local variables of this function # access to other outer variables such as lobby or screen is read-only and needs no declaration nonlocal joined, mycolor # messages about players arriving and leaving if topic.startswith(lobbyprefix): username = topic[len(lobbyprefix):] # message is b'', which counts as false, or non-empty (expected b'1'), which counts as true if message: lobby.add(username) # flash a green bar at the bottom to indicate arrival # this works because onMessageLobby is called from client.check_msg(), which occurs after drawing the menu (in `for selected in menu`) but before `pew.show(screen)` screen.box(1, 0, 7, 8, 1) else: # use discard(), not remove() to avoid an exception if the name is not there # (it should, but we have no control over what messages others send us) lobby.discard(username) # red bar at the bottom to indicate departure screen.box(2, 0, 7, 8, 1) # update the list form of the lobby by # - transforming the elements of the set form using a list comprehension (they are bytes but the menu wants strings) # - inserting them using a slice index that replaces everything but the ">exit" item at the end # it's important that we modify this list in place, not create a totally new list, because this list is the one the menu generator has a reference to lobbylist[:-1] = [ str(n, 'ascii') for n in lobby if n != myname ] # messages about someone joining us elif topic == jointopic: # message content is the name of the other player joined = message # the joined player (us) gets red mycolor = 2 client.set_callback(onMessageLobby) # subscribe to all topics 1 level deep in the lobby (= user names) client.subscribe(lobbyprefix + b'+') client.subscribe(jointopic) # -- lobby loop ---- # repeatedly poke the menu generator, which draws the menu and handles buttons, until the user selects an entry - conveniently done by a for loop # assigns the returned index to `selected` every time - we don't need it during the loop, we only need the value from the last iteration afterwards for selected in menu: # while in the menu, we also repeatedly need to check for incoming MQTT messages - this calls onMessageLobby if there is any, which may set joined client.check_msg() if joined: # leave the for loop break pew.show(screen) # this is the frame rate expected by the menu for an appropriate animation speed pew.tick(1 / 24) # we can leave the loop above in two ways: # 1. when the menu generator ends, which is when the local user has selected an emtry from the menu # 2. by the `break` statement when someone else has sent us a join message # the `else` block of a `for` statement is executed in case 1 but not in case 2 else: # if selected == len(lobbylist) - 1, the user selected ">exit", otherwise another player if selected < len(lobbylist) - 1: # selected someone to join, look up who by their index, convert from string to bytes, and send them a join message joined = bytes(lobbylist[selected], 'ascii') client.publish(joinprefix + joined, myname) # the joining player gets green mycolor = 1 # in any case (whether we joined someone, were joined, or are exiting), we now leave the lobby client.publish(lobbytopic, b'', True) # clear the menu from the screen screen.box(0) pew.show(screen) # if the user chose ">exit", we're done, return from the main() function if not joined: # (the `finally` block at the end will still be executed because we're jumping out from inside the `try` block) return # -- game initialization ---- # more MQTT topics mygameprefix = b'fourinarow/game/' + myname + b'/' mycursortopic = mygameprefix + b'cursor' mydroptopic = mygameprefix + b'drop' opgameprefix = b'fourinarow/game/' + joined + b'/' opcursortopic = opgameprefix + b'cursor' opdroptopic = opgameprefix + b'drop' # Execute a move by dropping a piece of whose turn it is at the given column. def move(cursor): nonlocal won, turn # determine the topmost occupied (or beyond-the-bottom) place in the column by iterating from the top y = 0 while y < 6 and board.pixel(cursor, y) == 0: y += 1 # now either y == 6 (all were free) or place y was occupied, in both cases y-1 is the desired free place # unless the whole column was full (y == 0) if y != 0: # place the piece in the final position board.pixel(cursor, y - 1, turn) # start the drop animation - doesn't draw anything yet, just sets up the generator that will draw when poked animations.append(drop(turn, cursor, y + 1)) # check for winning rows won = check(board) # won is either False or a non-empty sequence that counts as true if won: # start the blink animation animations.append(blink(won)) # reverse the turn: 1 -> 2, 2 -> 1 turn = 3 - turn # callback for handling incoming MQTT messages while we're in the game def onMessageGame(topic, message): nonlocal opcursor # input validation: check length, otherwise if someone sends us an empty message we crash with an IndexError on the following line if topic == opcursortopic and len(message) == 1: opcursor = message[0] # input validation: the opponent is only allowed to make a move when it is their turn elif topic == opdroptopic and len( message) == 1 and turn == 3 - mycolor: # opponent's move move(message[0]) client.set_callback(onMessageGame) # subscribe to all of the opponent's game topics (cursor and drop) client.subscribe(opgameprefix + b'#') # initial update so the opponent knows where my cursor is from the start # convert number to one-element bytes by packing it into an intermediate tuple (needs trailing comma to distinguish from grouping parentheses) client.publish(mycursortopic, bytes((cursor, )), True) # -- game loop ---- while True: # -- input handling ---- k = pew.keys() # key handling is different depending on whether the game is running or over if not won: # check for bits in k using the bitwise AND operator - the result is zero or nonzero, which count as false or true if k & pew.K_LEFT: # move cursor left if possible and publish the new position if cursor > 0: cursor -= 1 client.publish(mycursortopic, bytes((cursor, )), True) if k & pew.K_RIGHT: # move cursor right if possible and publish the new position if cursor < 6: cursor += 1 client.publish(mycursortopic, bytes((cursor, )), True) # drop only if the respective key was not pressed in the last iteration, otherwise we would repeatedly drop while the key is held down (edge detection) if k & ~prevk & (pew.K_DOWN | pew.K_O | pew.K_X) and turn == mycolor: # my move move(cursor) client.publish(mydroptopic, bytes((cursor, )), False) else: # when the game is over, exit on a key press - several conditions to check: # - the first time we're getting here, the key that dropped the final piece may still be pressed - do nothing until all keys have been up in the previous iteration # - do nothing until the drop animation has completed and only the blink animation (which is endless) remains if prevk == 0 and k != 0 and len(animations) == 1: return # save the pressed keys for the next iteration to detect edges prevk = k # check for incoming messages, which may execute an opponent's move via onMessageGame client.check_msg() # -- drawing ---- # clear previous cursor, dropping piece, and turn indicator screen.box(0, 0, 0, 8, 2) if not won: # draw two cursors - if they overlap, in orange, otherwise in their respective color screen.pixel(cursor, 0, mycolor) screen.pixel(opcursor, 0, 3 if cursor == opcursor else 3 - mycolor) # turn indicator if turn == mycolor: screen.pixel(7, 1, turn) # draw the board (in unanimated state) screen.blit(board, 0, 2) # poke all active animations to draw one iteration each # we'll be removing items from the list while iterating over it, so we need to do it backwards to avoid skipping items # start at the last position (len-1), continue to 0 inclusively which is -1 exclusively, in steps of -1 for i in range(len(animations) - 1, -1, -1): try: # next() pokes, it raises StopIteration when the generator is exhausted (animation is over) next(animations[i]) except StopIteration: # remove completed animations del animations[i] # done drawing into the framebuffer, send it to the display pew.show(screen) # wait until it's time for the next frame # 0.15 seconds is an appropriate frame time for our animations and key repeating - increase it if you still find it hard to move the cursor by exactly one pixel # drawing at a faster rate would require more complex key repeat handling pew.tick(0.15) # end of game loop finally: # however we exited from the try block, by an error or by a deliberate return, leave the lobby and close the connection client.publish(lobbytopic, b'', True) client.disconnect()
# creating ADC object using I2C interface i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000) adc = ads1x15.ADS1115(i2c, 72, 5) adc.gain = 1 # adc = machine.ADC(0) red_led = Pin(12, Pin.OUT) red_led.value(True) # connecting to network do_connect(sta_if, SSID, PWD) # importing and creating mqtt object which connects to IBM cloud import umqtt.simple as mqtt client = mqtt.MQTTClient(CLIENT_ID, BROKER, user='******', password=TOKEN) client.connect() sleep(1) # reading data from ADC payload = {'Voltage': adc.read(0)} try: # publishing ADC data to IBM cloud client.publish(TOPIC, json.dumps(payload)) print('Published: ', payload) except OSError: print('Message was not published') print('Im awake, but Im going to sleep')
import umqtt.simple as simple #import cockle #cockle.connect('Kitchen2','c3fnh0ile') #id = cockle.suffix() id = 'myid' uplink = simple.MQTTClient(id, "cefn-artful-thinkpad") def notify(topic, message): print("Topic: {} Message {}".format(topic, message)) uplink.set_callback(notify) uplink.connect() uplink.publish(topic='yo',msg='mars',retain=True,qos=1) uplink.subscribe(topic='hello') while True: uplink.wait_msg()
def __init__(self, Config): # Needed Variables ## Version Version = 300000 ### First didget = Software type 1-Production 2-Beta 3-Alpha ### Secound and third didget = Major version number ### Fourth to sixth = Minor version number ## Dict holding all configs ### Fill with config from device.json if it failes self.Config will = False self.Config = Config ## Log Queue self.Log_Queue = list() ## Variable for Pin Monitor # Remember to pass Dobby aka self self.Pin_Monitor = DobbyPinMonitor.Init(self) ## Holds all loaded modules self.Modules = {} # Holds loaded System Modules like WirePusher if enabeled self.Sys_Modules = {} # Log relies on this to check if we need to blink on errors # So needs to be set before log is used the first time self.IndicatorLED = None # If this is set, all subscribe and publishes will be mirrored and topic replaced as folles # <System Header>/<Hostname>/ = <self.gBridge> # We have to load this before mqtt so we know if we need to mirror topics self.gBridge_Topic = self.Config.get('gBridge_Topic', None) # MQTT Connection status self.MQTT_State = 'init' self.MQTT_Reconnect_At = 0 self.MQTT_Subscribe_To = [] # Init message self.Log(1, 'System', 'Initializing Dobby version: ' + str(Version)) # Subscribe to Commands topic self.MQTT_Subscribe(self.Peripherals_Topic("Commands")) # Change CPU frequancy if requested if Config.get('CPU_16', False) == True: machine.freq(160000000) self.Log(1, 'System', 'CPU frequancy set to: 16MHz') # ++++++++++++++++++++++++++++++++++++++++ WiFi setup ++++++++++++++++++++++++++++++++++++++++ # Setup WiFi # ## Log event self.Log(1, 'System', 'Connecting to WiFi SSID: ' + self.Config['WiFi_SSID']) ## Disable AP self.ap0 = network.WLAN(network.AP_IF) # Check if AP is active if self.ap0.active() == True: # Disable ap if active self.ap0.active(False) ## Setup wlan0 self.wlan0 = network.WLAN(network.STA_IF) # Activate wlan0 self.wlan0.active(True) # Set wifi hostname self.wlan0.config(dhcp_hostname=str(self.Config['Hostname'])) # Connect to wifi self.wlan0.connect( self.Config['WiFi_SSID'], self.Config['WiFi_Password'], ) # Check if we connected if self.wlan0.isconnected() == True: # Log ip self.Log(0, 'WiFi', 'Got IP: ' + str(self.wlan0.ifconfig()[0])) else: # Log ip self.Log(0, 'WiFi', "Not connected") # ++++++++++++++++++++++++++++++++++++++++ MQTT ++++++++++++++++++++++++++++++++++++++++ # Remember to add something raondom after the hostname so the borker see a new connecton # Check if we got a user and pass for mqtt # Generate Unique Post Hostname Post_Hostname = str(os.urandom(1)[0] % 1000) # Log event self.Log( 0, 'MQTT', 'Using hostname: ' + self.Config['Hostname'] + "-" + Post_Hostname) # Stores messages so we can act on them in MQTT Loop ## List containing Topic and payload ## [[<Topic>, <Payload>]] self.MQTT_Incomming_Queue = [] # Create MQTT Client self.MQTT_Client = MQTT.MQTTClient( self.Config['Hostname'] + "-" + Post_Hostname, self.Config['MQTT_Broker'], int(self.Config.get('MQTT_Port', 1883)), self.Config.get('MQTT_Username', None), self.Config.get('MQTT_Password', None)) # Set last will self.MQTT_Client.set_last_will( self.Config['System_Header'] + "/" + self.Config['Hostname'] + "/Log/Will", "Disconnected") # try to connect to mqtt self.MQTT_Connect() # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # ++++++++++++++++++++++++++++++++++++++++ Setup peripherals ++++++++++++++++++++++++++++++++++++++++ # Loop over config names in /conf and import matching modules ## Get config names Config_List = os.listdir('/conf') # Remove device.json since we dont want to use that again Config_List.remove('device.json') # Move relay to the front of the list if present ## try to remove for Entry in ['dimmer.json', 'relay.json']: try: Config_List.remove(Entry) ## if it fails do nothing except ValueError as e: pass ## If we removed relay.json add it back at the beginning of the list else: Config_List.insert(0, Entry) ## Loop over names in config for Name in Config_List: # Import the config ## False = Config not found or error during import ## If not false the imported Module will be returned Config = DobbyConfig.Load(Config_Name=Name, Delete_On_Error=False) Error = None # Load config is False if no config is found if Config is not False: # Try to import dobbydutton Module_Name = str('dobby.' + Name.replace('.json', '')) try: Module = __import__(Module_Name.replace(".", '/')) except (AttributeError, TypeError, SyntaxError, ImportError, KeyError) as e: Error = str(e) except MemoryError as e: Error = 'Not enough free memory. Free memory: ' + str( gc.mem_free()) finally: # Check if Module import ok if Error is None: # Log event self.Log(0, "System", "Module loaded: " + str(Module_Name)) # Pass config and get perifical object # Remember to pass Dobby aka self so we can log in Button and use dobby variables try: self.Modules[Name.replace('.json', '')] = Module.Init( self, Config) except self.Module_Error as e: Error = str(e) # Log event self.Log( 4, "System", "Unable to load module: " + str(Module_Name) + " - Error: " + Error) # Remove config file os.remove("/conf/" + Name) self.Log(1, "System", "Removed config file: /conf/" + Name) else: # Log event self.Log( 4, "System", "Unable to load module: " + str(Module_Name) + " - Error: " + Error) # Remove config file os.remove("/conf/" + Name) self.Log(1, "System", "Removed config file: /conf/" + Name) else: self.Log(0, 'System', "Invalid config: /conf/" + Name + "'") # Activate indicator led if D4 owned by IndicatorLED aka not used for something else if self.Pin_Monitor.Pins['D4']['Owner'] == 'IndicatorLED': # Import IndicatorLED import dobby.indicatorled # Init IndicatorLED and store in Sys_Modules to enable loop self.Sys_Modules['IndicatorLED'] = dobby.indicatorled.Init(self) # Do boot blink if IndicatorLED is configured self.Sys_Modules['IndicatorLED'].Enable('Booting') # Boot done message self.Log( 0, 'System', 'Dobby - Initialization compleate - Free memory: ' + str(gc.mem_free())) # Start loop() self.Loop()
def main(): # -- animations ---- def blink(row): while len(animations) > 1: yield while True: yield for x, y in row: screen.pixel(x, y + 2, 0) yield def drop(color, x, y): for i in range(1, y): screen.pixel(x, y, 0) screen.pixel(x, i, color) yield # -- initialization ---- pew.init() screen = pew.Pix() board = pew.Pix(7, 6) cursor = 3 opcursor = 3 turn = 1 prevk = 0b111111 won = False animations = [] with open('four-name', 'rb') as f: myname = f.read() lobbyprefix = b'fourinarow/lobby/' lobbytopic = lobbyprefix + myname joinprefix = b'fourinarow/join/' jointopic = joinprefix + myname client = mqtt.MQTTClient('', 'mqtt.kolleegium.ch') client.set_last_will(lobbytopic, b'', True) client.connect() try: # -- lobby initialization ---- client.publish(lobbytopic, b'1', True) joined = None lobby = set() lobbylist = ['>exit'] menu = menugen(screen, lobbylist) def onMessageLobby(topic, message): nonlocal joined, mycolor if topic.startswith(lobbyprefix): username = topic[len(lobbyprefix):] if message: lobby.add(username) screen.box(1, 0, 7, 8, 1) else: lobby.discard(username) screen.box(2, 0, 7, 8, 1) lobbylist[:-1] = [ str(n, 'ascii') for n in lobby if n != myname ] elif topic == jointopic: joined = message mycolor = 2 client.set_callback(onMessageLobby) client.subscribe(lobbyprefix + b'+') client.subscribe(jointopic) # -- lobby loop ---- for selected in menu: client.check_msg() if joined: break pew.show(screen) pew.tick(1 / 24) else: if selected < len(lobbylist) - 1: joined = bytes(lobbylist[selected], 'ascii') client.publish(joinprefix + joined, myname) mycolor = 1 client.publish(lobbytopic, b'', True) screen.box(0) pew.show(screen) if not joined: return # -- game initialization ---- mygameprefix = b'fourinarow/game/' + myname + b'/' mycursortopic = mygameprefix + b'cursor' mydroptopic = mygameprefix + b'drop' opgameprefix = b'fourinarow/game/' + joined + b'/' opcursortopic = opgameprefix + b'cursor' opdroptopic = opgameprefix + b'drop' def move(cursor): nonlocal won, turn y = 0 while y < 6 and board.pixel(cursor, y) == 0: y += 1 if y != 0: board.pixel(cursor, y - 1, turn) animations.append(drop(turn, cursor, y + 1)) won = check(board) if won: animations.append(blink(won)) turn = 3 - turn def onMessageGame(topic, message): nonlocal opcursor if topic == opcursortopic and len(message) == 1: opcursor = message[0] elif topic == opdroptopic and len( message) == 1 and turn == 3 - mycolor: move(message[0]) client.set_callback(onMessageGame) client.subscribe(opgameprefix + b'#') client.publish(mycursortopic, bytes((cursor, )), True) # -- game loop ---- while True: # -- input handling ---- k = pew.keys() if not won: if k & pew.K_LEFT: if cursor > 0: cursor -= 1 client.publish(mycursortopic, bytes((cursor, )), True) if k & pew.K_RIGHT: if cursor < 6: cursor += 1 client.publish(mycursortopic, bytes((cursor, )), True) if k & ~prevk & (pew.K_DOWN | pew.K_O | pew.K_X) and turn == mycolor: move(cursor) client.publish(mydroptopic, bytes((cursor, )), False) else: if prevk == 0 and k != 0 and len(animations) == 1: return prevk = k client.check_msg() # -- drawing ---- screen.box(0, 0, 0, 8, 2) if not won: screen.pixel(cursor, 0, mycolor) screen.pixel(opcursor, 0, 3 if cursor == opcursor else 3 - mycolor) if turn == mycolor: screen.pixel(7, 1, turn) screen.blit(board, 0, 2) for i in range(len(animations) - 1, -1, -1): try: next(animations[i]) except StopIteration: del animations[i] pew.show(screen) pew.tick(0.15) finally: client.publish(lobbytopic, b'', True) client.disconnect()
# config thing_id = 'team_name' #all lowercase, _ separator, no special chars company_name = 'your_company_name' endpoint = 'aws_iot_endpoint_dns_hostname' publish_rate = 5 # seconds between publishing messages fnames = os.listdir() cert = read_pem('.crt') key = read_pem('.key') topic = "iotsample/%s/%s/data" % (company_name, thing_id) client = mqtt.MQTTClient(thing_id, endpoint, ssl=True, ssl_params={ 'key': key, 'cert': cert }) while True: client.connect() ''' data = { "thingId": thing_id, "time": time(), "temperature": foo, "humidity": bar, "light": baz } '''