Example #1
0
async def wifi_config():
    global cfg
    global client
    global CLIENT_ID
    print('load configuration')
    f = open('config.json')
    cfg = json.loads(f.read())
    f.close()
    print(cfg)
    print('starting wifi connection')
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(cfg['ap']['ssid'], cfg['ap']['pwd'])
    while not wlan.isconnected():
        print('wait connection...')
        await asyncio.sleep(1)
    wlan.ifconfig()
    mqtt_cfg = cfg['mqtt']
    client = MQTTClient(
        CLIENT_ID, mqtt_cfg["broker"], 
        port=mqtt_cfg["port"], 
        keepalive=mqtt_cfg["keepalive"])
    will_msg = {'id': CLIENT_ID, 
        'status': False, 
        'msg': 'The connection from this device is lost:('
    }
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
Example #2
0
 def connect(self, keepAlive, clean_session):
     self.formatConnectInfo()
     mqtt_client = MQTTClient(self.clientid, self.mqtt_server, 1883,
                              self.username, self.password, keepAlive)
     mqtt_client.connect(clean_session=clean_session)
     mqtt_client.set_callback(self.proc)
     return mqtt_client
Example #3
0
def main(led_pin):
    i2c = I2C(-1, scl=Pin(5), sda=Pin(4))
    pca = Servos(i2c, min_us=500, max_us=2500)

    def domoticz_out(topic, msg):
        data = json.loads(msg)
        if data['idx'] == settings.CURTAIN_IDX:
            if data['nvalue'] == 1:
                pca.position(0, us=500)
            else:
                pca.position(0, us=1500)

    mqtt = MQTTClient(settings.CLIENT_ID,
                      settings.MQTT_SERVER,
                      user=settings.MQTT_USER,
                      password=settings.MQTT_PASSWD)
    mqtt.set_callback(domoticz_out)
    mqtt.connect()
    mqtt.subscribe(settings.SUB_TOPIC)
    print('Connected to {}, subscribed to {} topic'.format(
        settings.MQTT_SERVER, settings.SUB_TOPIC))

    while True:
        led_pin.value(0)
        mqtt.check_msg()
        lightsleep(100)
        led_pin.value(1)
        lightsleep(1000)
def MQTT_Init():
    # 创建一个mqtt实例
    c = MQTTClient(client_id=CLIENT_ID,
                   server=SERVER,
                   port=PORT,
                   user=USER,
                   password=PASSWORD,
                   keepalive=30)  # 必须要 keepalive=30 ,否则连接不上
    # 设置消息回调
    c.set_callback(sub_cb)
    # 建立连接
    try:
        c.connect()
    except Exception as e:
        print('!!!,e=%s' % e)
        return
    # c.connect()
    # 订阅主题
    c.subscribe(SUB_TOPIC.format(IMEI))
    # 发布消息
    Payload = '{"DeviceName":"{}","msg":"test publish"}'.format(IMEI)
    c.publish(PUB_TOPIC.format(IMEI), Payload)

    while True:
        c.wait_msg()
        if state == 1:
            break

    # 关闭连接
    c.disconnect()
def connected():
    global client
    client = MQTTClient(CLIENT_ID, 'q.emqtt.com', port=1883, keepalive=20)
    will_msg = {'id': CLIENT_ID, 'status': False, 'msg': 'The connection from this device is lost:('}
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/12345/switch', 0)
    client.subscribe('/device/4567/switch', 0)     
Example #6
0
def connect_and_subscribe():
    global client
    client = MQTTClient(CONFIG['client_id'], CONFIG['broker'])
    client.set_callback(callback)
    client.connect()
    print("Connected to {}".format(CONFIG['broker']))
    topic = topic_name(b"control")
    client.subscribe(topic)
    print("Subscribed to {}".format(topic))
Example #7
0
def mqtt_connect():
  client = MQTTClient(CLIENT_ID, SERVER, port=1883)
  client.set_callback(mqtt_callback)
  client.connect()
  print("mqtt connect success")
  client.subscribe(TOPIC)
  while True:
    client.check_msg()
    time.sleep(1)
    print("wait ...")
Example #8
0
def recepcionMQTT(server=SERVER, topic=TOPIC3):
    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(topic)
    #print("Connected to %s, subscribed to %s topic" % (server, topic))
    try:
        c.wait_msg()
    finally:
        c.disconnect()
Example #9
0
def recepcionMQTT(server=SERVER, topic=TOPIC3):
    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(topic)
    #print("Connected to %s, subscribed to %s topic" % (server, topic))
    try:
        c.wait_msg()
    finally:
        c.disconnect()
Example #10
0
def sendmq(msg):
    UNIQUE_ID = ubinascii.hexlify(machine.unique_id())
    MQTT_BROKER = "192.168.2.68"
    MQTT_PORT = 1883
    MQTT_TOPIC = "iot-2/type/lopy/id/" + "buhardilla" + "/evt/presence1/fmt/json"
    print(MQTT_TOPIC)
    mqtt_client = MQTTClient(UNIQUE_ID, MQTT_BROKER, port=MQTT_PORT)
    mqtt_client.settimeout = settimeout
    mqtt_client.set_callback(t3_publication)
    mqtt_client.connect()
    result = mqtt_client.publish(MQTT_TOPIC, json.dumps(msg))
    mqtt_client.disconnect()
    return result
Example #11
0
 def connect(self, mqt_id, secret, hmac_msg, keepAlive, clean_session, ssl):
     mqt_server = MQTT_SERVER.format(self.productKey)
     self.password = hmac.new(bytes(secret, "utf8"),
                              msg=bytes(hmac_msg, "utf8"),
                              digestmod=sha256).hexdigest()
     mqtt_client = MQTTClient(mqt_id,
                              mqt_server,
                              self.port,
                              self.username,
                              self.password,
                              keepAlive,
                              ssl=ssl)
     mqtt_client.set_callback(self.proc)
     mqtt_client.connect(clean_session=clean_session)
     return mqtt_client
Example #12
0
class MqttClient():
    '''
    mqtt init
    '''

    def __init__(self, clientid, server, port, pw):
        self.clientid = clientid
        self.pw = pw
        self.server = server
        self.port = port
        self.uasename = clientid
        self.client = None

    def connect(self):
        self.client = MQTTClient(self.clientid, self.server, self.port, self.uasename, self.pw, keepalive=300)
        self.client.set_callback(self.sub_cb)
        self.client.connect()

    def sub_cb(self, topic, msg):
        print("Subscribe Recv:   %s, %s" % (topic.decode(), msg.decode()))

    def subscribe(self, topic, qos=0):
        self.client.subscribe(topic, qos)

    def publish(self, topic, msg, qos=0):
        self.client.publish(topic, msg, qos)

    def disconnect(self):
        self.disconnect()

    def __loop_forever(self, t):
        # print("loop_forever")
        try:
            self.client.ping()
        except:
            return -1

    def __listen(self):
        while True:
            try:
                self.client.wait_msg()
            except OSError as e:
                return -1

    def start(self):
        _thread.start_new_thread(self.__listen, ())
        t = Timer(1)
        t.start(period=20000, mode=t.PERIODIC, callback=self.__loop_forever)
Example #13
0
def mqtt_connection(cfg):
    global client
    global CLIENT_ID
    client = MQTTClient(CLIENT_ID,
                        cfg["broker"],
                        port=cfg["port"],
                        keepalive=cfg["keepalive"])
    will_msg = {
        'id': CLIENT_ID,
        'status': False,
        'msg': 'The connection from this device is lost:('
    }
    client.set_last_will('/device/will/status', json.dumps(will_msg))
    client.set_callback(on_message)
    client.connect()
    client.subscribe('/device/{0}/switch'.format(CLIENT_ID.decode("utf-8")), 0)
Example #14
0
def main(server="localhost"):
    c = MQTTClient("umqtt_client", server)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"foo_topic")
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            c.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep(1)

    c.disconnect()
Example #15
0
def main(server=SERVER):

    c = MQTTClient(CLIENT_ID, server)
    # Subscribed messages will be delivered to this callback
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    print("Connected to %s, subscribed to %s topic" % (server, TOPIC))

    np_clear()

    #np_status_blink()

    try:
        while 1:
            #micropython.mem_info()
            c.wait_msg()
    finally:
        c.disconnect()
Example #16
0
def main(server="localhost"):
    c = MQTTClient(client_id=CLIENT_ID,
                   server=SERVER,
                   port=1883,
                   user=USER,
                   password=PASSWORD)
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(TOPIC)
    while True:
        if True:
            # Blocking wait for message
            c.wait_msg()
        else:
            # Non-blocking wait for message
            c.check_msg()
            # Then need to sleep to avoid 100% CPU usage (in a real
            # app other useful actions would be performed instead)
            time.sleep(1)

    c.disconnect()
Example #17
0
class Mqtt_Class():
    def __init__(self):
        # 创建一个mqtt实例
        self.client_id = "868540051778302"
        self.downtopic = "quec/868540051778302/down"
        self.uptopic = "quec/868540051778302/up"
        self.mqttserver = "southbound.quectel.com"
        self.mqttport = 1883
        self.uername = "868540051778302"
        self.passwd = "d40332b8211097ffbb0e2645c2efec95"
        self.mqtt_client = MQTTClient(self.client_id, self.mqttserver,
                                      self.mqttport, self.uername, self.passwd)

    def mqtt_recv_callback(self, topic, msg):
        print("Subscribe Recv: Topic={},Msg={}".format(topic.decode(),
                                                       msg.decode()))
        q_recv_thread.recv_thread.recv_callback(topic, msg.decode())

    def mqtt_set_recv_callback(self):
        # 设置消息回调
        self.mqtt_client.set_callback(self.mqtt_recv_callback)

    def connect(self):
        #建立连接
        self.mqtt_client.connect()

    def sub_topic(self, topic):
        # 订阅主题
        self.mqtt_client.subscribe(topic)

    def put_msg(self, msg, qos=0):
        # 发布消息
        self.mqtt_client.publish(self.uptopic, msg, qos)

    def wait_msg(self):
        self.mqtt_client.wait_msg()

    def disconnect(self):
        # 关闭连接
        self.mqtt_client.disconnect()
def MQTT_Init():
    # 创建一个mqtt实例
    c = MQTTClient(client_id=CLIENT_ID,
                   server=SERVER,
                   port=PORT,
                   user=USER,
                   password=PASSWORD,
                   keepalive=30)  # 必须要 keepalive=30 ,否则连接不上
    # 设置消息回调
    c.set_callback(sub_cb)
    # 建立连接
    c.connect()
    # 订阅主题
    c.subscribe('$oc/devices/{}/sys/messages/down'.format(DEVICE_ID))

    msg = b'''{
        "services": [{
            "service_id": "WaterMeterControl",
            "properties": {
                "state": "T:15c,  H: 85% "
            },
            "event_time": "20151212T121212Z"
        }
        ]
    }'''

    # 发布消息
    c.publish('$oc/devices/{}/sys/properties/report'.format(DEVICE_ID), msg)

    while True:
        c.wait_msg()
        if state == 1:
            break

    # 关闭连接
    c.disconnect()
Example #19
0
pycom.rgbled(0xf0d0000)  # Status orange: partially working
time.sleep(1)
pycom.rgbled(0x000000)

# Use the MQTT protocol to connect to Bluemix
print("Try to connect to IBM iot")
myiotorg = "5q6gu4"
client = MQTTClient("d:" + myiotorg + ":playbulb:playbulb30",
                    myiotorg + ".messaging.internetofthings.ibmcloud.com",
                    port=1883,
                    user="******",
                    password="******")
#client = MQTTClient(“d:<ORG Id>:<Device Type>:<Device Id>“, “<ORG Id>.messaging.internetofthings.ibmcloud.com”,user=”use-token-auth”, password=”<TOKEN>“, port=1883)
#print(client)
# Subscribed messages will be delivered to this callback
client.set_callback(sub_cb)
client.connect()
#client.subscribe(AIO_CONTROL_FEED)
#print("Connected to %s, subscribed to %s topic" % (AIO_SERVER, AIO_CONTROL_FEED))
print("Connected to Bluemix")
pycom.rgbled(0x00f000)  # Status green: online to Bluemix
#Publish a Hallo
#msg={"id":'+ubinascii.hexlify(network.LoRa().mac()).decode("utf-8")+',"value":"hello","type":"GW","msgid":0}
#o = json.loads(msg)
#o['type']="GW"
#o['gwid']=ubinascii.hexlify(network.LoRa().mac()).decode("utf-8")
#print(o)
#c=json.dumps(o)
print("Send a Hello to Bluemix")
client.publish(topic="iot-2/evt/hello/fmt/json",
               msg='{"value":"hello","type":"GW","msgid":0}')
Example #20
0
# Recepcion
def sub_cb(topic, msg):
    global state
    print((topic, msg))
    if msg == b"on":
        led.value(0)
        state = 1
    elif msg == b"off":
        led.value(1)
        state = 0
    elif msg == b"toggle":
        # LED is inversed, so setting it to current state
        # value will make it toggle
        led.value(state)


state = 1 - state
client_mqtt = MQTTClient(CLIENT_ID, SERVER)
# Subscribed messages will be delivered to this callback
client_mqtt.set_callback(sub_cb)
client_mqtt.connect()
client_mqtt.subscribe(TOPIC5)
print("Connected to %s, subscribed to %s topic" % (SERVER, TOPIC5))

try:
    while 1:
        # micropython.mem_info()
        client_mqtt.wait_msg()
finally:
    client_mqtt.disconnect()
Example #21
0
from machine import I2C, Pin
from dht12 import DHT12
from BH1750 import BH1750
import ssd1306
import time, json, machine, ubinascii
import _thread as th
from umqtt import MQTTClient
import wifi_connect as wlan
CLIENT_ID = ubinascii.hexlify(machine.unique_id())
client = None
# OLED
rst = Pin(16, Pin.OUT)
rst.value(1)
oledScl = Pin(15, Pin.OUT, Pin.PULL_UP)
oledSda = Pin(4, Pin.OUT, Pin.PULL_UP)
i2cOled = I2C(scl=oledScl, sda=oledSda, freq=450000)
oled = ssd1306.SSD1306_I2C(128, 64, i2cOled, addr=0x3c)
oled.fill(0)
oled.text('SENSOR', 40, 5)
oled.text('MicroPython', 10, 20)
oled.text('Waiting...', 10, 35)
oled.show()
wlan.connect()
oled.text('{0}'.format(wlan.get_ip()), 10, 50)
oled.show()
# MQTTClient
time.sleep(3)

def on_message(topic, msg):
    print(topic, msg)
Example #22
0
from umqtt import MQTTClient
import machine, ubinascii
import time
import network

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('HUAWEI', '0000000000')
while not wlan.isconnected():
    print('Wait connection')
    time.sleep(1)


def on_message(topic, msg):
    print(topic, msg)


CLIENT_ID = ubinascii.hexlify(machine.unique_id())
client = MQTTClient(CLIENT_ID, 'iot.eclipse.org', port=1883)
client.set_callback(on_message)
client.connect()
client.subscribe('micro/python/test')

while True:
    client.wait_msg()
Example #23
0
File: code.py Project: chain01/wiki
from umqtt import MQTTClient
state = 0


def sub_cb(topic, msg):
    global state
    print("subscribe recv:")
    print(topic, msg)
    state = 1


#创建一个 mqtt 实例
c = MQTTClient("umqtt_client", "mq.tongxinmao.com", '18830')
#设置消息回调
c.set_callback(sub_cb)
#建立连接
c.connect()
#订阅主题
c.subscribe(b"/public/TEST/quecpython")
print(
    "Connected to mq.tongxinmao.com, subscribed to /public/TEST/quecpython topic"
)
#发布消息
c.publish(b"/public/TEST/quecpython", b"my name is Kingka!")
print("Publish topic: /public/TEST/quecpython, msg: my name is Quecpython")

while True:
    c.wait_msg()  #阻塞函数,监听消息
    if state == 1:
        break
#关闭连接
Example #24
0
def msg(topic, msg):
    print(msg)
    if msg.decode() == 'reset':
        reset()


subscribed = False
pycom.heartbeat(False)
wlan = WLAN(mode=WLAN.STA)
#Set pin G23 as input with resistor down
P2 = Pin('P2', mode=Pin.IN, pull=Pin.PULL_DOWN)
button = Pin("G17", Pin.IN, pull=Pin.PULL_UP)
#id of client and ip of Pi wifi
mqtt = MQTTClient('LoPy', '192.168.5.1')
mqtt.set_callback(msg)
if not wlan.isconnected():
    boot.wlanConnect()
isConnected = tryConnect()

try:
    #uos.stat throws error if count.txt doesn't exist
    uos.stat('count.txt')
    #tries to read count of previous run, if can't thne count =  0
    with open('count.txt', 'r') as f:
        try:
            count = int(f.read())
        except:
            count = 0
            f.close()
    #wipe count.txt and write count of old run
class Game():
    def __init__(self, playerName, computerName):  #初始化
        #网络设定
        #WiFi名称和密码
        self.wifi_name = "NEUI"
        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        SERVER = "112.125.89.85"  #MQTT服务器地址
        SERVER_PORT = 3881  #MQTT服务器端口
        DEVICE_ID = "wc001"  #设备ID
        TOPIC1 = b"/cloud-skids/online/dev/" + DEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + DEVICE_ID
        CLIENT_ID = "f25410646a8348f8a1726a3890ad8f81"
        #设备状态
        ON = "1"
        OFF = "0"
        #对方的选择
        self.d = ["1", "2", "3"]
        self.choose = 0
        self.mark = 0
        #启动网络连接
        self.do_connect()
        gc.collect()
        self.client = MQTTClient(CLIENT_ID, SERVER, SERVER_PORT)
        self.client.set_callback(self.sub_cb)  #设置回调
        self.client.connect()
        print("连接到服务器:%s" % SERVER)
        self.client.publish(TOPIC1, ON)  #发布“1”到TOPIC1
        self.client.subscribe(self.TOPIC2)  #订阅TOPIC
        #游戏设定
        self.gameStart = False
        self.playerName = playerName
        self.computerName = computerName
        self.playerScore = 0
        self.computerScore = 0
        self.equalNum = 0
        self.playerStatus = 0
        self.computerStatus = 0
        for p in pins:
            keys.append(Pin(p, Pin.IN))
        self.displayInit()

    def do_connect(self):
        sta_if = network.WLAN(network.STA_IF)  #STA模式
        ap_if = network.WLAN(network.AP_IF)  #AP模式
        if ap_if.active():
            ap_if.active(False)  #关闭AP
        if not sta_if.isconnected():
            print('Connecting to network...')
        sta_if.active(True)  #激活STA
        sta_if.connect(self.wifi_name, self.wifi_SSID)  #WiFi的SSID和密码
        while not sta_if.isconnected():
            pass
        print('Network config:', sta_if.ifconfig())

    def sub_cb(self, topic, message):
        message = message.decode()
        print("mark is :", self.mark)
        #赋值给choose
        self.choose = int(message)

        if (self.choose < 20):  #来自1号自己的信息,不判断
            print("对方尚未选择")
            return
        elif (self.choose > 20):
            self.mark = self.mark + 1  #修改标志,代表一方已完成选择
            print("player1 get choose is :", self.choose)
            #处理所得信息
            self.computerStatus = self.choose - 20
            #显示对方结果
            text.draw(str(self.computerStatus), 172, 152, 0x000000, 0xffffff)
        #判断胜负并显示结果
        if self.mark % 2 == 0:  #如果双方都完成选择
            resultMessage = " 平局 "
            if self.computerStatus == 0:
                return
            elif (self.playerStatus == self.computerStatus):
                self.equalNum += 1
            elif (self.playerStatus > self.computerStatus):
                self.playerScore += 1
                resultMessage = "%s胜出" % self.playerName
            elif (self.playerStatus < self.computerStatus):
                self.computerScore += 1
                resultMessage = "%s胜出" % self.computerName
            text.draw(resultMessage, 90, 210, 0x000000, 0xffffff)
            self.updateTotolArea()

    def displayInit(self, x=10, y=10, w=222, h=303):
        #显示游戏规则信息
        mentionStr1 = "游戏规则:"
        mentionStr2 = "双方随机生成1-6的数"
        mentionStr3 = "按键1-3选择 按键4停止"
        text.draw(mentionStr1, 20, 20, 0x000000, 0xffffff)
        text.draw(mentionStr2, 20, 36, 0x000000, 0xffffff)
        text.draw(mentionStr3, 20, 52, 0x000000, 0xffffff)
        text.draw("-------------", 20, 68, 0x000000, 0xffffff)
        self.updateTotolArea()
        #设置游戏运行状态
        self.gameStart = True

    def roll(self):
        #获得随机数并更新显示
        result1 = randint(1, 6)
        text.draw(str(result1), 52, 152, 0x000000, 0xffffff)
        self.playerStatus = result1

    def pressKeyboardEvent(self, key):
        keymatch = ["Key1", "Key2", "Key3", "Key4"]
        #游戏还未开始,不必处理键盘输入
        if (self.gameStart == False):
            return
        #处理按键
        print(keymatch[key])
        self.mark = self.mark + 1
        if (keymatch[key] == "Key1"):
            self.roll()
            self.client.publish(self.TOPIC2, "1" + str(self.playerStatus))
            text.draw(str(self.playerStatus), 52, 168, 0x000000, 0xffffff)
        elif (keymatch[key] == "Key2"):
            self.roll()
            self.client.publish(self.TOPIC2, "1" + str(self.playerStatus))
            text.draw(str(self.playerStatus), 52, 168, 0x000000, 0xffffff)
        elif (keymatch[key] == "Key3"):
            self.roll()
            self.client.publish(self.TOPIC2, "1" + str(self.playerStatus))
            text.draw(str(self.playerStatus), 52, 168, 0x000000, 0xffffff)
        else:
            text.draw("游戏结束", 90, 210, 0x000000, 0xffffff)
            #设置游戏运行状态
            self.gameStart = False
            return

        #对方玩家选择

        #一号玩家收到21-26

        print("choose is :", self.choose)
        if (self.choose < 20):  #来自1号自己的信息,不判断
            print("对方尚未选择")
            return
        elif (self.choose > 20):
            print("player1 get choose is :", self.choose)
            #处理所得信息
            self.computerStatus = self.choose - 20
            #显示对方结果
            text.draw(str(self.computerStatus), 172, 152, 0x000000, 0xffffff)

        #判断胜负并显示结果
        if self.mark % 2 == 0:  #如果双方都完成选择
            resultMessage = " 平局 "
            if self.computerStatus == 0:
                return
            elif (self.playerStatus == self.computerStatus):
                self.equalNum += 1
            elif (self.playerStatus > self.computerStatus):
                self.playerScore += 1
                resultMessage = "%s胜出" % self.playerName
            elif (self.playerStatus < self.computerStatus):
                self.computerScore += 1
                resultMessage = "%s胜出" % self.computerName
            text.draw(resultMessage, 90, 210, 0x000000, 0xffffff)
            self.updateTotolArea()

    def startGame(self):

        print("-------骰子游戏开始-------")
        while True:
            self.client.check_msg()
            self.roll()
            #print(gc.mem_free())
            i = 0
            j = -1
            for k in keys:
                if (k.value() == 0):
                    if i != j:
                        j = i

                        self.pressKeyboardEvent(i)
                        self.client.check_msg()
                i = i + 1
                if (i > 3):
                    i = 0
            time.sleep_ms(100)  #按键防抖

    def updateTotolArea(self):
        #汇总区域用于显示电脑和玩家的胜平负次数
        print("-------更新汇总区域-------")
        playerTotal = "%s赢了%d局" % (self.playerName, self.playerScore)
        computerTotal = "%s赢了%d局" % (self.computerName, self.computerScore)
        equalTotal = "平局%d次" % self.equalNum
        text.draw("-------------", 20, 240, 0x000000, 0xffffff)
        text.draw(playerTotal, 20, 256, 0x000000, 0xffffff)
        text.draw(computerTotal, 20, 272, 0x000000, 0xffffff)
        text.draw(equalTotal, 20, 288, 0x000000, 0xffffff)
Example #26
0
class pics():
    def __init__(self):
        self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]]
        self.keymatch = ["Key1", "Key2", "Key3", "Key4"]
        self.select = 1
        self.displayInit()
        self.wifi_name = "NEUI"

        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        self.SERVER = "192.168.5.121"  #MQTT服务器地址
        self.SERVER_PORT = 1883  #MQTT服务器端口
        self.contentEVICE_ID = "wc001"  #设备ID
        self.TOPIC1 = b"/cloud-skids/online/dev/" + self.contentEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + self.contentEVICE_ID
        self.CLIENT_ID = "7e035cd4-15b4-4d4b-a706-abdb8151c57d"
        self.uart = UART(1,
                         baudrate=115200,
                         bits=8,
                         parity=0,
                         rx=18,
                         tx=19,
                         stop=1)
        #设备状态
        self.ON = "1"
        self.OFF = "0"

        self.content = " "  #初始化要发送的信息

        self.client = MQTTClient(self.CLIENT_ID, self.SERVER,
                                 self.SERVER_PORT)  #定义一个mqtt实例

    def drawInterface(self):  #界面初始化

        bmp1 = ubitmap.BitmapFromFile("pic/boy")

        bmp2 = ubitmap.BitmapFromFile("pic/girl")
        bmp1.draw(20, 200)  #显示boy图片
        bmp2.draw(140, 200)  #显示girl图片
        screen.drawline(0, 160, 240, 160, 2, 0xff0000)

    def do_connect(self):
        sta_if = network.WLAN(network.STA_IF)  #STA模式
        ap_if = network.WLAN(network.AP_IF)  #AP模式
        if ap_if.active():
            ap_if.active(False)  #关闭AP
        if not sta_if.isconnected():
            print('Connecting to network...')
        sta_if.active(True)  #激活STA
        sta_if.connect(self.wifi_name, self.wifi_SSID)  #WiFi的SSID和密码
        while not sta_if.isconnected():
            pass
        print('Network config:', sta_if.ifconfig())
        gc.collect()

    def selectInit(self):  #选择表情初始化
        screen.drawline(20, 200, 92, 200, 2, 0xff0000)
        screen.drawline(92, 200, 92, 272, 2, 0xff0000)
        screen.drawline(92, 272, 20, 272, 2, 0xff0000)
        screen.drawline(20, 272, 20, 200, 2, 0xff0000)

    def displayInit(self):  #初始化
        screen.clear()
        self.drawInterface()
        self.selectInit()

    def esp(self):
        self.client.set_callback(self.sub_cb)  #设置回调
        self.client.connect()
        print("连接到服务器:%s" % self.SERVER)
        self.client.publish(self.TOPIC1, self.ON)  #发布“1”到TOPIC1
        self.client.subscribe(self.TOPIC2)  #订阅TOPIC
        #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff)

    def keyboardEvent(self, key):
        if self.keymatch[key] == "Key1":  #右移键,选择要发送的表情
            if self.select % 2 == 1:  #用红色框选中boy表情
                screen.drawline(20, 200, 92, 200, 2, 0xffffff)
                screen.drawline(92, 200, 92, 272, 2, 0xffffff)
                screen.drawline(92, 272, 20, 272, 2, 0xffffff)
                screen.drawline(20, 272, 20, 200, 2, 0xffffff)
                screen.drawline(140, 200, 212, 200, 2, 0xff0000)
                screen.drawline(212, 200, 212, 272, 2, 0xff0000)
                screen.drawline(212, 272, 140, 272, 2, 0xff0000)
                screen.drawline(140, 272, 140, 200, 2, 0xff0000)
                self.select += 1
            else:  #用红色框选中girl表情
                screen.drawline(140, 200, 212, 200, 2, 0xffffff)
                screen.drawline(212, 200, 212, 272, 2, 0xffffff)
                screen.drawline(212, 272, 140, 272, 2, 0xffffff)
                screen.drawline(140, 272, 140, 200, 2, 0xffffff)
                screen.drawline(20, 200, 92, 200, 2, 0xff0000)
                screen.drawline(92, 200, 92, 272, 2, 0xff0000)
                screen.drawline(92, 272, 20, 272, 2, 0xff0000)
                screen.drawline(20, 272, 20, 200, 2, 0xff0000)
                self.select += 1
        if self.keymatch[key] == "Key3":  #发送表情按键
            if self.select % 2 == 1:  #显示已发送boy表情
                bmp1 = ubitmap.BitmapFromFile("pic/boy")

                bmp1.draw(140, 40)

                self.content = "001"

                self.client.publish(self.TOPIC2, self.content)  #给服务器发送boy表情的号码

            else:  #显示已发送girl表情

                bmp2 = ubitmap.BitmapFromFile("pic/girl")

                bmp2.draw(140, 40)

                self.content = "002"
                self.client.publish(self.TOPIC2,
                                    self.content)  #给服务器发送girl表情的号码

    def sub_cb(self, topic, message):  #从服务器接受信息
        message = message.decode()
        print("服务器发来信息:%s" % message)
        #global count
        if message == "001":  #收到boy表情号码显示boy表情
            bmp1 = ubitmap.BitmapFromFile("pic/boy")
            bmp1.draw(140, 40)
        elif message == "002":  #收到girl表情号码显示girl表情
            bmp1 = ubitmap.BitmapFromFile("pic/girl")
            bmp1.draw(140, 40)

    def start(self):
        try:
            while True:
                self.client.check_msg()  #检查是否收到信息
                i = 0  #用来辅助判断那个按键被按下
                j = -1
                for k in self.keys:  #检查按键是否被按下
                    if (k.value() == 0):  ##如果按键被按下

                        if i != j:
                            j = i
                            self.keyboardEvent(i)  #触发相应按键对应事件
                    i = i + 1
                    if (i > 3):
                        i = 0
                time.sleep_ms(130)
        finally:
            self.client.disconnect()
            print("MQTT连接断开")
Example #27
0
class GOES():
    def __init__(self):
        self.screen_width = 200
        self.screen_height = 280
        self.keys = [Pin(p, Pin.IN) for p in [35, 36, 39, 34]]
        self.keymatch = ["Key1", "Key2", "Key3", "Key4"]
        self.board = [[[20, 20, 0], [40, 20, 0], [60, 20, 0], [80, 20, 0],
                       [100, 20, 0], [120, 20, 0], [140, 20, 0], [160, 20, 0],
                       [180, 20, 0], [200, 20, 0], [220, 20, 0]],
                      [[20, 40, 0], [40, 40, 0], [60, 40, 0], [80, 40, 0],
                       [100, 40, 0], [120, 40, 0], [140, 40, 0], [160, 40, 0],
                       [180, 40, 0], [200, 40, 0], [220, 40, 0]],
                      [[20, 60, 0], [40, 60, 0], [60, 60, 0], [80, 60, 0],
                       [100, 60, 0], [120, 60, 0], [140, 60, 0], [160, 60, 0],
                       [180, 60, 0], [200, 60, 0], [220, 60, 0]],
                      [[20, 80, 0], [40, 80, 0], [60, 80, 0], [80, 80, 0],
                       [100, 80, 0], [120, 80, 0], [140, 80, 0], [160, 80, 0],
                       [180, 80, 0], [200, 80, 0], [220, 80, 0]],
                      [[20, 100, 0], [40, 100, 0], [60, 100, 0], [80, 100, 0],
                       [100, 100, 0], [120, 100, 0], [140, 100, 0],
                       [160, 100, 0], [180, 100, 0], [200, 100, 0],
                       [220, 100, 0]],
                      [[20, 120, 0], [40, 120, 0], [60, 120, 0], [80, 120, 0],
                       [100, 120, 0], [120, 120, 0], [140, 120, 0],
                       [160, 120, 0], [180, 120, 0], [200, 120, 0],
                       [220, 120, 0]],
                      [[20, 140, 0], [40, 140, 0], [60, 140, 0], [80, 140, 0],
                       [100, 140, 0], [120, 140, 0], [140, 140, 0],
                       [160, 140, 0], [180, 140, 0], [200, 140, 0],
                       [220, 140, 0]],
                      [[20, 160, 0], [40, 160, 0], [60, 160, 0], [80, 160, 0],
                       [100, 160, 0], [120, 160, 0], [140, 160, 0],
                       [160, 160, 0], [180, 160, 0], [200, 160, 0],
                       [220, 160, 0]],
                      [[20, 180, 0], [40, 180, 0], [60, 180, 0], [80, 180, 0],
                       [100, 180, 0], [120, 180, 0], [140, 180, 0],
                       [160, 180, 0], [180, 180, 0], [200, 180, 0],
                       [220, 180, 0]],
                      [[20, 200, 0], [40, 200, 0], [60, 200, 0], [80, 200, 0],
                       [100, 200, 0], [120, 200, 0], [140, 200, 0],
                       [160, 200, 0], [180, 200, 0], [200, 200, 0],
                       [220, 200, 0]],
                      [[20, 220, 0], [40, 220, 0], [60, 220, 0], [80, 220, 0],
                       [100, 220, 0], [120, 220, 0], [140, 220, 0],
                       [160, 220, 0], [180, 220, 0], [200, 220, 0],
                       [220, 220, 0]]]  #初始化棋子坐标(x坐标,y坐标,颜色)
        self.startX = 20
        self.startY = 20
        self.selectXi = 5
        self.selectYi = 5
        self.displayInit()
        self.color = 0x00ff00  #player2棋子颜色为绿色
        self.wifi_name = "NEUI"
        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        self.SERVER = "112.125.89.85"  #MQTT服务器地址
        self.SERVER_PORT = 3881  #MQTT服务器端口
        self.DEVICE_ID = "wc001"  #设备ID
        self.TOPIC1 = b"/cloud-skids/online/dev/" + self.DEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + self.DEVICE_ID
        self.CLIENT_ID = "f25410646a8348f8a1726a3890ad8f73"
        self.uart = UART(1,
                         baudrate=115200,
                         bits=8,
                         parity=0,
                         rx=18,
                         tx=19,
                         stop=1)
        #设备状态
        self.ON = "1"
        self.OFF = "0"
        self.d = " "
        self.c = MQTTClient(self.CLIENT_ID, self.SERVER, self.SERVER_PORT)

    def drawcross(self, x, y, lineColor):  # 画选择位置的框
        screen.drawline(x - 10, y - 10, x - 5, y - 10, 3, lineColor)
        screen.drawline(x - 10, y - 10, x - 10, y - 5, 3, lineColor)
        screen.drawline(x + 10, y - 10, x + 5, y - 10, 3, lineColor)
        screen.drawline(x + 10, y - 10, x + 10, y - 5, 3, lineColor)
        screen.drawline(x - 10, y + 10, x - 5, y + 10, 3, lineColor)
        screen.drawline(x - 10, y + 10, x - 10, y + 5, 3, lineColor)
        screen.drawline(x + 10, y + 10, x + 5, y + 10, 3, lineColor)
        screen.drawline(x + 10, y + 10, x + 10, y + 5, 3, lineColor)

    #画棋盘网格
    def grid(self):
        x = 20
        y = 20
        for i in range(11):
            screen.drawline(x, 20, x, 220, 3, 0x000000)
            x += 20
        for j in range(11):
            screen.drawline(20, y, 220, y, 3, 0x000000)
            y += 20

    def do_connect(self):
        sta_if = network.WLAN(network.STA_IF)  #STA模式
        ap_if = network.WLAN(network.AP_IF)  #AP模式
        if ap_if.active():
            ap_if.active(False)  #关闭AP
        if not sta_if.isconnected():
            print('Connecting to network...')
        sta_if.active(True)  #激活STA
        sta_if.connect(self.wifi_name, self.wifi_SSID)  #WiFi的SSID和密码
        while not sta_if.isconnected():
            pass
        print('Network config:', sta_if.ifconfig())
        gc.collect()

    def esp(self):
        self.c.set_callback(self.sub_cb)  #设置回调
        self.c.connect()
        print("连接到服务器:%s" % self.SERVER)
        self.c.publish(self.TOPIC1, self.ON)  #发布“1”到TOPIC1
        self.c.subscribe(self.TOPIC2)  #订阅TOPIC
        #display.text("从微信取得信息", 20, 20, 0xf000, 0xffff)

    def sub_cb(self, topic, message):  #从服务器接受信息
        message = message.decode()

        print("服务器发来信息:%s" % message)
        #global count
        t = int(message)  #根据接收到的信息解析棋子位置
        j = t // 11
        i = t % 11
        x = self.board[j][i][0]
        y = self.board[j][i][1]
        if self.board[j][i][2] == 0:
            self.put_circle_back(x, y, 10, 0x000000)  #在解析出的位置上画黑色棋子
            self.board[j][i][2] = 2  #将棋子标记为黑色
        self.is_win(i, j, self.board[j][i][2])  #判断胜负

    def put_circle_back(self, x, y, r, color):  #画圆形棋子
        a = 0  #选定原点距离圆心距离
        b = r  #在原点所画交叉线长度
        di = 3 - (r << 1)  #辅助判断画圆是否结束
        while (a <= b):  #选定原点画交叉线
            screen.drawline(x - b, y - a, x + b, y - a, 3, color)
            screen.drawline(x - a, y, x - a, y + b, 3, color)
            screen.drawline(x - b, y - a, x, y - a, 3, color)
            screen.drawline(x - a, y - b, x - a, y, 3, color)
            screen.drawline(x, y + a, x + b, y + a, 3, color)
            screen.drawline(x + a, y - b, x + a, y, 3, color)
            screen.drawline(x + a, y, x + a, y + b, 3, color)
            screen.drawline(x - b, y + a, x, y + a, 3, color)
            a += 1  #改变原点位置
            if (di < 0):  #辅助判断画圆是否结束,计算下一步所画交叉线长度
                di += 4 * a + 6
            else:
                di += 10 + 4 * (a - b)
                b -= 1
            screen.drawline(x + a, y, x + a, y + b, 3, color)

    def selectInit(self):  #选择初始化
        # 变量初始化
        self.selectXi = 5
        self.selectYi = 5
        x = self.board[self.selectYi][self.selectXi][0]
        y = self.board[self.selectYi][self.selectXi][1]
        # 选择初始化
        self.drawcross(x, y, 0xff0000)

    # 界面初始化
    def displayInit(self):  #开始游戏初始化
        screen.clear()
        self.grid()
        for self.selectYi in range(11):
            for self.selectXi in range(11):
                self.board[self.selectYi][self.selectXi][2] = 0
        self.selectInit()

    def is_win(self, i, j, k):  #判断胜负

        start_y = 0
        end_y = 10
        if j - 4 >= 0:
            start_y = j - 4
        if j + 4 <= 10:
            end_y = j + 4
        count = 0
        for pos_y in range(start_y, end_y + 1):  #判断纵向胜负
            if self.board[pos_y][i][2] == k and k == 1:
                count += 1

                if count >= 5:
                    text.draw("绿色方胜", 88, 160, 0xff0000)
            else:
                count = 0
        for pos_y in range(start_y, end_y + 1):
            if self.board[pos_y][i][2] == k and k == 2:
                count += 1

                if count >= 5:
                    text.draw("黑色方胜", 88, 160, 0xff0000)
            else:
                count = 0

        start_x = 0
        end_x = 10
        if i - 4 >= 0:
            start_x = i - 4
        if i + 4 <= 10:
            end_x = i + 4
        count = 0
        for pos_x in range(start_x, end_x + 1):  #判断横向胜负
            if self.board[j][pos_x][2] == k and k == 1:
                count += 1

                if count >= 5:
                    text.draw("绿色方胜", 88, 160, 0xff0000)
            else:
                count = 0
        for pos_x in range(start_x, end_x + 1):
            if self.board[j][pos_x][2] == k and k == 2:
                count += 1

                if count >= 5:
                    text.draw("黑色方胜", 88, 160, 0xff0000)
            else:
                count = 0

        count = 0
        s = j - i
        start = start_y
        end = end_x + s
        if j > i:
            start = start_x + s
            end = end_y
        for index in range(start, end + 1):  #判断斜方向胜负(左上右下)
            if self.board[index][index - s][2] == k and k == 1:
                count += 1

                if count >= 5:
                    text.draw("绿色方胜", 88, 160, 0xff0000)
            else:
                count = 0
        for index in range(start, end + 1):
            if self.board[index][index - s][2] == k and k == 2:
                count += 1

                if count >= 5:
                    text.draw("黑色方胜", 88, 160, 0xff0000)
            else:
                count = 0

        count = 0
        s = j + i

        if j + i <= 10:
            start = start_y
            end = s - start_x
        if j + i > 10:
            start = s - 10
            end = 10
        if s >= 4 and s <= 16:

            for index in range(start, end + 1):  #判断斜方向胜负(左下右上)
                if self.board[index][s - index][2] == k and k == 1:
                    count += 1

                    if count >= 5:
                        text.draw("绿色方胜", 88, 160, 0xff0000)
                else:
                    count = 0
            for index in range(start, end + 1):
                if self.board[index][s - index][2] == k and k == 2:
                    count += 1

                    if count >= 5:
                        text.draw("黑色方胜", 88, 160, 0xff0000)
                else:
                    count = 0

    def keyboardEvent(self, key):
        # 右移选择键
        if self.keymatch[key] == "Key1":
            # 取消前一个选择
            x = self.board[self.selectYi][self.selectXi][0]
            y = self.board[self.selectYi][self.selectXi][1]
            self.drawcross(x, y, 0xffffff)
            # 选择右边一个
            self.selectXi = (self.selectXi + 1) % 11
            x = self.board[self.selectYi][self.selectXi][0]
            y = self.board[self.selectYi][self.selectXi][1]
            self.drawcross(x, y, 0xff0000)
        # 纵向移动键
        elif self.keymatch[key] == "Key2":
            # 取消前一个选择
            x = self.board[self.selectYi][self.selectXi][0]
            y = self.board[self.selectYi][self.selectXi][1]
            self.drawcross(x, y, 0xffffff)
            # 选择下边一个
            self.selectYi = (self.selectYi + 1) % 11
            x = self.board[self.selectYi][self.selectXi][0]
            y = self.board[self.selectYi][self.selectXi][1]
            self.drawcross(x, y, 0xff0000)

# 确认键
        elif self.keymatch[key] == "Key3":
            x = self.board[self.selectYi][self.selectXi][0]
            y = self.board[self.selectYi][self.selectXi][1]
            if self.board[self.selectYi][self.selectXi][2] == 0:
                self.put_circle_back(x, y, 10, self.color)  #画绿色棋子
                self.board[self.selectYi][self.selectXi][2] = 1  #将棋子标记为绿色
                s = (self.selectYi) * 11 + (self.selectXi)
                self.d = str(s)
                self.c.publish(self.TOPIC2, self.d)  #向服务器发送棋子位置信息
            self.is_win(self.selectXi, self.selectYi,
                        self.board[self.selectYi][self.selectXi][2])
        elif self.keymatch[key] == "Key4":
            self.displayInit()

    def start(self):
        try:
            while True:
                self.c.check_msg()  #检查是否收到信息
                i = 0  #用来辅助判断那个按键被按下
                j = -1
                for k in self.keys:
                    if (k.value() == 0):  #如果按键被按下
                        if i != j:
                            j = i
                            self.keyboardEvent(i)  #触发相应按键对应事件
                    i = i + 1
                    if (i > 3):
                        i = 0
                time.sleep_ms(200)  # 按键去抖
        finally:
            self.c.disconnect()
            print("MQTT连接断开")
Example #28
0
class Game():
    def __init__(self, playerName, computerName):  #初始化
        #网络设定
        #WiFi名称和密码
        self.wifi_name = "NEUI"
        self.wifi_SSID = "NEUI3187"
        #MQTT服务端信息
        SERVER = "112.125.89.85"  #MQTT服务器地址
        SERVER_PORT = 3881  #MQTT服务器端口
        DEVICE_ID = "wc001"  #设备ID
        TOPIC1 = b"/cloud-skids/online/dev/" + DEVICE_ID
        self.TOPIC2 = b"/cloud-skids/message/server/" + DEVICE_ID
        CLIENT_ID = "f25410646a8348f8a1726a3890ad8f82"
        #设备状态
        ON = "1"
        OFF = "0"
        #对方的选择
        self.d = ["1", "2", "3"]
        self.choose = 0
        self.mark = 0
        #启动网络连接
        self.do_connect()
        gc.collect()
        self.client = MQTTClient(CLIENT_ID, SERVER, SERVER_PORT)
        self.client.set_callback(self.sub_cb)  #设置回调
        self.client.connect()
        print("连接到服务器:%s" % SERVER)
        self.client.publish(TOPIC1, ON)  #发布“1”到TOPIC1
        self.client.subscribe(self.TOPIC2)  #订阅TOPIC
        #游戏设定
        self.gameStart = False
        self.playerName = playerName
        self.computerName = computerName
        self.playerScore = 0
        self.computerScore = 0
        self.equalNum = 0
        self.playerStatus = 0
        self.playerMessage = ""
        self.computerStatus = 0
        self.computerMessage = ""
        for p in pins:
            keys.append(Pin(p, Pin.IN))
        self.displayInit()

    def do_connect(self):
        sta_if = network.WLAN(network.STA_IF)  #STA模式
        ap_if = network.WLAN(network.AP_IF)  #AP模式
        if ap_if.active():
            ap_if.active(False)  #关闭AP
        if not sta_if.isconnected():
            print('Connecting to network...')
        sta_if.active(True)  #激活STA
        sta_if.connect(self.wifi_name, self.wifi_SSID)  #WiFi的SSID和密码
        while not sta_if.isconnected():
            pass
        print('Network config:', sta_if.ifconfig())

    def sub_cb(self, topic, message):
        message = message.decode()

        print("choose is :", self.choose)
        self.choose = int(message)
        print("mark is :", self.mark)
        if self.choose > 20:  #来自2号自己的信息,不判断
            print("对方尚未选择出拳")
            return
        else:
            self.mark = self.mark + 1
            print("player1 choose is :", self.choose)
            self.computerStatus = self.choose - 10
            if (self.computerStatus == 1):
                self.computerMessage = "%s出拳为:剪刀" % self.computerName
                bmp_jiandao.draw(150, 140)
            if (self.computerStatus == 2):
                self.computerMessage = "%s出拳为:石头" % self.computerName
                bmp_shitou.draw(150, 140)
            if (self.computerStatus == 3):
                self.computerMessage = "%s出拳为:布 " % self.computerName
                bmp_bu.draw(150, 140)

        #显示电脑和玩家的出拳信息
        text.draw(self.playerMessage, 20, 84, 0x000000, 0xffffff)
        text.draw(self.computerMessage, 20, 100, 0x000000, 0xffffff)

        #判断胜负并显示结果
        if self.mark % 2 == 0:  #如果双方都完成选择
            resultMessage = " 平局 "
            if self.computerStatus == 0:
                return
            elif (self.playerStatus == self.computerStatus):
                self.equalNum += 1
            elif (self.playerStatus == 1 and self.computerStatus == 3):
                resultMessage = "%s胜出" % self.playerName
                self.playerScore += 1
            elif (self.playerStatus == 2 and self.computerStatus == 1):
                resultMessage = "%s胜出" % self.playerName
                self.playerScore += 1
            elif (self.playerStatus == 3 and self.computerStatus == 2):
                resultMessage = "%s胜出" % self.playerName
                self.playerScore += 1
            elif (self.computerStatus == 1 and self.playerStatus == 3):
                resultMessage = "%s胜出" % self.computerName
                self.computerScore += 1
            elif (self.computerStatus == 2 and self.playerStatus == 1):
                resultMessage = "%s胜出" % self.computerName
                self.computerScore += 1
            elif (self.computerStatus == 3 and self.playerStatus == 2):
                resultMessage = "%s胜出" % self.computerName
                self.computerScore += 1

            text.draw(resultMessage, 90, 210, 0x000000, 0xffffff)
            self.updateTotolArea()

    def displayInit(self, x=10, y=10, w=222, h=303):
        #显示游戏规则信息
        mentionStr1 = "游戏规则:"
        mentionStr2 = "按键1.剪刀 按键2.石头"
        mentionStr3 = "按键3.布  按键4.结束"
        text.draw(mentionStr1, 20, 20, 0x000000, 0xffffff)
        text.draw(mentionStr2, 20, 36, 0x000000, 0xffffff)
        text.draw(mentionStr3, 20, 52, 0x000000, 0xffffff)
        text.draw("-------------", 20, 68, 0x000000, 0xffffff)
        self.updateTotolArea()
        #设置游戏运行状态
        self.gameStart = True

    def pressKeyboardEvent(self, key):
        keymatch = ["Key1", "Key2", "Key3", "Key4"]
        #游戏还未开始,不必处理键盘输入
        if (self.gameStart == False):
            return
        print(keymatch[key])
        self.mark = self.mark + 1
        if (keymatch[key] == "Key1"):
            self.playerStatus = 1
            self.playerMessage = "%s出拳为:剪刀" % self.playerName
            self.client.publish(self.TOPIC2,
                                "2" + self.d[self.playerStatus - 1])
            bmp_jiandao.draw(40, 140)
        elif (keymatch[key] == "Key2"):
            self.playerStatus = 2
            self.playerMessage = "%s出拳为:石头" % self.playerName
            self.client.publish(self.TOPIC2,
                                "2" + self.d[self.playerStatus - 1])
            bmp_shitou.draw(40, 140)
        elif (keymatch[key] == "Key3"):
            self.playerStatus = 3
            self.playerMessage = "%s出拳为:布 " % self.playerName
            self.client.publish(self.TOPIC2,
                                "2" + self.d[self.playerStatus - 1])
            bmp_bu.draw(40, 140)
        else:
            text.draw("游戏结束", 90, 210, 0x000000, 0xffffff)
            #设置游戏运行状态
            self.gameStart = False
            return

        #电脑的出拳为一个随机值

        #二号玩家收到11-13

        print("choose is :", self.choose)
        if (self.choose > 20 or self.mark % 2 == 1):
            print("对方尚未选择出拳")
            return
        else:
            self.computerStatus = self.choose - 10
            if (self.computerStatus == 1):
                self.computerMessage = "%s出拳为:剪刀" % self.computerName
                bmp_jiandao.draw(150, 140)
            if (self.computerStatus == 2):
                self.computerMessage = "%s出拳为:石头" % self.computerName
                bmp_shitou.draw(150, 140)
            if (self.computerStatus == 3):
                self.computerMessage = "%s出拳为:布 " % self.computerName
                bmp_bu.draw(150, 140)

        #显示电脑和玩家的出拳信息
        text.draw(self.playerMessage, 20, 84, 0x000000, 0xffffff)
        text.draw(self.computerMessage, 20, 100, 0x000000, 0xffffff)

        #判断胜负并显示结果
        resultMessage = " 平局 "
        if self.computerStatus == 0:
            return
        elif (self.playerStatus == self.computerStatus):
            self.equalNum += 1
        elif (self.playerStatus == 1 and self.computerStatus == 3):
            resultMessage = "%s胜出" % self.playerName
            self.playerScore += 1
        elif (self.playerStatus == 2 and self.computerStatus == 1):
            resultMessage = "%s胜出" % self.playerName
            self.playerScore += 1
        elif (self.playerStatus == 3 and self.computerStatus == 2):
            resultMessage = "%s胜出" % self.playerName
            self.playerScore += 1
        elif (self.computerStatus == 1 and self.playerStatus == 3):
            resultMessage = "%s胜出" % self.computerName
            self.computerScore += 1
        elif (self.computerStatus == 2 and self.playerStatus == 1):
            resultMessage = "%s胜出" % self.computerName
            self.computerScore += 1
        elif (self.computerStatus == 3 and self.playerStatus == 2):
            resultMessage = "%s胜出" % self.computerName
            self.computerScore += 1

        text.draw(resultMessage, 90, 210, 0x000000, 0xffffff)
        self.updateTotolArea()

    def startGame(self):

        print("-------猜拳游戏开始-------")
        while True:
            self.client.check_msg()
            i = 0
            j = -1
            for k in keys:
                if (k.value() == 0):
                    if i != j:
                        j = i
                        self.client.check_msg()
                        self.pressKeyboardEvent(i)
                        self.client.check_msg()
                i = i + 1
                if (i > 3):
                    i = 0
            time.sleep_ms(100)  #按键防抖

    def updateTotolArea(self):
        #汇总区域用于显示电脑和玩家的胜平负次数
        print("-------更新汇总区域-------")
        playerTotal = "%s赢了%d局" % (self.playerName, self.playerScore)
        computerTotal = "%s赢了%d局" % (self.computerName, self.computerScore)
        equalTotal = "平局%d次" % self.equalNum
        text.draw("-------------", 20, 240, 0x000000, 0xffffff)
        text.draw(playerTotal, 20, 256, 0x000000, 0xffffff)
        text.draw(computerTotal, 20, 272, 0x000000, 0xffffff)
        text.draw(equalTotal, 20, 288, 0x000000, 0xffffff)
Example #29
0

def message_received(topic, msg):
    msg = msg.decode("utf-8")
    print("Message received: " + msg)
    morse.enqueue_message(msg)


print("Connecting to " + private.aio_server)
client = MQTTClient(client_id=private.client_id,
                    server=private.aio_server,
                    user=private.aio_user,
                    password=private.aio_key,
                    keepalive=30,
                    ssl=False)
client.set_callback(message_received)
client.connect()
client.subscribe(private.aio_feed)

morse = Morse()
morse.enqueue_message("ok", 'G')

timer = time.ticks_ms()
print("Running...")
while True:
    client.check_msg()
    if time.ticks_diff(time.ticks_ms(), timer) > 30000:
        client.ping()
        timer = time.ticks_ms()
    machine.idle()
    time.sleep_ms(100)
from umqtt import MQTTClient
import machine, ubinascii
import time, gc
import network
import json, errno
from dht import DHT22
from machine import Pin, I2C, Timer, ADC
from ssd1306 import SSD1306_I2C
import _thread as th
a1 = ADC(Pin(32))
a2 = ADC(Pin(33))
a3 = ADC(Pin(34))
scl = Pin(22)
sda = Pin(21)
i2c = I2C(scl=scl, sda=sda, freq=100000) 
oled = SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text('ESP32', 45, 5)
oled.text('MicroPython', 20, 20)
oled.text('System Startimg', 3, 35) 
oled.show()
dhtPn = Pin(17)
d = DHT22(dhtPn)
tim0 = Timer(0)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('see_dum', '0863219053')
while not wlan.isconnected():
    print('Wait connection')
    time.sleep(1)
Example #31
0
class BluestoneMqtt(object):
    inst = None

    def __init__(self, client_id, server, port, user, password, sub_topic,
                 pub_topic):
        BluestoneMqtt.inst = self

        self.bs_config = None
        self.bs_gpio = None
        self.bs_pwm = None
        self.bs_fota = None
        self.bs_uart = None

        self.sn = bluestone_common.BluestoneCommon.get_sn()
        self.client_id = client_id
        self.server = server
        self.port = port
        self.user = user
        self.password = password

        self.subscribe_topic = sub_topic
        self.publish_topic = pub_topic

        self.client = None
        self._is_sub_callback_running = False
        self._is_message_published = False

    def _init_mqtt(self):
        self.bs_config = bluestone_config.BluestoneConfig(
            'bluestone_config.json')
        self.bs_data_config = bluestone_config.BluestoneConfig(
            'bluestone_data.json')
        self.bs_gpio = bluestone_gpio.BluestoneGPIO()
        self.bs_pwm = bluestone_pwm.BluestonePWM()
        self.bs_fota = bluestone_fota.BluestoneFOTA()
        self.bs_uart = bluestone_uart.BlueStoneUart(None)

        # 创建一个MQTT实例
        self.client = MQTTClient(client_id=self.client_id,
                                 server=self.server,
                                 port=self.port,
                                 user=self.user,
                                 password=self.password,
                                 keepalive=30)
        _mqtt_log.info(
            "Start a new mqtt client, id:{}, server:{}, port:{}".format(
                self.client_id, self.server, self.port))

        self.client.set_callback(self._sub_callback)  # 设置消息回调
        self.client.connect()  # 建立连接

        #sub_topic = self.subscribe_topic.format(self.sn)
        _mqtt_log.info("Subscribe topic is {}".format(self.subscribe_topic))
        self.client.subscribe(self.subscribe_topic)  # 订阅主题

    def _update_gpio_status(self, io_level_list):
        try:
            self.bs_data_config.update_config('gpio', io_level_list)

            message = {}
            message['gpio'] = io_level_list
            _mqtt_log.info("Data configuration is {}".format(message))
            self.publish(message)
        except Exception as err:
            _mqtt_log.error(
                "Cannot update gpio level list, the error is {}".format(err))

    def _handle_callback(self, key, config):
        result = False
        try:
            if key.startswith('uart'):
                # first payload then config
                payload = self.bs_config.get_value(config, "payload")
                if payload:
                    self.bs_uart.uart_write(key, ujson.dumps(payload))
                uart_config = self.bs_config.get_value(config, "config")
                if uart_config:
                    self.bs_config.update_config(key, uart_config)
                    self.bs_data_config.update_config(key, uart_config)
                    result = True
            elif key.startswith('pwm'):
                id = self.bs_pwm.get_id_by_name(key)
                is_breathe = self.bs_config.get_int_value(config, "breathe")
                frequency = self.bs_config.get_int_value(config, "frequency")
                duty = self.bs_config.get_float_value(config, "duty")
                if is_breathe:
                    self.bs_pwm.start_breathe(id, frequency)
                else:
                    self.bs_pwm.start_once(id, frequency, duty)
            elif key.startswith('timer'):
                self.bs_config.update_config(key, config)
                self.bs_data_config.update_config(key, config)
                result = True
            elif key == 'gpio':
                io_level_list = self.bs_gpio.read_all()
                io_name_list = self.bs_gpio.get_io_name_list()
                for gpio_key in config.keys():
                    if gpio_key not in io_name_list:
                        continue
                    level = self.bs_config.get_int_value(config, gpio_key)
                    if level is not None:
                        id = self.bs_gpio.get_id_by_name(gpio_key)
                        self.bs_gpio.write(id, level)
                        io_level_list[gpio_key] = level
                self._update_gpio_status(io_level_list)
            elif key == 'fota':
                mode = self.bs_config.get_int_value(config, "mode")
                if mode == 0:
                    url_list = self.bs_config.get_value(config, "url")
                    self.bs_fota.start_fota_app(url_list)
                elif mode == 1:
                    url = self.bs_config.get_value(config, "url")
                    self.bs_fota.start_fota_firmware(url)
                result = True
        except Exception as err:
            _mqtt_log.error(
                "Cannot handle callback for mqtt, the error is {}".format(err))

        return result

    def _sub_callback_internal(self, topic, msg):
        try:
            message = msg.decode()
            _mqtt_log.info("Subscribe received, topic={}, message={}".format(
                topic.decode(), message))
            restart = False

            config_setting = ujson.loads(message)
            config_keys = config_setting.keys()
            for key in config_setting:
                config = config_setting[key]
                key_exist = self.bs_config.check_key_exist(key)
                if key_exist:
                    if not restart:
                        restart = self.bs_config.mqtt_check_key_restart(key)
                    result = self._handle_callback(key, config)
                    if result:
                        restart = True
            if restart:
                restart = False
                _mqtt_log.info(
                    "New configuration was received from mqtt, restarting system to take effect"
                )
                Power.powerRestart()
        except Exception as err:
            _mqtt_log.error(
                "Cannot handle subscribe callback for mqtt, the error is {}".
                format(err))
        finally:
            self._is_sub_callback_running = False

    # 云端消息响应回调函数
    def _sub_callback(self, topic, msg):
        if self._is_sub_callback_running:
            _mqtt_log.error(
                "Subscribe callback function is running, skipping the new request"
            )
            return

        self._is_sub_callback_running = True
        _thread.start_new_thread(self._sub_callback_internal, (topic, msg))

    def _mqtt_publish(self, message):
        #pub_topic = self.publish_topic.format(self.sn)
        #message = {"Config":{},"message":"MQTT hello from Bluestone"}

        if self.client is not None:
            self.client.publish(self.publish_topic, message)
            self._is_message_published = True
            _mqtt_log.info("Publish topic is {}, message is {}".format(
                self.publish_topic, message))

    def _wait_msg(self):
        while True:
            if self.client is not None:
                self.client.wait_msg()
            utime.sleep_ms(300)

    def is_message_published(self):
        return self._is_message_published

    def start(self):
        self._init_mqtt()

        _thread.start_new_thread(self._wait_msg, ())

    def publish(self, message):
        network_state = bluestone_common.BluestoneCommon.get_network_state()
        if network_state != 1:
            _mqtt_log.error(
                "Cannot publish mqtt message, the network state is {}".format(
                    network_state))
            return

        #_mqtt_log.info("Publish message is {}".format(message))
        #self._mqtt_publish(ujson.dumps(message))
        self._is_message_published = False
        _thread.start_new_thread(self._mqtt_publish, ([ujson.dumps(message)]))

    def connect(self):
        if self.client is not None:
            self.client.connect()
            _mqtt_log.info("MQTT connected")

    def disconnect(self):
        if self.client is not None:
            self.client.disconnect()
            _mqtt_log.info("MQTT disconnected")

    def close(self):
        self.disconnect()
        self.client = None
        _mqtt_log.info("MQTT closed")