Pubnub History Api - python-2.7

I am trying to extract the message from my pubnub history, where I wish to compare any change of messages. For the same I am calling pubnub.history in my main callback function (used by pubnub.subscribe) -
pubnub.history(channel=channel, count = 1, callback =_callback,error=_error)
and I define my _callback as:
def _callback(message):
_type = message[0]
_type_ = _type[0]
prevMess = _type_['command']
if prevMess == "..":
flag = 1
elif prevMess == "...":
flag = 4
elif prevMess == "....":
flag = 7
print flag
How can I successfully 'return' the flag value from the _callback() to my callback()? Or in that case return "prevMess" value from _callback() to callback()?

Related

Unable to mqtt_client publish inside a class

I'm trying to use Paho MQTT Client and Multiprocessing to send temperature with defined interval. However, publish command is not working inside class. I've checked self.mqtt_client inside scheduler it has the Client object.
Is there anyone that can address problem for me?
Everything inside class is working except Scheduler.
def scheduler(self, topic, interval):
if interval != 0:
while True:
if topic == "temp":
print("Temperature published " + interval) #It's working.
self.mqtt_client.publish(topic, interval , 0 , False) #There is no error/output about this line
time.sleep(int(interval))
else:
pass
Class:
class Switcher:
config = None
mqtt_client = None
mqtt_connected = False
switches = {}
stages = {}
def __init__(self, config):
self.config = config
for switch_cfg in self.config['switches']:
self.switches[switch_cfg['topic_set']] = Switch(int(switch_cfg['gpio']), switch_cfg['topic_status'], switch_cfg['initial'])
def scheduler(self, topic, interval):
if interval != 0:
while True:
if topic == "temp":
print("Temperature published " + interval) #It's working.
self.mqtt_client.publish(topic, interval , 0 , False) #There is no error/output about this line
time.sleep(int(interval))
else:
pass
def mqtt_connect(self):
if self.mqtt_broker_reachable():
self.verbose('Connecting to ' + self.config['mqtt_host'] + ':' + self.config['mqtt_port'])
self.mqtt_client = mqtt.Client(self.config['mqtt_client_id'])
if 'mqtt_user' in self.config and 'mqtt_password' in self.config:
self.mqtt_client.username_pw_set(self.config['mqtt_user'], self.config['mqtt_password'])
self.mqtt_client.on_connect = self.mqtt_on_connect
self.mqtt_client.on_disconnect = self.mqtt_on_disconnect
self.mqtt_client.on_message = self.mqtt_on_message
try:
self.mqtt_client.connect(self.config['mqtt_host'], int(self.config['mqtt_port']), 10)
for switch_cfg in self.config['switches']:
self.mqtt_client.subscribe(switch_cfg['topic_set'], 0)
self.mqtt_client.loop_forever()
except:
self.error(traceback.format_exc())
self.mqtt_client = None
else:
self.error(self.config['mqtt_host'] + ':' + self.config['mqtt_port'] + ' not reachable!')
def mqtt_on_connect(self, mqtt_client, userdata, flags, rc):
self.mqtt_connected = True
for switch_ios in self.config['switches']:
self.mqtt_client.publish(self.config['station_status'], "available", 0, False)
self.mqtt_client.publish(switch_ios['topic_status'], self.switches[switch_ios['topic_set']].get_state(), 0, False)
temp_interval = 1
temp_process = multiprocessing.Process(target=self.scheduler, args=("temp",str(temp_interval),))
temp_process.start()
self.verbose('...mqtt_connected!')
def mqtt_broker_reachable(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
try:
s.connect((self.config['mqtt_host'], int(self.config['mqtt_port'])))
s.close()
return True
except socket.error:
return False
def start(self):
self.mqtt_connect()
You mqtt_connect function will never return.
self.mqtt_client.loop_forever() Will block until self.mqtt_client.disconnect() is called.
You should probably be using self.mqtt_client.loop_start() which will run the client loop on it's own thread in the background. You can call self.mqtt_client.loop_stop() when you want to shut the client down.

Assert operator to count before and after from various variable

i have codes to get database records, send test data (not shown in below codes),
and count before/after size.
can i do below assertion to do simple math calculation directly using the printIn result?
assert responseListAfter.size() == responseListBefore.size + results
this is the full codes
//count the DB records which State = New
String dbQuery = "SELECT COUNT(*) as count FROM dispenseorders.dispenseorder where status = 'true'"
List results = CustomKeywords.'swisslog.database.getSQLResults'(GlobalVariable.dbConnString , GlobalVariable.dbUsername , GlobalVariable.dbPassword ,GlobalVariable.dbDriver ,dbQuery )
println results
//Before Refresh. count number of records in Kafka Topic A
def TopicBefore = 'A'
def NewMessageBefore = consumeMessageBefore(TopicBefore)
def responseListBefore = new JsonSlurper().parseText(consumeMessageBefore.getResponseText())
def consumeMessageBefore(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_A', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageBefore = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('before Request Refresh: \n' + responseListBefore.size)
WebUI.delay(10)
//after Refresh. count number of records in Kafka Topic A
def TopicAfter = 'A'
def NewMessageAfter = consumeMessageAfter(TopicAfter)
def responseListAfter = new JsonSlurper().parseText(consumeMessageAfter.getResponseText())
def consumeMessageAfter(def topic) {
WS.sendRequest(findTestObject('Object Repository/Kafka/subscribe_to_topic_for_DR', [('topic_name') : topic, ('KafkaRestName') : GlobalVariable.KafkaRestName
, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
return consumeMessageAfter = WS.sendRequestAndVerify(findTestObject('Object Repository/Kafka/consume_message_from_topic_for_DR',
[('KafkaRestName') : GlobalVariable.KafkaRestName, ('KafkaRestPort') : GlobalVariable.KafkaRestPort]))
}
println('after Request Refresh: \n' + responseListAfter.size)
//check total messages. After Refresh count = Before Refresh count + DB records
assert responseListAfter.size() == responseListBefore.size + results
results is a list, and you need a list size (int) to add it to other ints:
assert responseListAfter.size() == responseListBefore.size() + results.size()

Dropbox script/Do something when download done

Maybe I missed something when I looked over the Dropbox uploader https://github.com/andreafabrizi/Dropbox-Uploader . I'm creating a python script that uploads files from a USB plugged into a RPi, but need to have it so when the upload is complete, a boolean changes to false. Is there a way to detect this? Code is commented where I want this to occur.
import pygame
from pygame.locals import *
from subprocess import call
uploadSym = pygame.image.load('uploadsymbol.png')
loadingSym = pygame.image.load('loading.png')
uploadSym = pygame.transform.scale(uploadSym, (250,300))
loadingSym = pygame.transform.scale(loadingSym, (300,300))
rect = uploadSym.get_rect()
rect = rect.move((200,60))
rect = loadingSym.get_rect()
rect = rect.move((200,60))
firstSlide = False
def toggle_fullscreen():
screen = pygame.display.get_surface()
tmp = screen.convert()
caption = pygame.display.get_caption()
cursor = pygame.mouse.get_cursor()
w,h = screen.get_width(),screen.get_height()
flags = screen.get_flags()
bits = screen.get_bitsize()
pygame.display.quit()
pygame.display.init()
screen = pygame.display.set_mode((w,h),flags^FULLSCREEN,bits)
screen.blit(tmp,(0,0))
pygame.display.set_caption(*caption)
pygame.key.set_mods(0)
pygame.mouse.set_cursor( *cursor )
return screen
if __name__ == '__main__':
SW,SH = 640,480
screen = pygame.display.set_mode((SW,SH),pygame.NOFRAME)
pygame.display.set_caption('Uploader')
_quit = False
while not _quit:
for e in pygame.event.get():
if (e.type is KEYDOWN and e.key == K_RETURN and (e.mod&(KMOD_LALT|KMOD_RALT)) != 0):
toggle_fullscreen()
elif e.type is QUIT:
_quit = True
elif e.type is KEYDOWN and e.key == K_ESCAPE:
_quit = True
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
screen = pygame.display.get_surface()
screen.fill([255, 255, 255])
#Click within the given area and upload begins
if 450 > mouse[0] > 250 and 360 > mouse[1] > 60 and click[0] == 1:
firstSlide = True
#T/F keeps png up for new slide
elif firstSlide == True:
loadRot = pygame.transform.rotate(loadingSym,0)
screen.blit(loadRot, rect)
#Upload test file to dropbox
Upload = "/home/pi/Uploader/Dropbox-Uploader/dropbox_uploader.sh upload loading.png /"
call ([Upload], shell=True)
#Here I need an if statement that says, when upload done firstSlide = False
#{
#
#
#}
else:
screen.blit(uploadSym, rect)
pygame.display.update()
The subprocess.call() function returns the exit-code of the command. So the call() will (should) return 0 on success, and non-zero on error.
So:
uploaded_ok = ( subprocess.call( Upload, shell=True) == 0 )
Will give you a True/False success.
NOTE: Link to 2.7 doco, since OP tagged question Python2.7

Check for values return from EnumValue

I'm reading values from registry using EnumValue. I want to check the existence of all values from the registry and pop up error message if any value is empty.
key = OpenKey(HKEY_CURRENT_USER, r'Software\myapp\path', 0,KEY_READ)
for i in range(0,6):
n,v,t = EnumValue(key,i)
value = str(v).split(',')
if (value[0:] == ''):
dlg = wx.MessageDialog(None,'value is empty','Alert',wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
value returns
['1000']
['10MS/s']
['Edge']
['500']
['']
['Rise']
How can i have all the values return from EnumValue in a single list so that i can iterate this list and find if any value is empty?
Tried ','.join([value]) but didn't work!
I found answer myself
import wx
from _winreg import *
empty = False
key = OpenKey(HKEY_CURRENT_USER, r'Software\myapp\path', 0,KEY_READ)
for i in range(0,6):
n,v,t = EnumValue(key,i)
value = str(v)
if value == "":
empty = True
break
if empty:
dlg = wx.MessageDialog(None,'value is empty','Alert',wx.OK|wx.ICON_ERROR)
dlg.ShowModal()

Unicode and UTF-8 in python to generate csv file

I'm trying to write some variableas in a csv file.
Documentation (https://docs.python.org/2/library/csv.html) say the all input must be UTF-8 or ASCII, but I don't know how to set the encode ( I already tried .decode('utf-8'))
part of the code:
def get_events():
global SEVERITY, SEVERITY
get_host()
for HID,HNAME in zip(HOSTID,HOSTNAME):
EVENT = zapi.event.get(time_from=DATE_FROM,
time_till=DATE_TILL,
output='extend',
source='0',
hostids=HID,
select_acknowledges='extend',
)
for t in EVENT:
TRIGGERID = t['objectid']
TRIGGER = zapi.trigger.get(output='extend',
triggerids=TRIGGERID,
expandDescription='true',
)
for T in TRIGGER:
TRIGGER_D = T['description'].encode('utf-8')
SEVERITY = T['priority']
if int(SEVERITY) < 3 or TRIGGER_D.decode('utf-8') == 'Zabbix agent on %s is unreachable for 8 minutes' % HNAME or TRIGGER_D.decode('utf-8') == '%s jmx is not reachable' % HNAME:
continue
NS = t['ns']
HOUR = t['clock']
if t.get('value') == "0":
STATUS = "OK"
elif t.get('value')== "1":
STATUS = "PROBLEM"
else:
STATUS = "UNKNOWN"
if t['acknowledged'] == "1":
LISTA_DIC = t['acknowledges'][0]
USER = LISTA_DIC['alias']
MESSAGE = LISTA_DIC["message"]
else:
MESSAGE = ""
USER = ""
with open(FILE_OUT, 'wb') as FILE:
FILE = csv.writer(FILE,delimiter=';')
FILE.writerow((HNAME,STATUS,HOUR,NS,TRIGGER_D, SEVERITY,MESSAGE,USER)
I'm get the error
“UnicodeDecodeError: 'ascii' codec can't decode byte”
Another thing: How add a newline in
FILE.writerow((HNAME,STATUS,HOUR,NS,TRIGGER_D, SEVERITY,MESSAGE,USER))
..MESSAGE,USER "\n")) doesn't work
Can solve the problem change the encode to latin-1
FILE.writerow((HNAME,STATUS,HOUR,NS,TRIGGER_D.encode('latin-1'), SEVERITY,MESSAGE.encode('latin-1'),USER)