Example #1
0
 def setValue(self, value, callback=None):
     from Msg import Msg
     Log.i(
         'Device', "Set value for device" + self.unid + "|" + self.setid +
         " :" + value + ", isOnline:%s" % self.isOnline)
     if self.mySocketWrap != None and self.isOnline == True:
         Log.i('Device', "Sending expl now")
         self.setValueCallback = callback
         Log.d('DeviceSetVal', "[1.1]")
         msg = self.mySocketWrap.sendValue(self, value,
                                           self.callbackSetValue)
         Log.d('DeviceSetVal', "[1.2]")
         self.needSetValue = False
     elif (self.mySocketWrap == None and self.isOnline == True):
         DB.addAlert(self.unid, self.setid, 1008)
         if (callback != None):
             msg = Msg(cmd="device.val.set.error")
             msg.sendAttempt = -1
             callback(msg, self)
     else:
         Log.i('Device', "Scheduled for when online")
         msg = Msg(cmd="device.val.set.scheduled")
         self.executeTriggerSeq(1)
         if (callback != None):
             callback(msg, self)
         self.needSetValue = True
         self.updateValueDb(value)
         if (self.isOnline == False):
             self.sendHeartBeat()
         #else:
         #	self.setIsOnline(False)
     self.lastValue = value
Example #2
0
def wechat():
    if request.method == 'GET':
        token = 'wechat'
        query = request.args
        signature = query.get('signature', '')
        timestamp = query.get('timestamp', '')
        nonce = query.get('nonce', '')
        echostr = query.get('echostr', '')
        s = [timestamp, nonce, token]
        s.sort()
        s = ''.join(s).encode('utf-8')
        if (hashlib.sha1(s).hexdigest() == signature):
            access_token = get_access_token()
            delete_menus(access_token)
            return make_response(echostr)
        else:
            print(' 该请求不是来自于微信...')
    # else:
    #     xml_recv = ET.fromstring(request.data)
    #     ToUserName = xml_recv.find("ToUserName").text
    #     FromUserName = xml_recv.find("FromUserName").text
    #     Content = xml_recv.find("Content").text
    #     reply = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content><FuncFlag>0</FuncFlag></xml>"
    #     response = make_response(reply % (FromUserName, ToUserName,
    #                                       str(int(time.time())), Content))
    #     response.content_type = 'application/xml'
    #     return response

    if request.method == 'POST':
        soup = BeautifulSoup(request.data, 'xml')
        toUserName = soup.find('ToUserName').text
        fromUserName = soup.find('FromUserName').text
        msgType = soup.find('MsgType').text
        msg = Msg(toUserName, fromUserName, msgType)

        if msgType == 'event':
            content = soup.find('Event').text
            if content == 'subscribe':
                text = '欢迎关注公众号...'
                response = make_response(msg.reply_text(text))
                return response
            elif content == 'CLICK':
                key_value = soup.find('EventKey').get_text()
                response = make_response(msg.reply_text(key_value))
                return response

        if msgType == 'text':

            content = soup.find('Content').get_text()
            key = '64fe923bce7b4eb8b0d169386fa745fe'
            api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='
            url = api + content
            content = json.loads(requests.get(url).text)['text']
            response = make_response(msg.reply_text(content))

            return response
Example #3
0
def HUB_sendACK():
    global modemUnid
    global modemSetid
    global isACKwaiting
    global DriverTCP
    if (isACKwaiting and modemSetid != ""):
        DriverTCP.sendMsg(Msg(unid=modemUnid, setid=modemSetid, cmd="ACK"))
        isACKwaiting = False
Example #4
0
def onRecieve(msg):
    global DriverTCP
    if (msg.cmd == "device.heartbeat" and Config.get('id') != ""):
        DriverTCP.sendMsgWithCheck(
            Msg(unSetId=Config.get('id'), cmd="device.reg.renew"))
    elif (msg.cmd == "device.reg.res"):
        Log.i("Receive/RegFin", "Got SetID", msg.value)
        Config.set('id', "00C8," + msg.value.replace(",", ""))
Example #5
0
 def run(self):
     logging.info("random str thread running...")
     while self.running:
         ranStr = str(int(time.time())) + ":" + "".join(
             random.sample(string.ascii_letters + string.digits, 8))
         msg = Msg(msgType=MsgType.RandomStr, load=ranStr)
         logging.info("random str thread put: " + ranStr)
         self.queue.put(msg)
         time.sleep(60)
Example #6
0
 def sendValue(self, device, value, callback=None):
     msg = Msg(unid=device.unid,
               setid=device.setid,
               cmd="device.val.set",
               value=value,
               socket=self,
               callback=callback)
     Log.d('DeviceSetVal', "[1.1.1]")
     self.outgoingMSG.append(msg)
     return msg
Example #7
0
def HUB_send(text):
    global modemUnid
    global modemSetid
    global DriverTCP
    if (modemSetid != ""):
        DriverTCP.sendMsgWithCheck(
            Msg(unid=modemUnid,
                setid=modemSetid,
                value=text,
                cmd="device.val.input"))
Example #8
0
    def open(self):
        self._client = ""
        self._tmp_files = {}
        self._downloaded = []
        global _clients

        while True:
            print _clients
            tmp_id = str(random.randint(0,999999)).zfill(10)
            print tmp_id
            if id not in _clients: 
                self._client = Client(tmp_id)
                _clients[tmp_id] = self
                break
        
        print _clients
        
        self._client._files = {}
        tmp_msg = Msg(None, self._client.client_id)
        tmp_msg.set_type(MsgCon.TYPE_CONN_DETAILS)
        tmp_msg.set_body(self._client.get_details())
        self.write_message(str(tmp_msg))
Example #9
0
    def run(self):
        self.init()
        self.eventFilter = self.getFilter()
        userInfo = self.getUserInfo()
        msg = Msg(msgType=MsgType.ETH_UPDATE, load=userInfo)
        logging.info("web3 thread put msg: " + json.dumps(msg.load, indent=2))
        self.queue.put(msg)
        logging.info("web3 thread is running...")
        while self.running:
            try:
                for event in self.eventFilter.get_new_entries():
                    self.handle_event(event)
            except Exception as e:
                logging.info(e)
                self.init()
                self.eventFilter = self.getFilter()
                userInfo = self.getUserInfo()
                msg = Msg(msgType=MsgType.ETH_UPDATE, load=userInfo)
                logging.info("web3 thread put msg: " +
                             json.dumps(msg.load, indent=2))
                self.queue.put(msg)

            time.sleep(5)
Example #10
0
def onRecieve(msg):
    global isACKwaiting
    global camUnid
    global DriverTCP
    if (msg.cmd == "device.heartbeat"):
        #008C
        if (msg.unid == "0000" or msg.unid == ""):
            cams = Config.get('cams')
            cams = cams.split(',')
            for setid in cams:
                if (setid != ""):
                    DriverTCP.sendMsgWithCheck(
                        Msg(unid=camUnid, setid=setid, cmd="device.reg.renew"))
        else:
            DriverTCP.sendMsgWithCheck(
                Msg(unid=camUnid, setid=msg.setid, cmd="device.reg.renew"))
    elif (msg.cmd == "device.val.set"):
        isACKwaiting = True
        value = msg.value
        if '1' in value or 'true' in value or 't' in value or 'on' in value or 'вкл' in value:
            Log.i('OnRecv', 'Turning Wanscam Alarm ON')
            sendAlarm(1, msg.setid)
        elif '0' in value or 'false' in value or 'f' in value or 'off' in value or 'выкл' in value:
            Log.i('OnRecv', 'Turning Wanscam Alarm OFF')
            sendAlarm(0, msg.setid)
        elif 'up' in value or 'UP' in value:
            Log.i('OnRecv', 'Rotating Wanscam UP')
            sendCamsUp(msg.setid)
    elif (msg.cmd == 'device.reg.notif'):
        setid = msg.setid
        Config.set('cam_' + setid, '')
        cams = Config.get('cams')
        if cams == "":
            Config.set('cams', setid)
        else:
            Config.set('cams', cams + "," + setid)
Example #11
0
 def run(self):
     self.vs = VideoStream(usePiCamera=True).start()
     time.sleep(2)
     logging.info("scan qrcode thread is running...")
     while self.running:
         frame = self.vs.read()
         frame = imutils.resize(frame, width=400)
         barcodes = pyzbar.decode(frame)
         for barcode in barcodes:
             data = barcode.data
             if self.cache.has(data):
                 continue
             self.cache.add(data, None)
             msg = Msg(msgType=MsgType.SCAN_QR_CODE, load=barcode.data)
             logging.info("scan qrcode thread put msg: " + str(msg.load))
             self.queue.put(msg)
Example #12
0
 def sendHeartBeat(self):
     from Msg import Msg
     if (self.mySocketWrap != None):
         try:
             self.mySocketWrap.sendMsg(
                 Msg(unid=self.unid,
                     setid=self.setid,
                     cmd="device.heartbeat",
                     socket=self.mySocketWrap,
                     callback=self.heartbeatRes))
         except Exception as e:
             exc = str(e)
             if ("Broken pipe" in exc):
                 self.setIsOnline(False)
     else:
         self.setIsOnline(False)
Example #13
0
def onRecieve(msg):
    global isWorkingWithModem
    global isACKwaiting
    global modemUnid
    global modemSetid
    global DriverTCP

    if (msg.cmd == "device.heartbeat"):
        #if("OK" in send_at("AT").upper()) and modemSetid != "":
        DriverTCP.sendMsgWithCheck(
            Msg(unid=modemUnid, setid=modemSetid, cmd="device.reg.renew"))
        #DriverTCP.sendMsgWithCheck(msg)
    elif (msg.cmd == "device.val.set"):
        while isWorkingWithModem == True:
            pass
        isACKwaiting = True
        parseHubCmd(msg.value)
    elif (msg.cmd == "device.reg.res"):
        Log.i("Receive/RegFin", "Got SetID", msg.value)
        modemSetid = msg.value.replace(",", "")
        Config.set('id', modemSetid)
        HUB_sendACK()
Example #14
0
 def init_start_msg(self):
     #绘制开始页面文本
     self.bk = (0, 0, 0)
     self.title_msg = Msg(self.screen, 'Energy Game', 300, 70, 80, self.bk,
                          (230, 230, 230), 375, 40)
     self.continue1_msg = Msg(self.screen, 'Continue', 200, 70, 60, self.bk,
                              (230, 230, 230), 425, 180)
     self.new_game_msg = Msg(self.screen, 'New Game', 200, 70, 60, self.bk,
                             (230, 230, 230), 425, 280)
     self.options_msg = Msg(self.screen, 'Options', 200, 70, 60, self.bk,
                            (230, 230, 230), 425, 380)
     self.rules_msg = Msg(self.screen, 'Game Rules', 200, 70, 60, self.bk,
                          (230, 230, 230), 425, 480)
     self.exit_msg = Msg(self.screen, 'Exit', 200, 70, 60, self.bk,
                         (230, 230, 230), 425, 580)
     self.start_msgs = [
         self.title_msg, self.continue1_msg, self.new_game_msg,
         self.options_msg, self.rules_msg, self.exit_msg
     ]
     for i in self.start_msgs:
         i.create_msg()
         i.draw_msg()
Example #15
0
def main():

    running = True

    r = Robot(tokenbot.token_bot)
    dog = Dog()
    m_flow = Msg('flw')
    m_dr = Msg('dr')  #daily route

    lst_id = r.get_f_lst_id()

    while running:
        time.sleep(r.dyn_delay)  # (0.9)

        r.get_lst_msg_bot()
        if (not r.skippy):
            if r.lst_msg_id > int(lst_id):
                m_flow.init_xtnd(r.lst_msg)

                m_flow.chk_msg_type()
                if m_flow.v_msg_fid != None:
                    m_flow.v_msg_f_pth = r.bot.get_file(
                        m_flow.v_msg_fid)['file_path']
                    m_flow.v_msg_rcgz()

                m_flow.analyze_txt_in_msg()

                r.snd_msg(m_flow.anlz_msg_cht_id, m_flow.cre_msg_txt_new)

                r.upd_f_lst_id()
                lst_id = str(r.lst_msg_id)

        m_dr.daily_route()
        if m_dr.dr_sw_warn:
            r.snd_msg(m_dr.anlz_msg_cht_id, m_dr.cre_msg_txt_new)
            m_dr.dr_sw_warn = False

        if m_flow.sw_dog_act:
            dog.dog_act()
            if dog.sw_dog_msg:
                r.snd_msg(tokenbot.dr_usr_id, dog.dog_msg)
                if m_flow.sw_dogpic:
                    r.snd_photo(tokenbot.dr_usr_id, dog.dd_jpg)
        else:
            dog.rmss_l = []

        if m_flow.sw_ssh:
            dog.ssh_act()
            m_flow.sw_ssh = False
Example #16
0
    def start(self):
        self.rtmpUrl = 'rtmp://39.107.26.100:1935:1935/myapp/test1'

        mycv = CvHelp()

        # 视频来源
        filePath = '/mnt/e/nginx-rtmp/'
        filePath = ''
        camera = cv2.VideoCapture(filePath + "test2.mp4")  # 从文件读取视频

        # camera = cv2.VideoCapture(0) # 参数0表示第一个摄像头 摄像头读取视频
        # if (camera.isOpened()):# 判断视频是否打开
        #     print 'Open camera'
        # else:
        #     print 'Fail to open camera!'
        #     return
        # camera.set(cv2.CAP_PROP_FRAME_WIDTH, 600)  # 2560x1920 2217x2217 2952×1944 1920x1080
        # camera.set(cv2.CAP_PROP_FRAME_HEIGHT, 450)
        # camera.set(cv2.CAP_PROP_FPS, 5)

        # 视频属性
        size = (int(camera.get(cv2.CAP_PROP_FRAME_WIDTH)),
                int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        # size = (size[0] / 10, size[1] / 10)
        sizeStr = str(size[0]) + 'x' + str(size[1])
        fps = camera.get(cv2.CAP_PROP_FPS)  # 30p/self
        fps = int(fps)
        print 'size:' + sizeStr + ' fps:' + str(fps)

        # 视频文件保存
        # fourcc = cv2.VideoWriter_fourcc(*'XVID')
        # out = cv2.VideoWriter(filePath+'res_mv.avi',fourcc, fps, size)
        # 管道输出 ffmpeg推送rtmp
        command = [
            'ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo',
            '-pix_fmt', 'bgr24', '-s', sizeStr, '-r',
            str(fps), '-i', '-', '-c:v', 'libx264', '-pix_fmt', 'yuv420p',
            '-preset', 'ultrafast', '-f', 'flv', self.rtmpUrl
        ]
        pipe = sp.Popen(command, stdin=sp.PIPE)  #,shell=False

        lineWidth = 1 + int((size[1] - 400) / 400)  # 400 1 800 2 1080 3
        textSize = size[1] / 1000.0  # 400 0.45
        heightDeta = size[1] / 20 + 10  # 400 20
        count = 0
        faces = []
        while True:
            ###########################图片采集
            count = count + 1
            ret, frame = camera.read()  # 逐帧采集视频流
            if not ret:
                break
            detectCount = 0
            if (count % fps == 0):
                ###########################图片处理
                # 探测图片中的人脸 延帧检测
                faces = mycv.classfier.detectMultiScale(frame,
                                                        scaleFactor=1.1,
                                                        minNeighbors=5,
                                                        minSize=(5, 5))
                detectCount = len(faces)
                pass
            for (x, y, w, h) in faces:
                # cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
                mycv.drawRect(frame, (x, y), (x + w, y + h), (128, 64, 255),
                              line_width=lineWidth)

            frame = cv2.resize(frame, size)
            # 绘制推送图片帧信息
            fpsshow = "Fps  :" + str(int(fps)) + "  Frame:" + str(count)
            nframe = "Play :" + str(int(count / fps))
            ntime = "Time :" + time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime())
            # if(count % fps == 0):
            #     print(fpsshow + " " + ntime)
            mycv.drawText(frame, (0, heightDeta * 1),
                          fpsshow,
                          textSize=textSize,
                          lineWidth=lineWidth)
            mycv.drawText(frame, (0, heightDeta * 2),
                          nframe,
                          textSize=textSize,
                          lineWidth=lineWidth)
            mycv.drawText(frame, (0, heightDeta * 3),
                          ntime,
                          textSize=textSize,
                          lineWidth=lineWidth)

            # 当发现人脸 进行 操作
            # 保存图片文件
            # 记录数据库
            # 推送提醒socket
            if (detectCount > 0):
                msg = Msg()
                fileId = 'res_' + time.strftime(
                    "%Y%m%d%H%M%S",
                    time.localtime()) + '_' + str(count) + '.png'
                msg.data['res'] = fileId
                msg.data['type'] = 'broadcast'
                # mycv.save(filePath + fileId, frame)
                if (self.serverSocket):
                    self.serverSocket.sendImpl(jsonstr)

                    pass

                pass
            ############################图片输出
            # 结果帧处理 存入文件 / 推流 / ffmpeg 再处理
            # out.write(frame)    # 存入视频文件
            pipe.stdin.write(frame.tostring())  # 存入管道

            pass
        camera.release()
        # Release everything if job is finished
        # out.release()
        print("Over!")
        pass
Example #17
0
def CAN_onRecieve(msg):
    global pi
    bytes = msg.data
    data = []
    for byte in bytes:
        data.append(int(byte))
    remote = msg.is_remote_frame
    id = msg.arbitration_id
    fd = msg.is_fd
    err = msg.is_error_frame
    strId = ('%.8x' % (id)).lower()
    print("1")
    if err == False and len(data) > 0 and len(strId) == 8:
        unid = strId[:4]
        setid = strId[4:]
        powerSupply = pi.read(PS_PIN) == 0
        if (len(unid) == 4 and unid != "0000" and unid != ""
                and powerSupply == True):
            Log.i('Recv', ("Received: From %s with data: %s" %
                           (strId, ';'.join(map(str, data)))))
            cmd = int(data[0] / 16)
            Log.i('Recv', "CMD: %i" % cmd)
            frameCount = data[0] % 16
            if (frameCount > 1):
                curFrame = data[1]
                if (curFrame > 0 and id in messagesWaitingComplete):
                    messagesWaitingComplete[id].value += ';'.join(
                        map(str, data[2:]))
                elif (curFrame == 0):
                    if (setid == "0000"):
                        setid = ""
                    messagesWaitingComplete[id] = Msg(unid=unid,
                                                      setid=setid,
                                                      cmd=cmdIntToStr(cmd),
                                                      value=','.join(
                                                          map(str, data[2:])),
                                                      callback=ACK_clb)
                elif (curFrame == (frameCount - 1)
                      and id in messagesWaitingComplete):
                    DriverTCP.sendMsg(messagesWaitingComplete[id])
                    del messagesWaitingComplete[id]
                else:
                    Log.e('Recv',
                          "ERROR: Lost first frames or message incomplete")
            else:
                if (setid == "0000"):
                    setid = ""

                msg = Msg(unid=unid,
                          setid=setid,
                          cmd=cmdIntToStr(cmd),
                          value=';'.join(map(str, data[1:])),
                          callback=ACK_clb)
                Log.d("Recv/TCPSend", "MSG:", msg.toJSON())
                DriverTCP.sendMsg(msg)
        elif (powerSupply == False):
            Log.w('Recv', "Skipping garbage")
        else:
            Log.w('Recv', "id:", id, "data:", data)
    else:
        Log.w('Recv', "Er:", err, "id:", id, "data:", data)
Example #18
0
    def reciveWorker(self):
        self.tcpConn.settimeout(10)
        try:
            if self.IP == '127.0.0.1' or self.IP == 'localhost':
                self.interface = 0
            else:
                self.interface = 1
            self.tcpConn.setblocking(1)

            self.sendMsg(Msg(cmd="device.heartbeat", socket=self,
                             setid="0001"))
            #self.tcpConn.setblocking(0)
            i = 0
            start = time.clock()
            while True:
                ready = False
                sleep(0.002)
                try:

                    if ((time.clock() - start) > 5.0):
                        self.tcpConn.sendall("\n".encode())
                        start = time.clock()
                    data = self.tcpConn.recv(2048).decode('utf-8')
                    if (len(data) > 3):
                        for line in data.split("\n"):
                            if (line != ""):
                                Log.i('SocketWrap', "Received MSG: " + line)
                                msg = Msg.fromJSONstr(self, line)
                                if (msg.cmd == "ACK" or msg.cmd == "0"):
                                    msg.cmd = "ACK"
                                    Log.i(
                                        'SocketWrap',
                                        "ACK recived. Looking for awating msgs "
                                        + msg.toJSON())
                                    toRemove = []
                                    for i in range(len(self.outgoingMSG)):
                                        if (i > len(self.outgoingMSG)):
                                            break
                                        msgS = self.outgoingMSG[i]
                                        if (msgS.setid == msg.setid
                                                and msgS.unid == msg.unid):
                                            Log.i(
                                                'SocketWrap/ACK',
                                                "Msg for ACK found:" +
                                                msgS.toJSON(), msg)
                                            if (msgS.callback != None):
                                                Log.d('SocketWrap/ACK',
                                                      "Calling callback")
                                                msgS.callback(msg)
                                            if (msgS.socket != None):
                                                msgS.socket.sendAck(
                                                    setid=msgS.setid,
                                                    unid=msgS.unid)
                                            toRemove.append(i)
                                            #break
                                    for i in range(len(toRemove)):
                                        try:
                                            del self.outgoingMSG[i]
                                        except:
                                            pass
                                    Log.i('SocketWrap', "ACK proceed complete")
                                elif (msg.cmd == "device.reg.new"
                                      or msg.cmd == "10"):
                                    msg.cmd = "device.reg.new"
                                    self.registerDevice(msg.unid)
                                    #msg.callback = self.sendMsg
                                    #SocketWrap.outgoingMSG.append(msg)
                                elif (msg.cmd == "device.reg.renew"
                                      or msg.cmd == "device.heartbeat"
                                      or msg.cmd == "12" or msg.cmd == "1"):
                                    Log.i('SocketWrap',
                                          "Got MSG: " + msg.toJSON())
                                    allId = msg.unid + '' + msg.setid
                                    if allId not in SocketWrap.allUnits:
                                        Log.e(
                                            'SocketWrap',
                                            "Not able to find device by ID " +
                                            allId + " . Registering as new")
                                        self.registerDevice(
                                            msg.unid, msg.setid)
                                        continue
                                    msg.device = SocketWrap.allUnits[allId]
                                    device = msg.device
                                    device.mySocketWrap = self
                                    device.setIsOnline(True)
                                    self.units[allId] = device
                                    SocketWrap.onlineUnits[allId] = device
                                    if (msg.cmd == "12"):
                                        msg.cmd = "device.reg.renew"
                                    elif (msg.cmd == "1"):
                                        msg.cmd = "device.heartbeat"
                                    if (msg.socket != None):
                                        msg.socket.sendAck(setid=msg.setid,
                                                           unid=msg.unid)
                                    #else:
                                    self.sendAck(setid=msg.setid,
                                                 unid=msg.unid)
                                    #if(device.isOnline ==False):
                                    Log.i(
                                        'SocketWrap', "Dir: " +
                                        device.direction + ", nedStVal = %s" %
                                        device.needSetValue)

                                    if 'O' in device.direction and device.needSetValue == True:
                                        Log.i('SocketWrap',
                                              "Sending last missed value")
                                        device.needSetValue = False
                                        #self.tcpConn.send(allId+''+device.parseFormatToValue(device.lastValue)+'\r\n')

                                        DB.registerEvent(
                                            device.unid, device.setid,
                                            'SocketWrap',
                                            'device register renew.')
                                        device.setValue(device.lastValue)
                                        msg.callback = self.onNeedSetValueAck
                                        #SocketWrap.outgoingMSG.append(msg)

                                elif (msg.cmd == "device.val.input"
                                      or msg.cmd == "20"):
                                    msg.cmd = "device.val.input"
                                    self.sendAck(setid=msg.setid,
                                                 unid=msg.unid)
                                    self.onValueRecieved(
                                        msg.unid, msg.setid, msg.value)
                                elif (msg.cmd == "device.val.set"
                                      or msg.cmd == "22"):
                                    msg.cmd = "device.val.set"
                                    allId = msg.unid + '' + msg.setid
                                    if allId not in SocketWrap.allUnits:
                                        Log.e('SocketWrap',
                                              "Not able to get device ID")
                                        return
                                    device = SocketWrap.allUnits[allId]
                                    Log.d('DeviceSetVal', "[1]")
                                    device.setValue(msg.value,
                                                    callback=sendMsg)
                                    Log.d('DeviceSetVal', "[2]")
                                    msg.callback = self.sendMsg
                                    #SocketWrap.outgoingMSG.append(msg)
                                    #socketWrap.onValueRecieved(msg.unid,msg.setid,value)
                                    Log.d('DeviceSetVal', "[3]")
                        Log.i('SocketWrap', "MSG proceed complete")
                except ValueError as e:
                    Log.e('SocketWrap/ValueError', "While E " + str(e),
                          traceback.format_exc())
                '''except socket.timeout: 
					#self.tcpConn.setblocking(0)
					try:
						if i == 5:
							i = 0
							self.tcpConn.send("\n")
						i+=1
					except:
						break
					#pass
				except socket.error as e:
					#print("[D] While E ", e)
					try:
						if i == 25:
							i = 0
							#self.tcpConn.send("\n")
							self.tcpConn.send(" ")
						i+=1
					except:
						break
					#pass
				
				except Exception as e:
					exc = str(e)
					Log.e('SocketWrap/ValueError',exc)'''
        #finally:
        except socket.error:
            Log.e('SocketWrap/Thread/1', "Closing socket: %s " % socket.error,
                  traceback.format_exc())
        except Exception as e:
            exc = str(e)
            Log.e('SocketWrap/Thread/2', exc, traceback.format_exc())
        Log.i('SocketWrap', "Closing driver ")

        #self.tcpConn.shutdown(2)
        self.tcpConn.close()
        self.onClientDisConnected()
        Log.i('SocketWrap',
              "Client disConnected: " + self.IP + ":" + self.port)
        if 'socketWrap' in locals():
            del self
Example #19
0
 def sendAck(self, unid, setid):
     Log.i('SocketWrap/sendAck', "To %s %s" % (unid, setid))
     self.sendMsg(Msg(unid=unid, setid=setid, cmd="ACK", socket=self))
Example #20
0
def process(conn, msg):
    print msg
    msg_obj = Msg(msg)
    #print msg_obj
        
    if msg_obj.get_type() == MsgCon.TYPE_FILE_INFO:
        body = tornado.escape.json_decode(msg_obj.get_body())
        print body
        conn._tmp_files[body["file_id"]] = File(body["filename"], body["file_id"], body["file_chunk_count"])
        #print "File Info: ID-%s Name-%s Length-%d"% (body["file_id"], body["filename"], body["file_chunk_count"])
        tmp_msg = Msg(None, "0000000000")        
        tmp_msg.set_value("msg_id", msg_obj.get_msg_id())
        tmp_msg.set_type(MsgCon.TYPE_ACK)
        tmp_msg.set_body({"status": 200})
        conn.write_message(str(tmp_msg))
        
    elif msg_obj.get_type() == MsgCon.TYPE_FILE_PUSH:
        body = tornado.escape.json_decode(msg_obj.get_body())
        print "PUSH"
        
        for file_obj in conn._client._files.itervalues():
            if file_obj.file_id not in _clients[body["client_id"]]._downloaded:
                tmp_msg = Msg(None, "0000000000")
                tmp_msg.set_type(MsgCon.TYPE_FILE_INFO)
                tmp_msg.set_body(file_obj.get_dict())
                _clients[body["client_id"]].write_message(str(tmp_msg))
                     
                     
                print file_obj.file_id
                print file_obj.file_ref
                file_obj.inflate()
                   
                for chunk in file_obj._chunks.itervalues():
                    tmp_msg1 = Msg(None, "0000000000")
                    tmp_msg1.set_type(MsgCon.TYPE_FILE_CHUNK)
    
                    print chunk.file_id
                    print chunk.chunk_id
                    tmp_msg1.set_body(chunk.__dict__)
                    _clients[body["client_id"]].write_message(str(tmp_msg1))
                    
                _clients[body["client_id"]]._downloaded.append(file_obj.file_id);
                print "DONE"
            
            print conn._client._files

        
    elif msg_obj.get_type() == MsgCon.TYPE_FILE_REQUEST:
        body = tornado.escape.json_decode(msg_obj.get_body())
        
        print _clients[body["client_id"]]._client._files

        for file_obj in _clients[body["client_id"]]._client._files.itervalues():
            if file_obj.file_id not in conn._downloaded:

                tmp_msg = Msg(None, "0000000000")
                tmp_msg.set_type(MsgCon.TYPE_FILE_INFO)
                tmp_msg.set_body(file_obj.get_dict())
                conn.write_message(str(tmp_msg))
                     
                     
                print file_obj.file_id
                print file_obj.file_ref
                file_obj.inflate()
                   
                for chunk in file_obj._chunks.itervalues():
                    tmp_msg1 = Msg(None, "0000000000")
                    tmp_msg1.set_type(MsgCon.TYPE_FILE_CHUNK)
    
                    print chunk.file_id
                    print chunk.chunk_id
                    tmp_msg1.set_body(chunk.__dict__)
                    conn.write_message(str(tmp_msg1))
                    
                conn._downloaded.append(file_obj.file_id);
                print "DONE"
            
            print conn._client._files
                
        
    elif msg_obj.get_type() == MsgCon.TYPE_FILE_CHUNK:
        body = tornado.escape.json_decode(msg_obj.get_body())
        # body
        tmp_file = conn._tmp_files[body["file_id"]]
        tmp_file.add_chunk(Chunk(body))
        
        tmp_msg = Msg(None, "0000000000")
        tmp_msg.set_value("msg_id", msg_obj.get_msg_id())
        tmp_msg.set_type(MsgCon.TYPE_ACK)
        tmp_msg.set_body({"status": 200})
        conn.write_message(str(tmp_msg))

        #print "File Chunk: ID-%s Chunk-%d"% (body["file_id"], body["chunk_id"])
        
        if tmp_file.check_chunks() == 0:
            print "File Received: ID-%s"% (body["file_id"])
            if tmp_file.validate():
                print "File Validated: ID-%s"% (body["file_id"])
                tmp_file.deflate(TMP_FILE_DIR)
                
                conn._client.add_file(tmp_file)
                conn._tmp_files[body["file_id"]] = None
                del conn._tmp_files[body["file_id"]]
                
                tmp_msg = Msg(None, "0000000000")
                tmp_msg.set_value("msg_id", msg_obj.get_msg_id())
                tmp_msg.set_type(MsgCon.TYPE_ACK)
                tmp_msg.set_body({"status": 200})
                conn.write_message(str(tmp_msg))
                
                
                
                
                
                
                
                
                
            else:
                print "FILE WENT WRONG" 
        
    """
Example #21
0
    def registerDevice(self, unid, setid=''):
        Log.i('SocketWrap', "Registering new device " + unid)
        resInfo = DB.sqlSelect(
            "SELECT units_def.description  FROM `units_def` WHERE unid = '%s'"
            % unid)
        if (setid == ''):
            res = DB.sqlSelect(
                "SELECT units_run.setid  FROM `units_run` WHERE units_run.unid = '%s' ORDER BY `id` DESC LIMIT 1 "
                % unid)
        #print("SELECT `id` FROM `units_run` WHERE `unid` = '%s' ORDER BY `id` DESC LIMIT 1 " % unid)
        nextSetdId = ''

        if len(resInfo) == 0:
            Log.e('SocketWrap', 'Unknown produced device connected')
            DB.addAlert(unid, nextSetdId, 1004)
            return Device(0, 0, self)
        else:
            if (setid != ''):
                nextSetdId = setid
            elif len(res) > 0:
                Log.i('SocketWrap', "Last id: %s" % res[0]['setid'])
                nextSetdId = '{:04x}'.format(int(res[0]['setid'], 16) + 1)
            else:
                nextSetdId = '0001'
            nextSetdId = nextSetdId.upper()
            Log.i('SocketWrap',
                  "Registering new device with id: " + unid + "|" + nextSetdId)

            sql = """
				INSERT INTO `units_run`
				(
				 `unid`,
				 `setid`,
				 `lastvalue`,
				 `lasttime`,
				 `timeAdded`,
				 `interface`,
				 `name`,
				 `alive`
				)
				VALUES
				(
				 '%s',
				 '%s',
				 '',
				 '',
				 '%s',
				 '%s',
				 '%s',
				 '1'
				); 
			""" % (unid, nextSetdId, strftime("%Y.%m.%d %H:%M:%S", localtime()),
            self.interface, resInfo[0]['description'])
            id = DB.sqlInsert(sql)

            msg = Msg(unid=unid,
                      setid=setid,
                      cmd="device.reg.res",
                      value=nextSetdId[:2] + ',' + nextSetdId[2:],
                      socket=self)
            self.outgoingMSG.append(msg)

            device = Device(unid, nextSetdId, self)
            device.id = id
            device.isOnline = True
            allId = unid + '' + nextSetdId
            self.units[allId] = device
            SocketWrap.allUnits[allId] = device
            SocketWrap.onlineUnits[unid + '' + nextSetdId] = device

            DB.registerEvent(unid, nextSetdId, 'SocketWrap',
                             'Registered new device!')
            return device
Example #22
0
def sendPowerSupplyValue(value):
    global DriverTCP
    DriverTCP.sendMsgWithCheck(
        Msg(unSetId=Config.get('id'), value=str(value),
            cmd="device.val.input"))
Example #23
0
    def thread(self, intfId):
        try:
            start = time.clock()
            Log.i('DriverTCP/Thread', 'Connected')

            while True:
                #try:
                if ((time.clock() - start) > 5.0):
                    #Log.d('PortalConnect/Thread','Keep Alvie sent')
                    self.sock.sendall("\n".encode())
                    start = time.clock()
                try:
                    ready_to_read, ready_to_write, in_error = select.select([
                        self.sock,
                    ], [
                        self.sock,
                    ], [], 5)
                except select.error:
                    #conn.shutdown(2)    # 0 = done receiving, 1 = done sending, 2 = both
                    # connection error event here, maybe reconnect
                    break

                #if len(ready_to_read) > 0:
                data = self.sock.recv(2048).decode('utf-8')
                if not data:
                    break
                if len(data) > 5:
                    for line in data.split("\n"):
                        if len(line) > 5:
                            Log.i('DriverTCP/Thread', 'received "%s"' % line)
                            from DriverTCP import Msg
                            msg = Msg.fromJSONstr(self, line)
                            if (msg.cmd == "ACK" or msg.cmd == "0"
                                    or msg.cmd == "device.reg.res"):
                                #msg.cmd = "ACK"
                                Log.i(
                                    'DriverTCP/Thread',
                                    "ACK recived. Looking for awating msgs " +
                                    msg.toJSON())
                                isAckThere = False
                                toRemove = []
                                for i in range(len(self.outgoingMSG)):
                                    msgS = self.outgoingMSG[i]
                                    if (msgS.setid == msg.setid
                                            and msgS.unid == msg.unid):
                                        Log.i(
                                            'DriverTCP/ACK',
                                            "Msg for ACK found:" +
                                            msgS.toJSON(), msg)
                                        if (msgS.callback != None):
                                            Log.d('DriverTCP/ACK',
                                                  "Calling callback")
                                            msgS.callback(msg)
                                        if (msgS.socket != None):
                                            msgS.socket.sendAck(
                                                setid=msgS.setid,
                                                unid=msgS.unid)
                                        toRemove.append(i)
                                        isAckThere = True
                                        #break
                                for i in range(len(toRemove)):
                                    try:
                                        del self.outgoingMSG[i]
                                    except:
                                        pass
                                Log.i('DriverTCP/Thread',
                                      "ACK proceed complete")
                                if ((isAckThere == False
                                     or msg.cmd == "device.reg.res")
                                        and self.onRecieveCallback != None):
                                    Log.i('DriverTCP/Thread',
                                          "Calling callback", msg.cmd)
                                    self.onRecieveCallback(msg)
                            elif (msg != None and self != None
                                  and self.onRecieveCallback != None):
                                self.onRecieveCallback(msg)
                #else:
                #break
                #time.sleep(0.3)
                '''except ValueError as e:
					Log.e('DriverTCP/Thread',"While E: %s"%e)
				except ConnectionError as e:
					Log.e('DriverTCP/Thread',"While E: %s"%e)'''
                #except socket.error:
                #	Log.e('DriverTCP/Thread',"Closing driver: ", socket.error)
        except socket.error:
            Log.e('DriverTCP/Thread/1', "Closing socket: %s " % socket.error,
                  traceback.format_exc())
        except Exception as e:
            exc = str(e)
            Log.e('DriverTCP/Thread/2', exc, traceback.format_exc())
        #except ValueError:
        Log.d('DriverTCP/Thread', 'closing socket', ValueError)
        self.sock.close()
        self.connect()
Example #24
0
 def registerDevice(self, unid):
     msg = Msg(unid=unid, value=str(1), cmd="device.reg.new")
     self.sendMsg(msg)
Example #25
0
	def client_thread(conn, addr):
		conn.settimeout(7)
		conn.setblocking(1)
		try:
			
			#conn.setblocking(0)
			i =0
			while API.threadRun:
				ready = False
				time.sleep(0.2)
				try:
					data = conn.recv(1024)
					if not data:
						break
					#print(data)
					jsonObj = json.loads(data.decode('utf-8'))
					if ('token' not in jsonObj or jsonObj['token'] != API.token):
						conn.send(json.dumps({"errcode": "2003", "msg": "Wrong API token"}).encode())
						conn.close()
					else:
						payload = jsonObj['data']
						if ('cmd' in payload):
							cmd = payload['cmd']
							if (cmd == 'device.value.set'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueACK',"Is device online: %i"%device.isOnline)
								while(API.socketAwaitACK !=None):
									continue
								if (device != None):
									API.socketAwaitACK = conn
									device.setValue(payload['value'].strip(), callback=API.onValueSetACK)
									
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.value.schedule'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueSchedule',"Is device online: %i"%device.isOnline)
								
								if (device != None):
									value = payload['value'].strip()
									print("'",value,"'")
									date = payload['date']
									unid = device.unid
									setid = device.setid
									scriptStr = f'''
newVal = '{value}'
unit    = Device.findDeviceById('{unid}','{setid}')
smsStr = 'sms,all,*'
if unit != None:
	unit.setValue(newVal)
	smsStr = smsStr + 'Value {value} set ok'
else:
	smsStr = smsStr + 'Error setting value {value}'

modems = Device.findDeviceById('0078','')
if len(modems)>0:
	for key, modem in modems.items():
		modem.setValue(smsStr)
'''
									
									uscript = ''.join(random.choice(string.ascii_uppercase + string.digits) for i in range(5))+".py"
									dir = common.config['HubServer']['USCRIPTS_PATH']+'Temp/'
									path = dir+uscript
									if not os.path.exists(dir):
										os.makedirs(dir)
									outFile = open(path, "w+", encoding="utf-8")
									outFile.write(scriptStr)
									outFile.close()
									DB.sqlInsert(f"""
										INSERT INTO `schedule`
										(
											`type`, 
											`time`, 
											`lastTimeRun`, 
											`nextTimeRun`, 
											`script_name`, 
											`active`
										)
										VALUES
										(
											'1',
											'{date}',
											'',
											'',
											'{uscript}',
											'1'
										); 
									""")
									from Tasker import Task
									Task.getAllTasks()
									conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.conf.set'):
								device = Device.findDeviceById(payload['unitId'],payload['setId'])
								Log.i('API/OnValueACK',"Is device online: %i"%device.isOnline)
								while(API.socketAwaitACK !=None):
									continue
								if (device != None):
									if(device.isOnline):
										API.socketAwaitACK = conn
										device.setSettings(payload['value'], callback=API.onValueSetACK)
									else:
										conn.send(json.dumps({"errcode": "3003", "msg": "Device offline", "payload":payload}).encode())
									
								else:
									conn.send(json.dumps({"errcode": "3002", "msg": "No such device", "payload":payload}).encode())
							elif (cmd == 'device.reg.notif'):
								unid = payload['unitId']
								setid = payload['setId']
								devices = Device.findDeviceById(unid)
								msg = Msg(unid = unid, setid = setid, cmd="device.reg.notif")
								while(API.socketAwaitACK !=None):
									continue
								isNeedAll = True
								Log.d("API/NotifyNew",devices)
								for key, device in devices.items():
									if(device.mySocketWrap != None):
										API.socketAwaitACK = conn
										device.mySocketWrap.sendMsg(msg)
										isNeedAll = False
										break

								Log.d("API/NotifyNew","[4]Point")
								if isNeedAll:
									for socketWrap in SocketWrap.allSockets:
										socketWrap.sendMsg(msg)
									#print("Disc/Is device online",SocketWrap.allUnits["00B40172"].isOnline)
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('wifi.update' in cmd):
								interface = 'wlan0'
								name = payload['ssid']
								password = payload['password']
								os.system('iwconfig ' + interface + ' essid ' + name + ' key ' + password)
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('config.update' in cmd):
								if ('db' in cmd):
									common.config.set('DataBase', 'HOST', payload['host'])
									common.config.set('DataBase', 'USER', payload['login'])
									common.config.set('DataBase', 'PASSW', payload['password'])
									common.config.set('DataBase', 'DB', payload['dbname'])
									common.config.set('DataBase', 'CHARSET', payload['charset'])
									DB.close()
									DB.start()
									Log.i('API/ConfigUpdate/DB',"MySQL reconnect")
									conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('schedule.update' in cmd):
								from Tasker import Task
								Task.getAllTasks()
								conn.send(json.dumps({"errcode": "0", "data": {}}).encode())
							elif ('uscript.run' in cmd):
								from Tasker import Task
								res = Task.runUserScriptEnv(payload['uscript'])
								conn.send(json.dumps({"errcode": "0", "data": res}).encode())
							elif (cmd == 'system.stat.get'):
								response = {}
								response['Hub_version'] = common.config['HubServer']['VERSION']
								if ('PortalConnect' in common.config):
									response['Hub_id'] = common.config['PortalConnect']['id']
								response['CPU_load'] = str(psutil.cpu_percent()) + '%'
								memory = psutil.virtual_memory()
								# Divide from Bytes -> KB -> MB
								available = round(memory.available/1024.0/1024.0,1)
								total = round(memory.total/1024.0/1024.0,1)
								response['Memory'] = str(available) + 'MB free / ' + str(total) + 'MB total ( ' + str(memory.percent) + '% )'
								
								disk = psutil.disk_usage('/')
								disk_total = round(disk.total / 2**30,2)     # GiB.
								disk_used = round(disk.used / 2**30,2)
								disk_free = round(disk.free / 2**30,2)
								disk_percent_used = disk.percent
								response['Disk'] = str(disk_free) + 'GB free / ' + str(disk_total) + 'GB total ( ' + str(disk_percent_used) + '% )'
								
								conn.send(json.dumps({"errcode": "0", "data": response}).encode())
							elif (cmd == 'system.cmd'):
								shell = payload['shell']
								Log.i('API',"Executing shell cmd %s"%shell)
								#res = str(check_output(shell.split(" ") ))
								res = subprocess.Popen(shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=10,shell=True, cwd=os.path.dirname(os.path.realpath(__file__))+"/../" )
								stdout,stderr = res.communicate()
								Log.i('API/',"Executing shell cmd res %s"%stdout)
								res = stdout.decode('utf-8')
								resLo = res.lower()
								if ("error" in resLo or "not exists" in resLo or "forbidden" in resLo or "not allow" in resLo or "failed" in resLo): 
									conn.send(json.dumps({"errcode": "2006", "msg": res}).encode())
								else:
									conn.send(json.dumps({"errcode": "0", "data": res}).encode())
							else:
								conn.send(json.dumps({"errcode": "2005", "data": {'cmd':cmd}}).encode())
				except socket.timeout: 
					try:
						if i == 5:
							i = 0
							conn.send("\n")
						i+=1
					except:
						break
				except socket.error as e:
					try:
						if i == 25:
							i = 0
							conn.send(" ")
						i+=1
					except:
						break
				except ValueError as e:
					Log.e('API/ValueError',"While E: %s"%e)
				except:
					conn.send(json.dumps({"errcode": "2003", "msg": "Error proceeding request"}).encode())
					Log.e('API/ValueError',"During API request execution fail")
		except socket.error as e:
			Log.e('API/ValueError'," Closing driver: %s"% e)
		except ValueError as e:
			Log.e('API/ValueError'," Closing driver: %s"% e)
		conn.close()
		Log.i('API/',"API client disconnected: " + addr[0] + ":" + str(addr[1]))
Example #26
0
 def handle_event(self, event):
     userInfo = self.getUserInfo()
     msg = Msg(msgType=MsgType.ETH_UPDATE, load=userInfo)
     logging.info("web3 thread put msg: " + json.dumps(msg.load, indent=2))
     self.queue.put(msg)