#!/usr/bin/env python3 ## # Simulateur d'alarme en Python sur Raspberry Pi # Utilisation d'une LED # et d'un capteur PIR sur port GPIO # Utilisation d'un modem GSM sur port USB avec gammu import RPi.GPIO as GPIO import time import gammu # Préparation du modem pour envoi de SMS sm = gammu.StateMachine() sm.ReadConfig() sm.Init() # Préparation du message à envoyer message = { 'Text': 'Mouvement détecté', 'SMSC': { 'Location': 1 }, 'Number': '0612345678' } # Configuration des ports GPIO du Raspberry Pi GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) PIR = 7
def sms_check(self): """Control and processing SMS""" data = get_sms_options() # Load data from json file tel1 = data["tel1"] tel2 = data["tel2"] comm1 = data["txt1"] comm2 = data["txt2"] comm3 = data["txt3"] comm4 = data["txt4"] comm5 = data["txt5"] comm6 = data["txt6"] sm = gammu.StateMachine() sm.ReadConfig() try: sm.Init() print("Checking SMS...") except: print("Error: SMS modem fault") status = sm.GetSMSStatus() remain = status["SIMUsed"] + status["PhoneUsed"] + status["TemplatesUsed"] sms = [] start = True while remain > 0: if start: cursms = sm.GetNextSMS(Start=True, Folder=0) start = False else: cursms = sm.GetNextSMS(Location=cursms[0]["Location"], Folder=0) remain = remain - len(cursms) sms.append(cursms) data = gammu.LinkSMS(sms) for x in data: v = gammu.DecodeSMS(x) m = x[0] print("%-15s: %s" % ("Sender", m["Number"])) print("%-15s: %s" % ("Date", str(m["DateTime"]))) print("%-15s: %s" % ("State", m["State"])) print("%-15s: %s" % ("SMS command", m["Text"])) if (m["Number"] == tel1) or (m["Number"] == tel2): # If telephone is admin 1 or admin 2 self.add_status( time.strftime("%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) + " SMS from admin") if m["State"] == "UnRead": # If SMS is unread if ( m["Text"] == comm1 ): # If command = comm1 (info - send SMS to admin phone1 and phone2) self.add_status("Command " + comm1 + " is processed") if gv.lrun[1] == 98: pgr = "Run-once" elif gv.lrun[1] == 99: pgr = "Manual" else: pgr = str(gv.lrun[1]) start = time.gmtime(gv.now - gv.lrun[2]) if pgr != "0": logline = ( " {program: " + pgr + ",station: " + str(gv.lrun[0]) + ",duration: " + timestr(gv.lrun[2]) + ",start: " + time.strftime("%H:%M:%S - %Y-%m-%d", start) + "}") else: logline = " Last program none" revision = " Rev: " + gv.ver_date datastr = ("On " + time.strftime( "%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) + ". Run time: " + uptime() + " IP: " + get_ip() + logline + revision) message = { "Text": datastr, "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm1 + " was processed and confirmation was sent as SMS to: " + m["Number"]) self.add_status("SMS text: " + datastr) sm.DeleteSMS(m["Folder"], m["Location"]) # SMS deleted self.add_status("Received SMS was deleted") elif m["Text"] == comm2: # If command = comm2 (stop - system SIP off) self.add_status("Command " + comm2 + " is processed") gv.sd["en"] = 0 # disable system SIP jsave(gv.sd, "sd") # save en = 0 message = { "Text": "Command: " + comm2 + " was processed", "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm2 + " was processed and confirmation was sent as SMS to: " + m["Number"]) sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status("Received SMS was deleted") elif m["Text"] == comm3: # If command = comm3 (start - system SIP on) self.add_status("Command " + comm3 + " is processed") gv.sd["en"] = 1 # enable system SIP jsave(gv.sd, "sd") # save en = 1 message = { "Text": "Command: " + comm3 + " was processed", "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm3 + " was processed and confirmation was sent as SMS to: " + m["Number"]) sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status("Received SMS was deleted") elif m["Text"] == comm4: # If command = comm4 (reboot system) self.add_status("Command " + comm4 + " is processed") message = { "Text": "Command: " + comm4 + " was processed", "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm4 + " was processed and confirmation was sent as SMS to: " + m["Number"]) sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status( "Received SMS was deleted and system is now reboot") self._sleep(10) reboot() # restart linux system elif m["Text"] == comm5: # If command = comm5 (poweroff system) self.add_status("Command " + comm5 + " is processed") message = { "Text": "Command: " + comm5 + " was processed", "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm5 + " was processed and confirmation was sent as SMS to: " + m["Number"]) sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status( "Received SMS was deleted and system is now poweroff") self._sleep(10) poweroff() # poweroff linux system elif m["Text"] == comm6: # If command = comm6 (update SIP system) self.add_status("Command " + comm6 + " is processed") message = { "Text": "Command: " + comm6 + " was processed", "SMSC": { "Location": 1 }, "Number": m["Number"], } sm.SendSMS(message) self.add_status( "Command: " + comm6 + " was processed and confirmation was sent as SMS to: " + m["Number"]) try: from plugins.system_update import perform_update perform_update() self.add_status( "Received SMS was deleted, update was performed and program will restart" ) except ImportError: self.add_status( "Received SMS was deleted, but could not perform update" ) sm.DeleteSMS(m["Folder"], m["Location"]) else: # If SMS command is not defined sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status("Received command " + m["Text"] + " is not defined!") else: # If SMS was read sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status("Received SMS was deleted - SMS was read") else: # If telephone number is not admin 1 or admin 2 phone number sm.DeleteSMS(m["Folder"], m["Location"]) self.add_status( "Received SMS was deleted - SMS was not from admin")
def sms_check(self): """Control and processing SMS""" data = get_sms_options() # Load data from json file tel1 = data['tel1'] tel2 = data['tel2'] comm1 = data['txt1'] comm2 = data['txt2'] comm3 = data['txt3'] comm4 = data['txt4'] comm5 = data['txt5'] comm6 = data['txt6'] sm = gammu.StateMachine() sm.ReadConfig() try: sm.Init() print "Checking SMS..." except: print "Error: SMS modem fault" status = sm.GetSMSStatus() remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed'] sms = [] start = True while remain > 0: if start: cursms = sm.GetNextSMS(Start=True, Folder=0) start = False else: cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0) remain = remain - len(cursms) sms.append(cursms) data = gammu.LinkSMS(sms) for x in data: v = gammu.DecodeSMS(x) m = x[0] print '%-15s: %s' % ('Sender', m['Number']) print '%-15s: %s' % ('Date', str(m['DateTime'])) print '%-15s: %s' % ('State', m['State']) print '%-15s: %s' % ('SMS command', m['Text']) if (m['Number'] == tel1) or (m['Number'] == tel2): # If telephone is admin 1 or admin 2 self.add_status(time.strftime("%d.%m.%Y at %H:%M:%S", time.localtime(time.time())) + ' SMS from admin') if m['State'] == "UnRead": # If SMS is unread if m['Text'] == comm1: # If command = comm1 (info - send SMS to admin phone1 and phone2) self.add_status('Command ' + comm1 + ' is processed') if gv.lrun[1] == 98: pgr = 'Run-once' elif gv.lrun[1] == 99: pgr = 'Manual' else: pgr = str(gv.lrun[1]) start = time.gmtime(gv.now - gv.lrun[2]) if pgr != '0': logline = ' {program: ' + pgr + ',station: ' + str(gv.lrun[0]) + ',duration: ' + timestr( gv.lrun[2]) + ',start: ' + time.strftime("%H:%M:%S - %Y-%m-%d", start) + '}' else: logline = ' Last program none' revision = ' Rev: ' + gv.ver_date datastr = ('On ' + time.strftime("%d.%m.%Y at %H:%M:%S", time.localtime( time.time())) + '. Run time: ' + uptime() + ' IP: ' + get_ip() + logline + revision) message = { 'Text': datastr, 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm1 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) self.add_status('SMS text: ' + datastr) sm.DeleteSMS(m['Folder'], m['Location']) # SMS deleted self.add_status('Received SMS was deleted') elif m['Text'] == comm2: # If command = comm2 (stop - system SIP off) self.add_status('Command ' + comm2 + ' is processed') gv.sd['en'] = 0 # disable system SIP jsave(gv.sd, 'sd') # save en = 0 message = { 'Text': 'Command: ' + comm2 + ' was processed', 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm2 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted') elif m['Text'] == comm3: # If command = comm3 (start - system SIP on) self.add_status('Command ' + comm3 + ' is processed') gv.sd['en'] = 1 # enable system SIP jsave(gv.sd, 'sd') # save en = 1 message = { 'Text': 'Command: ' + comm3 + ' was processed', 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm3 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted') elif m['Text'] == comm4: # If command = comm4 (reboot system) self.add_status('Command ' + comm4 + ' is processed') message = { 'Text': 'Command: ' + comm4 + ' was processed', 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm4 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted and system is now reboot') self._sleep(10) reboot() # restart linux system elif m['Text'] == comm5: # If command = comm5 (poweroff system) self.add_status('Command ' + comm5 + ' is processed') message = { 'Text': 'Command: ' + comm5 + ' was processed', 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm5 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted and system is now poweroff') self._sleep(10) poweroff() # poweroff linux system elif m['Text'] == comm6: # If command = comm6 (update SIP system) self.add_status('Command ' + comm6 + ' is processed') message = { 'Text': 'Command: ' + comm6 + ' was processed', 'SMSC': {'Location': 1}, 'Number': m['Number'], } sm.SendSMS(message) self.add_status( 'Command: ' + comm6 + ' was processed and confirmation was sent as SMS to: ' + m['Number']) try: from plugins.system_update import perform_update perform_update() self.add_status('Received SMS was deleted, update was performed and program will restart') except ImportError: self.add_status('Received SMS was deleted, but could not perform update') sm.DeleteSMS(m['Folder'], m['Location']) else: # If SMS command is not defined sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received command ' + m['Text'] + ' is not defined!') else: # If SMS was read sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted - SMS was read') else: # If telephone number is not admin 1 or admin 2 phone number sm.DeleteSMS(m['Folder'], m['Location']) self.add_status('Received SMS was deleted - SMS was not from admin')
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # from __future__ import print_function import gammu import sys state_machine = gammu.StateMachine() if len(sys.argv) >= 2: state_machine.ReadConfig(Filename=sys.argv[1]) del sys.argv[1] else: state_machine.ReadConfig() state_machine.Init() if len(sys.argv) != 2: print('Usage: setdiverts.py NUMBER') sys.exit(1) state_machine.SetCallDivert('AllTypes', 'All', sys.argv[1]) diverts = state_machine.GetCallDivert()
def get_statemachine(self): state_machine = gammu.StateMachine() state_machine.ReadConfig(Filename=self.config_name) state_machine.Init() self._state_machine = state_machine return state_machine
def main(): parser = argparse.ArgumentParser(usage="usage: %(prog)s [options]") parser.add_argument("-c", "--config", action="store", type=str, dest="config", default=None, help="Config file path") parser.add_argument("-f", "--folder", action="store", type=str, dest="folder", default=None, help="Folder to be used for testing") parser.add_argument("-t", "--test-file", action="store", type=str, dest="testfile", default="./data/cgi.jpg", help="Local file to be used for testing") args = parser.parse_args() if args.folder is None: print("You have to select folder where testing will be done!") print("And even better, you should read the script before you run it.") sys.exit(1) if not os.path.exists(args.testfile): print("You have to select file which will be used for testing!") sys.exit(1) state_machine = gammu.StateMachine() if args.config is not None: state_machine.ReadConfig(Filename=args.config) else: state_machine.ReadConfig() state_machine.Init() # Check GetFileSystemStatus print("Expection: Info about filesystem usage") try: fs_info = state_machine.GetFileSystemStatus() fs_info["Total"] = fs_info["Free"] + fs_info["Used"] print("Used: {Used:d}, Free: {Free:d}, Total: {Total:d}".format( **fs_info)) except gammu.ERR_NOTSUPPORTED: print("You will have to live without this knowledge") # Check DeleteFile print("\n\nExpection: Deleting cgi.jpg from memorycard") try: state_machine.DeleteFile(unicode(args.folder + "/cgi.jpg")) except gammu.ERR_FILENOTEXIST: print("Oh well - we copy it now ;-) (You SHOULD read this)") # Check AddFilePart print("\n\nExpection: Put cgi.jpg onto Memorycard on phone") file_handle = open(args.testfile, "rb") file_stat = os.stat(args.testfile) ttime = datetime.datetime.fromtimestamp(file_stat[8]) file_f = { "ID_FullName": args.folder, "Name": u"cgi.jpg", "Modified": ttime, "Folder": 0, "Level": 1, "Used": file_stat[6], "Buffer": file_handle.read(), "Type": "Other", "Protected": 0, "ReadOnly": 0, "Hidden": 0, "System": 0, "Handle": 0, "Pos": 0, "Finished": 0 } while not file_f["Finished"]: file_f = state_machine.AddFilePart(file_f) # Check GetFilePart print( "\n\nExpection: Get cgi.jpg from memorycard and write it as test.jpg") with open('./test.jpg', 'wb') as handle: file_f = {"ID_FullName": args.folder + "/cgi.jpg", "Finished": 0} while not file_f["Finished"]: file_f = state_machine.GetFilePart(file_f) handle.write(file_f["Buffer"]) handle.flush() # Check correct transfer print("\n\nExpection: test.jpg and cgi.jpg to be the same") f1 = open(args.testfile, "rb") f2 = open("./test.jpg", "rb") if f1.read() == f2.read(): print("Same files") else: print("Files differ!") os.remove("./test.jpg") # Check GetNextRootFolder print("\n\nExpection: Root Folder List") try: file_obj = state_machine.GetNextRootFolder(u"") while 1: print(file_obj["ID_FullName"] + " - " + file_obj["Name"]) try: file_obj = state_machine.GetNextRootFolder( file_obj["ID_FullName"]) except gammu.ERR_EMPTY: break except gammu.ERR_NOTSUPPORTED: print("Not supported...") # Check GetNextFileFolder print("\n\nExpection: Info for a file of the phone (cgi.jpg)") file_f = state_machine.GetNextFileFolder(1) while 1: if file_f["Name"] != "cgi.jpg": file_f = state_machine.GetNextFileFolder(0) else: attribute = "" if file_f["Protected"]: attribute = attribute + "P" if file_f["ReadOnly"]: attribute = attribute + "R" if file_f["Hidden"]: attribute = attribute + "H" if file_f["System"]: attribute = attribute + "S" print(("ID: " + file_f["ID_FullName"] + "\n" + "Name: " + file_f["Name"] + "\n" + "Folder: " + str(file_f["Folder"]) + "\n" + "Used: " + str(file_f["Used"]) + "\n" + "Modified: " + file_f["Modified"].strftime("%x %X") + "\n" + "Type: " + file_f["Type"] + "\n" + "Level: " + str(file_f["Level"]) + "\n" + "Attribute: " + attribute)) break # Check SetFileAttributes # Protected is spared, as my mobile nokia 6230i says it's unsupported print("\n\nExpection: Modifying attributes " "(readonly=1, protected=0, system=1, hidden=1)") state_machine.SetFileAttributes(unicode(args.folder + "/cgi.jpg"), 1, 0, 1, 1) # Check GetFolderListing print("\n\nExpection: Listing of cgi.jpg's properties") file_f = state_machine.GetFolderListing(unicode(args.folder), 1) while 1: if file_f["Name"] != "cgi.jpg": file_f = state_machine.GetFolderListing(unicode(args.folder), 0) else: attribute = "" if file_f["Protected"]: attribute = attribute + "P" if file_f["ReadOnly"]: attribute = attribute + "R" if file_f["Hidden"]: attribute = attribute + "H" if file_f["System"]: attribute = attribute + "S" print(("ID: " + file_f["ID_FullName"] + "\n" + "Name: " + file_f["Name"] + "\n" + "Folder: " + str(file_f["Folder"]) + "\n" + "Used: " + str(file_f["Used"]) + "\n" + "Modified: " + file_f["Modified"].strftime("%x %X") + "\n" + "Type: " + file_f["Type"] + "\n" + "Level: " + str(file_f["Level"]) + "\n" + "Attribute: " + attribute)) break # Check DeleteFile print("\n\nExpection: Deletion of cgi.jpg from memorycard") try: state_machine.DeleteFile(unicode(args.folder + "cgi.jpg")) print("Deleted") except gammu.ERR_FILENOTEXIST: print("Something is wrong ...") # Check AddFolder print("\n\nExpection: Creation of a folder on the memorycard \"42alpha\"") file_f = state_machine.AddFolder(unicode(args.folder), u"42alpha") # Check GetFolderListing again *wired* print("\n\nExpection: Print properties of newly created folder") file_f = state_machine.GetFolderListing(unicode(args.folder), 1) while 1: if file_f["Name"] != "42alpha": file_f = state_machine.GetFolderListing(unicode(args.folder), 0) else: attribute = "" if file_f["Protected"]: attribute = attribute + "P" if file_f["ReadOnly"]: attribute = attribute + "R" if file_f["Hidden"]: attribute = attribute + "H" if file_f["System"]: attribute = attribute + "S" print(("ID: " + file_f["ID_FullName"] + "\n" + "Name: " + file_f["Name"] + "\n" + "Folder: " + str(file_f["Folder"]) + "\n" + "Used: " + str(file_f["Used"]) + "\n" + "Modified: " + file_f["Modified"].strftime("%x %X") + "\n" + "Type: " + file_f["Type"] + "\n" + "Level: " + str(file_f["Level"]) + "\n" + "Attribute: " + attribute)) break # Check DeleteFolder print("\n\nExpection: Deletion of previously created folder \"42alpha\"") state_machine.DeleteFolder(unicode(args.folder + "/42alpha"))
def __init__(self): self.sm = gammu.StateMachine() self.sm.ReadConfig() self.sm.Init() self.tasklist = [] self.__read_entries()
def run_action(self, option, text): conf = self.conf if option[0] == 'H': channel = int(option[1:]) GPIO.output(channel, 1) elif option[0] == 'L': channel = int(option[1:]) GPIO.output(channel, 0) elif option == 'ACT1': try: wait = float(text) time.sleep(wait) except Exception,e: print 'ERROR wait action: '+str(e) elif option == 'ACT2': if text: try: text = text.split(' ') subprocess.Popen(text) except Exception,e: print 'ERROR command action: '+str(e) elif option == 'ACT3': subprocess.Popen(['sudo', 'reboot']) elif option == 'ACT4': subprocess.Popen(['sudo', 'shutdown', '-h', 'now']) elif option == 'ACT5': subprocess.Popen(['pkill', '-9', 'kplex']) elif option == 'ACT6': subprocess.call(['pkill', '-9', 'kplex']) subprocess.Popen('kplex') elif option == 'ACT7': subprocess.Popen(['startup', 'stop']) elif option == 'ACT8': subprocess.Popen(['startup', 'restart']) elif option == 'ACT9': subprocess.Popen(['sudo', 'python', self.currentpath +'/wifi_server.py', '0']) conf.set('WIFI', 'enable', '0') elif option == 'ACT10': subprocess.Popen(['sudo', 'python', self.currentpath+'/wifi_server.py', '1']) conf.set('WIFI', 'enable', '1') #elif option == 'ACT11': #elif option == 'ACT12': elif option == 'ACT13': now = time.strftime("%H:%M:%S") tweetStr = now + ' ' + text apiKey = conf.get('TWITTER', 'apiKey') apiSecret = conf.get('TWITTER', 'apiSecret') accessToken = conf.get('TWITTER', 'accessToken') accessTokenSecret = conf.get('TWITTER', 'accessTokenSecret') if len(tweetStr) > 140: tweetStr = tweetStr[0:140] try: msg = TwitterBot(apiKey, apiSecret, accessToken, accessTokenSecret) msg.send(tweetStr) except Exception,e: print 'ERROR Twitter action: '+str(e) elif option == 'ACT14': subject = text body = '' for i in self.SK.list_SK: body += i[1]+': '+str(i[2])+_('\nsource: ')+i[0]+_('\ntimestamp: ')+i[7]+'\n\n' GMAIL_USERNAME = conf.get('GMAIL', 'gmail') GMAIL_PASSWORD = conf.get('GMAIL', 'password') recipient = conf.get('GMAIL', 'recipient') if not body: body = time.strftime("%H:%M:%S") + ' ' + subject try: msg = GmailBot(GMAIL_USERNAME, GMAIL_PASSWORD, recipient) msg.send(subject, body) except Exception,e: print 'ERROR gmail action: '+str(e) elif option == 'ACT15': subprocess.Popen(['mpg123', '-q', text]) elif option == 'ACT16': subprocess.Popen(['pkill', '-9', 'mpg123']) elif option == 'ACT17': subprocess.Popen(['python', self.currentpath + '/message.py', text, conf.get('GENERAL', 'lang')]) elif option == 'ACT18': subprocess.Popen(['pkill', '-f', 'message.py']) elif option == 'ACT19': subprocess.Popen(['python', self.currentpath+'/ctrl_actions.py', '1']) elif option == 'ACT20': subprocess.Popen(['python', self.currentpath + '/ctrl_actions.py', '0']) elif option == 'ACT21': try: sm = gammu.StateMachine() sm.ReadConfig() sm.Init() message = { 'Text': text, 'SMSC': {'Location': 1}, 'Number': conf.get('SMS', 'phone'), } sm.SendSMS(message) except Exception,e: print 'ERROR SMS action: '+str(e) elif option == 'ACT22': pairs_list = text.split('\n\n') Erg='' if pairs_list: for i in pairs_list: try: pairs = i.split('\n') skkey = pairs[0].strip('\n') value = pairs[1].strip('\n') if re.match('^[0-9a-zA-Z\.]+$', skkey) and value: Erg += '{"path": "'+skkey+'","value":"'+str(value)+'"},' except Exception,e: print 'ERROR parsing Signal K key action: '+str(e) if Erg: SignalK='{"updates":[{"$source":"OPactions","values":[' SignalK+=Erg[0:-1]+']}]}\n' self.sock.sendto(SignalK, ('127.0.0.1', 55557)) elif option[:4] == 'MQTT': topic = option[4:] payload = text auth = {'username': conf.get('MQTT', 'username'), 'password': conf.get('MQTT', 'password')} publish.single(topic, payload=payload, hostname='127.0.0.1', port='1883', auth=auth) publish.single(topic, payload=payload, hostname=conf.get('MQTT', 'broker'), port=conf.get('MQTT', 'port'), auth=auth)
def sendsms(self, phone, msgs): """ Send SMS using Gammu. Arguments: ``phone'' is the phone number the messages are to be dispatched to. ``msgs'' is a list of messages ordered with the most severe first. Each message is a tuple with ID, text and severity of the message. Returns five values: The formatted SMS. A list of IDs of sent messages. A list of IDs of ignored messages. A boolean which is true for success and false for failure. An integer which is the sending ID if available or 0 otherwise. """ # Format SMS (sms, sent, ignored) = self.formatsms(msgs) sms = decode_sms_to_unicode(sms) # We got a python-gammu binding :-) sm = gammu.StateMachine() try: # Typically ~root/.gammurc or ~$NAV_USER/.gammurc sm.ReadConfig() except IOError as error: raise PermanentDispatcherError(error) try: # Fails if e.g. phone is not connected # See http://www.gammu.org/wiki/index.php?title=Gammu:Error_Codes # for complete list of errors fetched here sm.Init() except gammu.GSMError as error: raise PermanentDispatcherError( "GSM %s error %d: %s" % (error[0]['Where'], error[0]['Code'], error[0]['Text']) ) message = { 'Text': sms, 'SMSC': {'Location': 1}, 'Number': phone } try: # Tested with: # - Nokia 6610, Tekram IRmate 410U and Gammu 1.07.00 # - Sony Ericsson K310, USB cable, Gammu 1.06.00, python-gammu 0.13 smsid = sm.SendSMS(message) except gammu.GSMError as error: raise DispatcherError("GSM %s error %d: %s" % (error[0]['Where'], error[0]['Code'], error[0]['Text'])) if isinstance(smsid, (int, long)): result = True else: result = False return (sms, sent, ignored, result, smsid)
def __init__(self, configIndex = 0): self.__gammuStateMachine = gammu.StateMachine() self.__gammuStateMachine.ReadConfig(configIndex)
def start_polling(self): phone = gammu.StateMachine() self.poller = LoopingCall(self.receive_and_send_messages, phone) self.poller.start(self.poll_interval, True)
#testeado con un ZTE N720 #!/usr/bin/env python import gammu import sys sm = gammu.StateMachine() #stateMachine para comunicacion con el dispositivo sm.ReadConfig() # lee (~/.gammurc) sm.Init() # inicializar conexion al dispositivo # armado de la estructura para el sms message = { 'Number': '+581234567891',# aca numero de telefono de destino (incluir codigo de pais '+58' = venezuela) 'SMSC': {'Number': '+581234567891'},# numero de telefono de origen 'Text': 'Hola gammu dese piton!',# texto del mensaje a enviar 'Class': 0, } sm.SendSMS(message) #funcion para enviar el mensaje
def sms_check(self): """Control and processing SMS""" try: import gammu except Exception: log.error(NAME, _('SMS Modem plug-in') + ':\n' + traceback.format_exc()) tel1 = sms_options['tel1'] tel2 = sms_options['tel2'] comm1 = sms_options['txt1'] comm2 = sms_options['txt2'] comm3 = sms_options['txt3'] comm4 = sms_options['txt4'] comm5 = sms_options['txt5'] comm6 = sms_options['txt6'] comm7 = sms_options['txt7'] comm8 = sms_options['txt8'] comm9 = sms_options['txt9'] sm = gammu.StateMachine() sm.ReadConfig() try: sm.Init() log.debug(NAME, datetime_string() + ': ' + _('Checking SMS...')) except: log.error(NAME, _('SMS Modem plug-in') + ':\n' + traceback.format_exc()) self._sleep(60) if sms_options[ "use_strength"]: # print strength signal in status Window every check SMS signal = sm.GetSignalQuality( ) # list: SignalPercent, SignalStrength, BitErrorRate log.info( NAME, datetime_string() + ': ' + _('Signal') + ': ' + str(signal['SignalPercent']) + '% ' + str(signal['SignalStrength']) + 'dB') status = sm.GetSMSStatus() remain = status['SIMUsed'] + status['PhoneUsed'] + status['TemplatesUsed'] sms = [] start = True while remain > 0: if start: cursms = sm.GetNextSMS(Start=True, Folder=0) start = False else: cursms = sm.GetNextSMS(Location=cursms[0]['Location'], Folder=0) remain = remain - len(cursms) sms.append(cursms) data = gammu.LinkSMS(sms) for x in data: v = gammu.DecodeSMS(x) m = x[0] print '%-15s: %s' % ('Sender', m['Number']) print '%-15s: %s' % ('Date', str(m['DateTime'])) print '%-15s: %s' % ('State', m['State']) print '%-15s: %s' % ('SMS command', m['Text']) if (m['Number'] == tel1) or (m['Number'] == tel2): # If telephone is admin 1 or admin 2 log.info(NAME, datetime_string() + ': ' + _('SMS from admin')) if m['State'] == "UnRead": # If SMS is unread log.clear(NAME) if m['Text'] == comm1: # If command = comm1 (info - send SMS to admin phone1 and phone2) log.info( NAME, _('Command') + ' ' + comm1 + ' ' + _('is processed')) # send 1/2 SMS with text 1 up = helpers.uptime() temp = helpers.get_cpu_temp( options.temp_unit) + ' ' + options.temp_unit ip = str(helpers.get_ip()) ver = version.ver_date datastr = ('SMS 1/2. ' + datetime_string() + ', TEMP: ' + temp + ', IP: ' + ip + ', SW: ' + ver + ', UP: ' + up) message = { 'Text': datastr, 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) # send sms 1/2 log.info(NAME, datastr) # send 2/2 SMS with text 2 if inputs.rain_sensed(): rain = "Active" else: rain = "Inactive" try: from plugins import pressure_monitor state_press = pressure_monitor.get_check_pressure() if state_press: press = "High" else: press = "Low" except Exception: press = "N/A" finished = [ run for run in log.finished_runs() if not run['blocked'] ] if finished: last_prog = finished[-1]['start'].strftime( '%H:%M: ') + finished[-1]['program_name'] else: last_prog = 'None' datastr = ('SMS 2/2. ' + 'RAIN: ' + rain + ', PRESS: ' + press + ', LAST: ' + last_prog) message = { 'Text': datastr, 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) # send sms 2/2 log.info(NAME, datastr) log.info( NAME, _('Command') + ': ' + comm1 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) # SMS deleted log.info(NAME, _('Received SMS was deleted')) elif m['Text'] == comm2: # If command = comm2 (stop - scheduler) log.info( NAME, _('Command') + ' ' + comm2 + ' ' + _('is processed')) options.scheduler_enabled = False log.finish_run(None) stations.clear() message = { 'Text': 'Command: ' + comm2 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm2 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted')) elif m['Text'] == comm3: # If command = comm3 (start - scheduler) log.info( NAME, _('Command') + ' ' + comm3 + ' ' + _('is processed')) options.scheduler_enabled = True message = { 'Text': 'Command: ' + comm3 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm3 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted')) elif m['Text'] == comm4: # If command = comm4 (reboot system) log.info( NAME, _('Command') + ' ' + comm4 + ' ' + _('is processed')) message = { 'Text': 'Command: ' + comm4 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm4 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info( NAME, _('Received SMS was deleted and system is now reboot')) reboot() # restart linux system elif m['Text'] == comm5: # If command = comm5 (poweroff system) log.info( NAME, _('Command') + ' ' + comm5 + ' ' + _('is processed')) message = { 'Text': 'Command: ' + comm5 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm5 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info( NAME, _('Received SMS was deleted and system is now poweroff' )) poweroff() # poweroff linux system elif m['Text'] == comm6: # If command = comm6 (update ospi system) log.info( NAME, _('Command') + ' ' + comm6 + ' ' + _('is processed')) message = { 'Text': 'Command: ' + comm6 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm6 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) try: from plugins.system_update import perform_update perform_update() log.info( NAME, _('Received SMS was deleted, update was performed and program will restart' )) except ImportError: log.info( NAME, _('Received SMS was deleted, but could not perform update' )) sm.DeleteSMS(m['Folder'], m['Location']) elif m['Text'] == comm7: # If command = comm7 (send email with foto from webcam) log.info( NAME, _('Command') + ' ' + comm7 + ' ' + _('is processed')) message = { 'Text': 'Command: ' + comm7 + ' was processed', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm7 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) try: from plugins.webcam import get_run_cam, get_image_location get_run_cam() # process save foto to ./data/image.jpg msg = _('SMS plug-in send image file from webcam.') send_email(msg, attach=get_image_location()) except ImportError: log.info( NAME, _('Received SMS was deleted, but could not send email with photo from webcam' )) message = { 'Text': 'Error: not send foto from webcam', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) sm.DeleteSMS(m['Folder'], m['Location']) elif m['Text'] == comm8: # If command = comm8 (send SMS with available commands) log.info( NAME, _('Command') + ' ' + comm8 + ' ' + _('is processed')) message = { 'Text': 'Available commands: ' + comm1 + ',' + comm2 + ',' + comm3 + ',' + comm4 + ',' + comm5 + ',' + comm6 + ',' + comm7 + ',' + comm8 + ',' + comm9 + 'xx', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + comm8 + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted')) elif m['Text'][0:len( comm9 )] == comm9: # If command = lenght char comm9 (run now program xx) num = m['Text'][len( comm9 ):] # number from sms text example: run36 -> num=36 log.info( NAME, _('Command') + ' ' + comm9 + ' ' + _('is processed')) index = int(num) if index <= programs.count( ): # if program number from sms text exists in program db log.finish_run(None) stations.clear() prog = int(index - 1) programs.run_now(prog) log.info( NAME, _('Program') + ': ' + str(index) + ' ' + _('now run')) message = { 'Text': 'Program: ' + str(index) + ' now run', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } else: message = { 'Text': 'Program: ' + str(index) + ' no exists!', 'SMSC': { 'Location': 1 }, 'Number': m['Number'], } sm.SendSMS(message) log.info( NAME, _('Command') + ': ' + str(m['Text']) + ' ' + _('was processed and confirmation was sent as SMS to') + ': ' + m['Number']) sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted')) else: # If SMS command is not defined sm.DeleteSMS(m['Folder'], m['Location']) log.info( NAME, _('Received command') + ' ' + m['Text'] + ' ' + _('is not defined!')) else: # If SMS was read sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted - SMS was read')) else: # If telephone number is not admin 1 or admin 2 phone number sm.DeleteSMS(m['Folder'], m['Location']) log.info(NAME, _('Received SMS was deleted - SMS was not from admin'))