import binascii
import threading
import paho.mqtt.client as mqtt
import time
import json
import base64
import struct
import types
import syslog
import os
import sys
from Queue import Queue

#  {"identifier":"final_result","sn":"Oy9thUdy","mi":50961098,"timestamp":1618114489}
def protocol_encode(obj):
    id = obj['identifier']

    if (id == "conn"):
        obj['UUID'] = "FFF2"
        obj['data'] = "CC80020301010001"
    elif (id == "start"):
        obj['UUID'] = "FFF2"
        obj['data'] = "CC80020301020002"
    else:
        obj = None
        
    return obj

def protocol_decode(data, sn, gw_sn, port):
    pre,ver,len,data_type,sub_type = struct.unpack(">HBBBB", data[:6])

    if pre != 0xAA80:
        return None
    obj = {}
    if data_type == 1:
        if sub_type == 5:
            _,PH,_,_,PL,_ = struct.unpack("BBBBBB", data[6:12])
            p = PH * 256 + PH^PL
            obj['blood_pressure'] = p
            obj['identifier'] = "blood_pressure"
        elif sub_type == 6:
            c1,c2,c3,c4,c5,c6 = struct.unpack("BBBBBB", data[13:19])
            obj['systolic'] = c1 * 256 + c2
            obj['diastolic'] = c3 * 256 + c4
            obj['PUL'] = c5 * 256 + c6
            obj['identifier'] = "final_result"
    
    obj_str = json.dumps(obj)
    send_data = {}
    send_data["sn"] = sn
    send_data["identifier"] = obj["identifier"]
    send_data["time"] = int(time.time())
    send_data["mi"] = 0
    send_data["port"] = port
    send_data["tag_node"] = obj_str
    
    send_data["data_type"] = 2
    send_json = json.dumps(send_data)
    publish_topic = "ipc/" + gw_sn + "/" + port + "/device/" + sn + "/data/service/" + obj["identifier"]
    
    topic_payload = {}
    topic_payload["topic"] = publish_topic
    topic_payload["payload"] = send_json

    return topic_payload

