Beispiel #1
0
def sdv_callback(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    logger1.debug("sdv: " + msg.topic + "->" + msg.payload, level="i")
    topicArray = string.rsplit(msg.topic, '/')
    dev = topicArray[len(topicArray) - 3]
    ch = topicArray[len(topicArray) - 2]
    obj = topicArray[len(topicArray) - 5]
    if (int(dev) == getTlgDev()):
        logger1.debug("route to Telegram device: " + msg.payload, level="i")
        client.publish("/ssn/acc/" + str(ACCOUNT) + "/telegram/out",
                       payload=msg.payload,
                       qos=0,
                       retain=False)
    else:
        # make set dev value command:
        sdv = '{"ssn":{"v":1,"obj":' + obj + ',"cmd":"sdv", "data": {"adev":' + dev + ',"acmd":' + ch + ',"aval":' + msg.payload + '}}}"'
        #    logWrite("sdv= "+sdv, level="i")
        tmpMsg = ssnMsg(destObj=int(obj),
                        srcObj=0,
                        msgType=2,
                        msgID=None,
                        msgData=sdv)
        client.publish("/ssn/acc/" + str(ACCOUNT) + "/obj/" + obj +
                       "/commands",
                       tmpMsg.getSSNPDU(),
                       qos=0,
                       retain=False)
Beispiel #2
0
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    logWrite(msg.topic+"->"+msg.payload)
    tail = msg.payload
    while len(tail):
        tmpMsg = ssnMsg()
        tail, nResult = tmpMsg.processBuffer(tail)
        # send message into serial interface if obj_dest in serials route list
        if (nResult):
            if (tmpMsg.destObj in serial_if):
                logWrite("route into serial, dest Obj="+str(tmpMsg.destObj), level="i")
                # use serial interface
#                serWrite(ser1, str(msg.payload))
                serPutMsg(str(msg.payload))
#                ser1.setRTS(True)
#                ser1.write(str(msg.payload))
#                while (ser1.outWaiting() > 0):
#                    time.sleep(0.01)
#                ser1.setRTS(False)
            elif (tmpMsg.destObj == tlg_if):
                logWrite("route to Telegram: "+msg.topic+"->"+msg.payload, level="i")
                if (ssnbot):
                    ssnbot.sendTlgMessage(msg.payload)
            else:
                logWrite("skip serial routing", level="i")
Beispiel #3
0
def send_command(strCmd, nCmdType, destObj):
    ssnTempMsg = ssnMsg(destObj=destObj,  srcObj=getProxyObj(), msgType=nCmdType, msgID=None, \
    msgData=strCmd, msgChannel=None, msgSocket=None, msgSerial=None)

    client.publish("/ssn/acc/" + str(ACCOUNT) + "/obj/" + str(destObj) +
                   "/commands",
                   ssnTempMsg.getSSNPDU(),
                   qos=0,
                   retain=False)
Beispiel #4
0
def sdv_callback(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    logWrite("sdv: "+msg.topic+"->"+msg.payload, level="i")
    topicArray = string.rsplit(msg.topic,'/')
    dev = topicArray[len(topicArray)-3]
    ch = topicArray[len(topicArray)-2]
    obj = topicArray[len(topicArray)-5]
    # make set dev value command:
    sdv = '{"ssn":{"v":1,"obj":'+obj+',"cmd":"sdv", "data": {"adev":'+dev+',"acmd":'+ch+',"aval":'+msg.payload+'}}}"'
#    logWrite("sdv= "+sdv, level="i")
    tmpMsg = ssnMsg(destObj=int(obj),  srcObj=0, msgType=2, msgID=None, msgData=sdv)
    client.publish("/ssn/acc/" + str(ACCOUNT)+"/obj/" + obj+"/commands",
                  tmpMsg.getSSNPDU(), qos=0, retain=False)
Beispiel #5
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print('Chat:', content_type, chat_type, chat_id)
        msg_text = ""

        content_type, chat_type, chat_id = telepot.glance(msg)
        try:
            #                msg_data = json.loads(msg)
            if (len(msg)):
                msg_text = msg["text"]
                cmdArray = string.rsplit(msg_text, ' ')
                command = cmdArray[0]
                if (len(command)):
                    print("command: " + command)
                    if (command == "/getdevvals"):
                        obj = cmdArray[1]
                        #                            if (isinstance( a,( int, long ) )
                        if (obj.isdigit()):
                            ssn_cmd = '{"ssn":{"v":1,"obj":' + obj + ',"cmd":"getdevvals", "data": {"g":1}}}'
                            #                            ssn_cmd = '===ssn10001000502003b{"ssn":{"v":1,"obj":'+int(cmdArray[1])+',"cmd":"getdevvals", "data": {"g":1}}}968f' # !!!!!!!!TO DO
                            #                                tmpMsg = ssnMsg(destObj=int(obj), srcObj=self.tlg_obj, msgType=2, msgID=None, msgData=ssn_cmd)
                            tmpMsg = ssnMsg(destObj=10,
                                            srcObj=5,
                                            msgType=2,
                                            msgID=None,
                                            msgData=str(ssn_cmd))
                            print tmpMsg.getSSNPDU()
                            self.sendSsnCommand(msg=tmpMsg.getSSNPDU(),
                                                obj_id=int(obj))
                        else:
                            self.bot.sendMessage(
                                chat_id, "ERROR: OBJ_ID not integer" + obj)

#    sdv = '{"ssn":{"v":1,"obj":'+obj+',"cmd":"sdv", "data": {"adev":'+dev+',"acmd":'+ch+',"aval":'+msg.payload+'}}}"'

                    elif (command == "/info"):
                        self.bot.sendMessage(
                            chat_id, "INFO: MQTTHOST" + self.client._host)
                    elif (command == "/unixtime"):
                        self.sendTlgMessage(
                            "MSK-1: " +
                            datetime.datetime.utcfromtimestamp(int(
                                cmdArray[1])).strftime('%Y-%m-%d %H:%M:%S'),
                            chat_id)
#                            self.bot.sendMessage(chat_id, "MSK-1: "+datetime.datetime.utcfromtimestamp(int(cmdArray[1])).strftime('%Y-%m-%d %H:%M:%S'))

        except Exception as ex:
            print("Exception message processing, msg={}: {}".format(msg, ex))

        print('Normal Message:', content_type, chat_type, chat_id)
Beispiel #6
0
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    global g_tail
    msg_len = len(msg.payload)
    logger1.debug(msg.topic + " -> " + msg.payload)
    #    tail = msg.payload
    #    g_tail = g_tail + msg.payload
    g_tail = msg.payload
    tail = ""

    while (len(tail) < msg_len):
        msg_len = len(tail)
        #    while len(tail):
        tmpMsg = ssnMsg()
        tail, nResult = tmpMsg.processBuffer(g_tail)
        # send message into serial interface if obj_dest in serials route list
        if (nResult):
            logger1.info("LOG routing message: srcObj=" + str(tmpMsg.srcObj) +
                         ", destObj=" + str(tmpMsg.destObj))
            if (len(g_tail) > 10000):  # check buffer owerflow
                logger1.warn("Buffer overflow!")
                g_tail = ""
            else:
                g_tail = tail

            if (tmpMsg.destObj in serial_if):
                logger1.info("route into serial, destObj=" +
                             str(tmpMsg.destObj) + ", srcObj=" +
                             str(tmpMsg.srcObj))
                # use serial interface
                #                serWrite(ser1, str(msg.payload))
                serPutMsg(str(msg.payload))


#                ser1.setRTS(True)
#                ser1.write(str(msg.payload))
#                while (ser1.outWaiting() > 0):
#                    time.sleep(0.01)
#                ser1.setRTS(False)
            elif (tmpMsg.destObj == tlg_if):
                logger1.info("route to Telegram: " + msg.topic + "->" +
                             msg.payload)
                if (ssnbot):
                    ssnbot.sendTlgMessage(msg.payload)
            else:
                logger1.info("skip serial routing")
Beispiel #7
0
def raw_data_callback(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    logWrite("raw_data: "+msg.topic+"->", level="i")
    logWrite(msg.payload, level="d")
    tail = msg.payload
    while len(tail):
        tmpMsg = ssnMsg()
        tail, nResult = tmpMsg.processBuffer(tail)
        if (nResult):
            if (tmpMsg.msgType == 6):
                #process LOG message
#            if (tmpMsg.destObj in serial_if):
                logWrite("LOG message, src Obj="+str(tmpMsg.srcObj), level="i")
                try:
                    ssn_data = json.loads(tmpMsg.msgData)
                    for logItem in ssn_data['log']:
                        # publish event into events topic and devices values into its topics:
                        if (len(logItem)):
                            client.publish("/ssn/acc/"+str(ACCOUNT)+"/obj/"+str(tmpMsg.srcObj)+"/events",
                                           payload=json.dumps(logItem), qos=0, retain=False)
                            client.publish("/ssn/acc/"+str(ACCOUNT)+"/obj/"+
                                str(tmpMsg.srcObj)+"/device/"+str(logItem['d'])+"/"+str(logItem['c'])+"/out",
                                payload=logItem['v'], qos=0, retain=True)
                            client.publish("/ssn/acc/"+str(ACCOUNT)+"/obj/"+
                                str(tmpMsg.srcObj)+"/device/"+str(logItem['d'])+"/"+str(logItem['c'])+"/devicetime",
                                payload=logItem['t'], qos=0, retain=True)
                except Exception as ex:
                    logWrite("Cannot decode JSON object, payload={}: {}".format(tmpMsg.msgData,ex), level="e")
            elif (tmpMsg.msgType == 2):
                #process JSON message
                logWrite("JSON message, src Obj="+str(tmpMsg.srcObj), level="i")
            elif (tmpMsg.msgType == 3):
                #process TELEMETRY message
                logWrite("TELEMETRY message, src_Obj="+str(tmpMsg.srcObj)+" dst_Obj="+str(tmpMsg.destObj), level="i")
                try:
#                    logWrite("JSON: "+tmpMsg.msgData, level="d")
                    ssn_data = json.loads(tmpMsg.msgData)
                except Exception as ex:
                    logWrite("TELEMETRY. Cannot decode JSON object, payload={}: {}".format(tmpMsg.msgData,ex), level="e")
                if (ssn_data['ssn']['ret'] == "getdevvals"):
                    processTelemetry(ssn_data['ssn']['data'], tmpMsg)
            else:
                logWrite("skip row data processing", level="i")
Beispiel #8
0
def main(argv):
    inputfile = ''
    destObj = 0
    srcObj = 3
    msgType = 2
    msgID = None
    msgData = ""

    try:
        opts, args = getopt.getopt(
            argv, "hd:fstiD",
            ["file=", "dest=", "src=", "type=", "id=", "data="])
    except getopt.GetoptError:
        print 'ssnmqc.py [--file <inputfile> or -D <data string>] --dest <destObj> -src <srcObj> --type <msgType> --id <msgID>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'ssnmqc.py [--file <inputfile> or -D <data string>] --dest <destObj> -src <srcObj> --type <msgType> --id <msgID>'
            sys.exit()
        if opt in ("-f", "--file"):
            inputfile = arg
        if opt in ("-d", "--dest"):
            destObj = int(arg, 10)
        if opt in ("-s", "--src"):
            srcObj = int(arg, 10)
        if opt in ("-t", "--type"):
            msgType = int(arg, 10)
        if opt in ("-i", "--id"):
            msgID = arg
        if opt in ("-D", "--data"):
            msgData = arg
    if (inputfile):
        with open(inputfile) as f:
            msgData = f.read()

#    print "QQQ: " + destObj
#    data = '{"ssn":{"v":1,"obj":10,"cmd":"getdevvals", "data": {"g":1}}}'
    config = {}
    execfile("ssnmqtt.cfg", config)
    #    TCPBufferSize = config["TCPBufferSize"]
    MQTT_HOST = config["MQTT_HOST"]  # mqtt boker host
    MQTT_PORT = config["MQTT_PORT"]  # mqtt boker port
    MQTT_BROKER_USER = config["MQTT_BROKER_USER"]  # mqtt broker user
    MQTT_BROKER_PASS = config["MQTT_BROKER_PASS"]  # mqtt broker password
    MQTT_BROKER_CLIENT_ID = config["MQTT_BROKER_CLIENT_ID"]  # broker client id
    ssnTimeout = config["SSNTimeout"]

    #    TOPIC_COMMANDS = config["TOPIC_COMMANDS"]
    ACCOUNT = config["ACCOUNT"]

    client = mqtt.Client(client_id=MQTT_BROKER_CLIENT_ID)
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish
    client.username_pw_set(MQTT_BROKER_USER, password=MQTT_BROKER_PASS)
    client.connect(MQTT_HOST, MQTT_PORT, 60)

    nTimeIncrement = 0.01
    nTimeout = ssnTimeout
    nRes = 1
    while ((client._state != mqtt.mqtt_cs_connected) and (nTimeout > 0)):
        time.sleep(nTimeIncrement)
        nTimeout -= nTimeIncrement
    if (nTimeout > 0):
        nRes = 0
        # to do: make other checks
    if (nRes):
        tmpMsg = ssnMsg(destObj=destObj, srcObj=srcObj, msgType=msgType, msgID=msgID, msgData=msgData, \
        msgChannel=1, msgSocket=None, msgSerial = None)

        # Send data
        bufToSend = tmpMsg.getSSNPDU()
        print >> sys.stderr, 'sending "%s"' % bufToSend

        #        print >> sys.stderr, 'publish to "%s"' % TOPIC_COMMANDS
        client.publish("/ssn/acc/" + str(ACCOUNT) + "/obj/" + str(destObj) +
                       "/commands",
                       payload=bufToSend,
                       qos=0,
                       retain=False)
    # to do: get response


#        recv_data = sock.recv(TCPBufferSize)
#        amount_received += len(recv_data)
#        print >>sys.stderr, 'received "%s"' % recv_data
    else:
        print >> sys.stderr, 'error connect to broker'
Beispiel #9
0
def main(argv):
    inputfile = ''
    destObj = 0
    srcObj = 3
    msgType = 2
    msgID = None
    msgData = ""
    
    try:
       opts, args = getopt.getopt(argv,"hd:fstiD",["file=","dest=","src=","type=","id=","data="])
    except getopt.GetoptError:
       print 'ssnmqc.py [--file <inputfile> or -D <data string>] --dest <destObj> -src <srcObj> --type <msgType> --id <msgID>'
       sys.exit(2)
    for opt, arg in opts:
       if opt == '-h':
           print 'ssnmqc.py [--file <inputfile> or -D <data string>] --dest <destObj> -src <srcObj> --type <msgType> --id <msgID>'
           sys.exit()
       if opt in ("-f", "--file"):
          inputfile = arg
       if opt in ("-d", "--dest"):
         destObj = int(arg, 10)
       if opt in ("-s", "--src"):
         srcObj = int(arg, 10)
       if opt in ("-t", "--type"):
         msgType = int(arg, 10)
       if opt in ("-i", "--id"):
         msgID = arg
       if opt in ("-D", "--data"):
         msgData = arg
    if (inputfile):
        with open(inputfile) as f:
            msgData = f.read()

#    print "QQQ: " + destObj
#    data = '{"ssn":{"v":1,"obj":10,"cmd":"getdevvals", "data": {"g":1}}}'
    config = {}
    execfile("ssnmqtt.cfg", config) 
#    TCPBufferSize = config["TCPBufferSize"]
    MQTT_HOST = config["MQTT_HOST"]             # mqtt boker host
    MQTT_PORT = config["MQTT_PORT"]             # mqtt boker port 
    MQTT_BROKER_USER = config["MQTT_BROKER_USER"]     # mqtt broker user
    MQTT_BROKER_PASS = config["MQTT_BROKER_PASS"]     # mqtt broker password
    MQTT_BROKER_CLIENT_ID = config["MQTT_BROKER_CLIENT_ID"] # broker client id
    ssnTimeout = config["SSNTimeout"]

#    TOPIC_COMMANDS = config["TOPIC_COMMANDS"]
    ACCOUNT = config["ACCOUNT"]

    client = mqtt.Client(client_id=MQTT_BROKER_CLIENT_ID)
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish
    client.username_pw_set(MQTT_BROKER_USER, password=MQTT_BROKER_PASS)
    client.connect(MQTT_HOST, MQTT_PORT, 60)

    nTimeIncrement = 0.01
    nTimeout = ssnTimeout
    nRes = 1
    while ((client._state != mqtt.mqtt_cs_connected) and (nTimeout > 0)):
        time.sleep(nTimeIncrement)
        nTimeout -= nTimeIncrement
    if (nTimeout > 0):
        nRes = 0
        # to do: make other checks
    if (nRes):
        tmpMsg = ssnMsg(destObj=destObj, srcObj=srcObj, msgType=msgType, msgID=msgID, msgData=msgData, \
        msgChannel=1, msgSocket=None, msgSerial = None)
    
        # Send data
        bufToSend = tmpMsg.getSSNPDU()
        print >> sys.stderr, 'sending "%s"' % bufToSend
        
#        print >> sys.stderr, 'publish to "%s"' % TOPIC_COMMANDS
        client.publish("/ssn/acc/"+str(ACCOUNT)+"/obj/"+str(destObj)+"/commands", payload=bufToSend, qos=0, retain=False)
    # to do: get response

#        recv_data = sock.recv(TCPBufferSize)
#        amount_received += len(recv_data)
#        print >>sys.stderr, 'received "%s"' % recv_data
    else:
        print >> sys.stderr, 'error connect to broker'
Beispiel #10
0
def raw_data_callback(client, userdata, msg):
    global g_tail
    #print(msg.topic+" "+str(msg.payload))
    msg_len = len(msg.payload)
    logger1.debug("raw_data: " + msg.topic + "->")
    logger1.debug(msg.payload)
    #    g_tail = g_tail + msg.payload
    g_tail = msg.payload  # TO DO..
    tail = ""

    while (len(tail) < msg_len):
        msg_len = len(tail)
        tmpMsg = ssnMsg()
        tail, nResult = tmpMsg.processBuffer(g_tail)
        if (nResult):
            logger1.info("LOG raw_data message: srcObj=" + str(tmpMsg.srcObj) +
                         ", destObj=" + str(tmpMsg.destObj))

            if (len(g_tail) > 10000):  # check buffer owerflow
                logger1.warn("SSN packet buffer overflow!")
                g_tail = ""
            else:
                g_tail = tail

            if (tmpMsg.msgType == 6):
                #process LOG message
                #            if (tmpMsg.destObj in serial_if):
                logger1.debug("LOG message, src Obj=" + str(tmpMsg.srcObj))
                try:
                    ssn_data = json.loads(tmpMsg.msgData)
                    for logItem in ssn_data['log']:
                        # publish event into events topic and devices values into its topics:
                        if (len(logItem)):
                            client.publish("/ssn/acc/" + str(ACCOUNT) +
                                           "/obj/" + str(tmpMsg.srcObj) +
                                           "/events",
                                           payload=json.dumps(logItem),
                                           qos=0,
                                           retain=False)
                            client.publish("/ssn/acc/" + str(ACCOUNT) +
                                           "/obj/" + str(tmpMsg.srcObj) +
                                           "/device/" + str(logItem['d']) +
                                           "/" + str(logItem['c']) + "/out",
                                           payload=logItem['v'],
                                           qos=0,
                                           retain=True)
                            client.publish("/ssn/acc/" + str(ACCOUNT) +
                                           "/obj/" + str(tmpMsg.srcObj) +
                                           "/device/" + str(logItem['d']) +
                                           "/" + str(logItem['c']) +
                                           "/devicetime",
                                           payload=logItem['t'],
                                           qos=0,
                                           retain=True)
                except Exception as ex:
                    logger1.error(
                        "Cannot decode JSON object, payload={}: {}".format(
                            tmpMsg.msgData, ex))
            elif (tmpMsg.msgType == 2):
                #process JSON message
                logger1.info("JSON message, src Obj=" + str(tmpMsg.srcObj))
            elif (tmpMsg.msgType == 3):
                #process TELEMETRY message
                logger1.debug("TELEMETRY message, src_Obj=" +
                              str(tmpMsg.srcObj) + " dst_Obj=" +
                              str(tmpMsg.destObj))
                try:
                    #                    logWrite("JSON: "+tmpMsg.msgData, level="d")
                    ssn_data = json.loads(tmpMsg.msgData)
                except Exception as ex:
                    logger1.error(
                        "TELEMETRY. Cannot decode JSON object, payload={}: {}".
                        format(tmpMsg.msgData, ex))
                if (ssn_data['ssn']['ret'] == "getdevvals"):
                    processTelemetry(ssn_data['ssn']['data'], tmpMsg)
            else:
                logger1.debug("skip row data processing")