import json
import redis
import pymssql
import pymysql
import pymysql.cursors
import subprocess as sp
import time
import uuid
import threading
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import os
import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont
class TPyUtils:
def __init__(self):
self.objId = self.getUuid()
self.as_dict =True
self.charset ='utf8'
def startThread(self , function , funArgs ):
res=None
try:
t = threading.Thread(target=function, args = funArgs , daemon=True)
t.start()
res = t
except Exception as er:
pass
return res
def getRedis(self , host , port , db , uid , pwd ):
res=None
try:
res = redis.Redis(
host=host,
port=port,
db=db,
user=uid,
password=pwd,
decode_responses=True
)
except Exception as er:
print('TPyUtils.getRedis' ,'connect redis faild.', er)
return res
'''
参数 %(psName)s , %(psName)d
'''
def querySql(self , host , port , db , uid , pwd , sql , parameters=None):
res = []
try:
with pymssql.connect(server=host, port=port, user=uid, password=pwd, database=db, as_dict=self.as_dict, charset=self.charset) as conn:
with conn.cursor() as cursor:
if( parameters==None):
cursor.execute(sql)
else:
cursor.execute(sql, parameters)
res = list(cursor.fetchall())
except Exception as e:
print('TPyUtils.queryMsSql' ,"Mssql query error", e)
return res
def queryMySql(self , host , port , db , uid , pwd , sql , parameters=None):
res = []
try:
#with pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8') as conn:
conn = pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8' )
cursor = conn.cursor( pymysql.cursors.DictCursor)
if (parameters == None):
cursor.execute(sql)
else:
cursor.execute(sql, parameters)
cursor.close()
conn.close()
res = list(cursor.fetchall())
except Exception as e:
print('TPyUtils.queryMySql' ,"Mysql query error", e)
return res
def executeSql(self , host , port , db , uid , pwd , sql , parameters=None):
res=0
try:
with pymssql.connect(server=host, port=port, user=uid, password=pwd, database=db, as_dict=self.as_dict, charset=self.charset) as conn:
with conn.cursor() as cursor:
if( parameters==None):
cursor.execute(sql)
else:
cursor.execute(sql, parameters)
conn.commit()
res = 1
except Exception as er:
print('TPyUtils.executeMsSql' ,"Mssql query error", er)
return res
def executeMySql(self , host , port , db , uid , pwd , sql , parameters=None):
res=0
try:
#with pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8') as conn:
conn = pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8' )
cursor = conn.cursor( )
if (parameters == None):
cursor.execute(sql)
else:
cursor.execute(sql, parameters)
conn.commit()
cursor.close()
conn.close()
res = 1
except Exception as e:
print('TPyUtils.queryMySql' ,"Mysql query error", e)
return res
def executeBatchMySql(self , host , port , db , uid , pwd , sqlList):
res=0
try:
#with pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8') as conn:
conn = pymysql.connect(host=host, port=port, user=uid, passwd=pwd, db=db, charset='utf8' )
cursor = conn.cursor( )
for i in range(len(sqlList)):
sql = sqlList[i]
cursor.execute(sql)
conn.commit()
cursor.close()
conn.close()
res = 1
except Exception as e:
print('TPyUtils.queryMySql' ,"Mysql query error", e)
return res
def publishMqtt(self , host , port , uid , pwd , topic , content):
res=None
try:
client_id = str(time.time())
aAuth = {
'username': uid,
'password': pwd
}
publish.single( topic, content, qos=0, hostname= host, port=port , client_id=client_id, auth=aAuth )
except Exception as er:
print('TPyUtils.publishMqtt' ,"publish message error", er)
return res
def callCommandLine(self , commandStr ):
res=0
try:
print(commandStr)
cmd = sp.Popen(commandStr, stderr=sp.PIPE, stdout=sp.PIPE, universal_newlines=True, shell=True)
err = None
while err == None:
out, err = cmd.communicate()
time.sleep(1)
if( cmd.returncode ==0):
res = 1
else:
print(err)
except Exception as er:
print('TPyUtils.callCommandLine' ,"call command error.", er)
return res
def drawText(self, srcFn , dstFn , contents , textColor=(0, 255, 0), textSize=20):
res=0
try:
if( os.path.exists(srcFn)):
img = cv2.imread(dstFn)
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
draw = ImageDraw.Draw(img)
fontText = ImageFont.truetype("font/simsun.ttc", textSize, encoding="utf-8")
for textItem in contents :
left = textItem['left']
top = textItem['top']
text = textItem['text']
draw.text((left, top), text, textColor, font=fontText)
img = cv2.cvtColor(numpy.asarray(img), cv2.COLOR_RGB2BGR)
cv2.imwrite(dstFn, img)
res = 1
img = None
except Exception as er:
print('TPyUtils.drawText' ,"call command error.", er)
return res
def getUuid(self):
return str(uuid.uuid4()).replace('-', '')
def log(self , msg , err):
print(msg , err)
class TPyMqtt:
def __init__(self):
self.host = "media.hhdata.cn"
self.port = 52082
self.uid ="user"
self.pwd = "userpwd"
self.autoSubscribTopic=""
self.customEvents ={
"onConnected":None ,
"onDisconnected":None ,
"onRecMsg":None
}
self.ClientId = ""
self.Client = None
def doOnConnect(self, client, userdata, flags, rc):
try:
aTopic = self.autoSubscribTopic
if ((aTopic != None) and (aTopic != "")):
client.subscribe(aTopic, 0)
if (self.customEvents['onConnected']!= None):
self.customEvents['onConnected'](client, userdata, flags, rc)
except Exception as e:
print("TPyMqtt.OnConnect error", e)
def doOnDisConnect(self, client, userdata, flags, rc):
try:
if (self.customEvents['onDisonnected']!= None):
self.customEvents['onDisonnected'](client, userdata, flags, rc)
except Exception as er:
print("TPyMqtt.OnDisconnect error", er)
def doOnRecMsg(self, client, userdata, msg):
try:
if (self.customEvents['onRecMsg']!= None):
self.customEvents['onRecMsg'](client, userdata, msg)
except Exception as er:
print("TPyMqtt.onRecMsg error", er)
def connect(self , host , port , uid , pwd , autoSubscribTopic , onConnected , onDisConnected , onRecMsg):
try:
self.host = host
self.port = port
self.uid = uid
self.pwd = pwd
self.autoSubscribTopic = autoSubscribTopic
self.customEvents['onConnected'] = onConnected
self.customEvents['onDisconnected'] = onDisConnected
self.customEvents['onRecMsg'] = onRecMsg
self.ClientId = "pyClientId_"+str(uuid.uuid4()).replace('-', '')
self.Client = mqtt.Client(self.ClientId)
self.Client.on_connect = self.doOnConnect
self.Client.on_disconnect = self.doOnDisConnect
self.Client.on_message = self.doOnRecMsg
self.Client.connect(self.host , self.port )
self.Client.loop_forever()
except Exception as er:
print("TPyMqtt.connect error", er)
pyUtils = TPyUtils()
跨平台数据库与MQTT通信工具包
2238

被折叠的 条评论
为什么被折叠?



