Exemple #1
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)
Exemple #2
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 ...")
Exemple #3
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()
Exemple #4
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()
Exemple #5
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连接断开")
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)
Exemple #7
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连接断开")
Exemple #8
0
    finally:
        last_random_sent_ticks = time.ticks_ms()


# Use the MQTT protocol to connect to Adafruit IO
client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY)

# 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))

pycom.rgbled(0x00ff00)  # Status green: online to Adafruit IO

try:  # Code between try: and finally: may cause an error
    # so ensure the client disconnects the server if
    # that happens.
    while 1:  # Repeat this loop forever
        client.check_msg(
        )  # Action a message if one is received. Non-blocking.
        send_random()  # Send a random number to Adafruit IO if it's time.
finally:  # If an exception is thrown ...
    client.disconnect()  # ... disconnect the client and clean up.
    client = None
    wlan.disconnect()
    wlan = None
    pycom.rgbled(0x000022)  # Status blue: stopped
    print("Disconnected from Adafruit IO.")
Exemple #9
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)
Exemple #10
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)
Exemple #11
0
    #create count.txt
    with open('count.txt', 'x') as f:
        f.close()
    #write count as 0
    with open('count.txt', 'w') as f:
        f.write('0')
        count = 0

while True:
    if not subscribed:
        try:
            mqtt.subscribe('test/message')
            subscribed = True
        except:
            subscribed = False
    mqtt.check_msg()
    if not wlan.isconnected():
        boot.wlanConnect()
    #if not connected to broker try again, if cant wait 2 seconds
    if not isConnected:
        isConnected = tryConnect()
    if button() == 0 & isConnected:
        reset()
    #if input from radar and is connected to broker
    if P2() == 1 & isConnected & subscribed:
        count += 1
        #publish count
        mqtt.publish('test/message', str(count))
        f = open('count.txt', 'w')
        f.write(str(count))
        f.close()
# CONNECT TO WIFI
# We need to have a connection to WiFi for Internet access
# Code source: https://docs.pycom.io/chapter/tutorials/all/wlan.html

print("Connecting to WiFi ... ", end='')
wlan = WLAN(mode=WLAN.STA)
wlan.connect(WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS), timeout=5000)

while not wlan.isconnected():  # Code waits here until WiFi connects
    machine.idle()

print("done.")

# CONNECT TO ADAFRUIT IO
# Use the MQTT protocol to connect to Adafruit IO
adafruit_io = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER,
                         AIO_KEY)
adafruit_io.set_callback(sub_cb)
adafruit_io.connect()
adafruit_io.subscribe(AIO_CONTROL_FEED)
adafruit_io.subscribe(AIO_COLOUR_FEED)

while (True):
    light_level = 4095 - apin()

    send_to_aio(AIO_LIGHT_FEED, light_level)
    for x in range(0, 49):
        adafruit_io.check_msg()
        time.sleep(0.1)
Exemple #13
0
class MQTT:
    def __init__(self, led_control, device_name):
        """
        Constructor
        """

        self.led_control    = led_control
        self.topic          = mqtt_config['topic']
        self.resp_topic     = mqtt_config['resp_topic']
        self.device_name    = device_name

    def start(self):
        """
        Initialize MQTT Connection
        """
        print ("Creating client")
        self.client = MQTTClient(
                                client_id   = self.device_name,
                                server      = mqtt_config['address'],
                                user        = mqtt_config['username'],
                                password    = mqtt_config['user_key'],
                                port        = mqtt_config['port'])
        print ("Setting timeout")
        self.client.settimeout = self.set_timeout
        print ("Setting callback")
        self.client.set_callback(self.sub_cb)
        print ("Connecting mqtt", mqtt_config['address'], mqtt_config['username'], mqtt_config['user_key'], mqtt_config['port'])
        res = self.client.connect()
        if (res == -1):
            print ("Failed to connect")
            pycom.rgbled(0xB900B9)
            return
        print ("Subscribing")
        self.client.subscribe(topic=self.topic)

        self.client.set_last_will(self.resp_topic, "Bye")

        print ("Listening")
        pycom.rgbled(0x00ff00)

        Timer.Alarm(self.check_new_messages, 0.0075, periodic=True)

        gc.collect()

    def stop(self):
        """
        Disconnect and stop listening
        """
        self.client.disconnect()

    def send_data(self, data):
        self.client.publish(topic=self.resp_topic, msg=data)

    def sub_cb(self, topic, message):
        """
        """
        if message is None: return
        else: self.parse_input_data(message)

    def set_timeout(duration):
        """
        """
        pass

    def parse_input_data(self, data):
        """
        Chooses correct response for new characteristic value
        """
        decoded = data.decode('utf-8')
        #Echo data back to MQTT backend

        if "status" in decoded:
            resp_data = self.led_control.compose_status_response()
            self.send_data("resp:" + resp_data)
            return

        # print (decoded)

        self.send_data("resp:" + decoded)

        if ";" in decoded:
            self.led_control.set_route(decoded)
            return
        if ("," not in decoded): return
        data = decoded.split(",")
        #print (data)
        size = len(data)
        if (size == 0):
            print ("bad input")
            return

        if (size == 1):
            self.led_control.turn_off_leds()
        elif (size == 2):
            self.led_control.set_new_data((data[0], data[1], data[1], data[1]))
        elif (size == 4):
            self.led_control.set_new_data((data[0], data[1], data[2], data[3]))

    def check_new_messages(self, alarm):
        self.client.check_msg()
Exemple #14
0
class adafruit:
    def __init__(self, config, data_collector, logger):
        self.sensor = data_collector
        self.Config = config
        self.Logger = logger
        self.AIO_SERVER = config["adafruit"]["AIO_SERVER"]
        self.AIO_PORT = config["adafruit"]["AIO_PORT"]
        self.AIO_USER = config["adafruit"]["AIO_USER"]
        self.AIO_KEY = config["adafruit"]["AIO_KEY"]
        self.AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id())
        self.AIO_CONTROL_FEED = config["adafruit"]["AIO_CONTROL_FEED"]
        self.AIO_MOVEMENT_FEED = config["adafruit"]["AIO_MOVEMENT_FEED"]
        self.AIO_GPS_FEED = config["adafruit"]["AIO_GPS_FEED"]
        self.AIO_ACCELERATION_FEED = config["adafruit"][
            "AIO_ACCELERATION_FEED"]
        self.last_random_sent_ticks = config["adafruit"][
            "last_random_sent_ticks"]
        self.post_per_minute = config["adafruit"]["post_per_minute"]
        """Finding and connecting to network"""
        self.wlan = WLAN(mode=WLAN.STA)
        nets = self.wlan.scan()
        print("Scanning for Wifi")
        for net in nets:
            for knowNet in self.Config["network"]:
                if net.ssid == knowNet["name"]:
                    print(net.ssid + ' found!')
                    self.wlan.connect(net.ssid,
                                      auth=(net.sec, knowNet["password"]),
                                      timeout=5000)
                    while not self.wlan.isconnected():
                        machine.idle()  # save power while waiting
                    print('WLAN connection succeeded!')
                    break

        self.client = MQTTClient(self.AIO_CLIENT_ID, self.AIO_SERVER,
                                 self.AIO_PORT, self.AIO_USER, self.AIO_KEY)

    def runAdafruit(self):
        Time = utime.localtime(None)
        currentTime = str(Time[1]) + "/" + str(Time[2]) + "/" + str(
            Time[0]) + " at " + str(Time[3]) + ":" + str(Time[4]) + ":" + str(
                Time[5])
        self.Logger.log("Session began at " + currentTime)
        #Subscribed messages will be delivered to this callback
        self.client.set_callback(self.sub_cb)
        print('Connecting to io.adafruit.com')
        time.sleep(10)
        self.client.connect()
        self.client.subscribe(self.AIO_CONTROL_FEED)
        print("Connected to %s, subscribed to %s topic" %
              (self.AIO_SERVER, self.AIO_CONTROL_FEED))

        pycom.rgbled(0x0000FF)  # Blue

        try:
            while 1:
                self.client.check_msg()
                self.sendMovement()
        finally:
            self.client.disconnect()
            self.client = None
            self.wlan.disconnect()
            self.wlan = None
            pycom.rgbled(0x000022)
            print("Disconnected from Adafruit IO.")

    #responds to messages from Adafruit IO
    def sub_cb(self, topic, msg):
        print((topic, msg))
        if msg == b"ON":
            pycom.rgbled(0xffffff)
        elif msg == b"OFF":
            pycom.rgbled(0x000000)
        else:
            print("Unknown message")

    #Sends messages to Adafuit IO
    def sendMovement(self):
        #Waits 2 seconds to send data to avoid Adadruit IO
        if ((time.ticks_ms() - self.last_random_sent_ticks) <
            (1000 / (self.post_per_minute) / 60)):
            return

        angle = self.sensor.getAngle()
        acceleration = self.sensor.getAcceleration()
        gps = self.sensor.getGPS()
        if (str(gps[0]) == "None"):
            gps = "0,40.808679,-77.855693,0"
        else:
            gps = "0," + str(gps[0]) + "," + str(gps[1]) + ",0"

        print("Publishing: {0} to {1}, {2} to {3}, {4} to {5} ... ".format(
            angle, self.AIO_MOVEMENT_FEED, acceleration,
            self.AIO_ACCELERATION_FEED, gps, self.AIO_GPS_FEED),
              end='')
        try:
            self.client.publish(topic=self.AIO_MOVEMENT_FEED, msg=str(angle))
            self.client.publish(topic=self.AIO_ACCELERATION_FEED,
                                msg=str(acceleration))
            self.client.publish(topic=self.AIO_GPS_FEED, msg=str(gps))
            print("DONE")
        except Exception as e:
            print(e)
            print("FAILED")
        finally:
            self.last_random_sent_ticks = time.ticks_ms()