Exemplo n.º 1
0
def custom_sms_routine():
    sms = raw_input("Custom message: ")
    sim_num = raw_input("Number (default: server): ")

    print sms,
    if len(sim_num) == 0:
        dbio.write_sms_to_outbox(sms)
    else:
        dbio.write_sms_to_outbox(sms, sim_num)
Exemplo n.º 2
0
def main():
    parser = argparse.ArgumentParser(description = "Health routine [-options]")
    parser.add_argument("-r", "--read_only", 
        help = "do not save data to memory", action = 'store_true')

    try:
        args = parser.parse_args()
    except IndexError:
        print('>> Error in parsing arguments')
        error = parser.format_help()
        print(error)
        sys.exit()

    mc = common.get_mc_server()

    ts = dt.today()
    ts_str = ts.strftime("%x,%X,")

    try:
        if mc.get('rst_gsm_done') * mc.get('init_gsm_done') * mc.get('send_sms_done'):
            gsmio.check_csq()
            csq = int(mc.get("csq_val"))
            csq = str(csq)
        else:
            print(">> GSM is busy")
            csq = "98"
    except Exception as e:
        print(">> Error reading GSM CSQ. Setting CSQ to error value",e)
        csq = "98"

    cfg = mc.get("server_config")
    
    try:
        mmpertip = float(cfg['rain']['mmpertip'])
    except:
        os.system('python3 /home/pi/gateway3/gateway.py -ir')
        sys.exit()

    rainval = "%0.2f" % (rd.check_rain_value(reset_rain = True) * mmpertip) 
    sysvol = "%0.2f" % (pmon.read()["bus_voltage"])
    
    temp = os.popen("vcgencmd measure_temp").readline()
    tempval = temp.replace("temp=","").replace("'C\n","")
    print("Temperature: {0}".format(tempval))

    msgtosend = cfg["coordinfo"]["name"] + "W," + ts_str
    msgtosend += "0,000," + tempval + "," + rainval + ","
    msgtosend += sysvol + ","
    msgtosend += csq

    if not args.read_only:
        print(">> Saving to memory:")
        time.sleep(5)
        print(msgtosend)
        #common.save_sms_to_memory(msgtosend)
        dbio.write_sms_to_outbox(msgtosend)
Exemplo n.º 3
0
 def on_rx_done(self):
     #BOARD.led_on()
     print("\nRxDone")
     self.clear_irq_flags(RxDone=1)
     payload = self.read_payload(nocheck=True)
     data = ''.join([chr(c) for c in payload])
     print(">> Saving...")
     #print data
     #common.save_sms_to_memory(data)
     data = re.sub(r'[^a-zA-z0-9*<>#/:.\-,+]', "", data)
     timestamp = dt.now().strftime("%y%m%d%H%M%S")
     rssi = self.get_pkt_rssi_value() * -1
     print("RSSI: " + str(rssi))
     if data.startswith('>>'):
         print(">> Valid lora data.")
         hashStart = data.find('#')
         if hashStart != -1:
             data = data[hashStart + 1:-1]
         data = data[:data.find('<<')]
         data = re.sub(r'[<>]', "", data)
         router_name = data[:5]
         global router_list
         global rssi_info
         global volt_info
         if router_name in router_list:
             if rssi_info[router_name] == '':
                 rssi_info[router_name] = str(rssi)
             if 'VOLT' in data:
                 volt_info[router_name] = data[11:data.find('*', 11)]
                 print(data)
         dts = data  #+ '*' + timestamp
         #common.save_sms_to_memory(dts)
         if 'VOLT' not in dts:
             dbio.write_sms_to_outbox(dts)
     else:
         print(">> Invalidated.")
         dts = data + '*INVALID*' + timestamp
         filename = "/home/pi/logs/lora_data.txt"
         with open(filename, 'a+') as fh:
             fh.write(dts + '\n')
         print(dts)
         print(">> Saved to text file.")
     #print(bytes(payload).decode())
     self.set_mode(MODE.SLEEP)
     self.reset_ptr_rx()
     #BOARD.led_off()
     self.set_mode(MODE.RXCONT)
Exemplo n.º 4
0
        rssi_msg += '{},{},{},'.format(router, rssi_info[router],
                                       volt_info[router])
    rssi_msg += '*{}'.format(timestamp)
    return rssi_msg


#try: input("Press enter to start...")
#except: pass

try:
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(rxtimeout)
    lora.start()
except KeyboardInterrupt:
    sys.stdout.flush()
    print("")
    sys.stderr.write("KeyboardInterrupt\n")
except SampleTimeoutException:
    sys.stdout.flush()
    print("")
    #save rssi info: dbio.
    sys.stderr.write("TimeoutInterrupt\n")
finally:
    sys.stdout.flush()
    print("")
    lora.set_mode(MODE.SLEEP)
    #    print(lora)
    print("Terminating")
    BOARD.teardown()
    dbio.write_sms_to_outbox(build_rssi_msg())
Exemplo n.º 5
0
def send_smsoutbox_memory():
    # lockscript.get_lock('gsm')

    print "Sending from memory ..."
    mc = common.get_mc_server()
    sc = mc.get('server_config')
    smsoutbox = mc.get("smsoutbox")

    # print smsoutbox
    phonebook = mc.get("phonebook")

    resend_limit = sc['gsmio']['sendretry']

    smsoutbox_unsent = smsoutbox[smsoutbox["stat"] < resend_limit]
    print smsoutbox_unsent

    for index, row in smsoutbox_unsent.iterrows():
        sms_msg = row['msg']
        sim_num = phonebook[row["contact_id"]]

        if len(sms_msg) > 160:
            smsoutbox.loc[index, 'stat'] = 99
            print "Abort sending", sms_msg
            continue

        stat = gsmio.send_msg(sms_msg, sim_num)

        if stat == 0:
            smsoutbox.loc[index, 'stat'] = resend_limit
            print '>> Message sent'
        else:
            print '>> Message sending failed'
            print '>> Writing to mysql for sending later'
            smsoutbox.loc[index, 'stat'] += 1

            if smsoutbox.loc[index, 'stat'] >= resend_limit:
                dbio.write_sms_to_outbox(sms_msg, sim_num)
                mc.set("sms_in_db", True)

            if stat == -2:
                print '>> Updating smsoutbox before GSM reset'
                smsoutbox_updated = mc.get("smsoutbox")
                ts_latest = smsoutbox.ts.max()
                smsoutbox_new_inserts = smsoutbox_updated[
                    smsoutbox_updated.ts > ts_latest]
                smsoutbox = smsoutbox.append(smsoutbox_new_inserts,
                                             ignore_index=True)
                mc.set("smsoutbox", smsoutbox)
                print '>> Done updating smsoutbox'

                raise gsmio.CustomGSMResetException

    print smsoutbox

    # get smsoutbox for new messages inserted while sending
    smsoutbox_updated = mc.get("smsoutbox")

    # get all items later than the latest ts of smsoutbox
    ts_latest = smsoutbox.ts.max()
    smsoutbox_new_inserts = smsoutbox_updated[smsoutbox_updated.ts > ts_latest]

    # append new items in existing smsoutbox
    smsoutbox = smsoutbox.append(smsoutbox_new_inserts, ignore_index=True)

    mc.set("smsoutbox", smsoutbox)
Exemplo n.º 6
0
    ts = dt.now().strftime('%y%m%d%H%M%S')
    strcmd = 'ARQCMD6T' + '/' + ts + '\r\n'
    cmd = strcmd.encode()
    print(("COMMAND: {}".format(cmd)))
    s.write(cmd)
    time.sleep(1)

    while True:
        if (s.in_waiting > 0):
            rx = s.read_until().decode()
            if rx.startswith('>>'):
                #print("RAW PACKET:\n{}".format(rx))
                s.write('OK'.encode())
                rx = re.sub('[^A-Za-z0-9\+\/\*\:\.\-\,]', '', rx)
                #common.save_sms_to_memory(rx)
                dbio.write_sms_to_outbox(rx)
                print(("VALID PACKET STORED FOR SENDING:\n{}\n".format(rx)))
            elif rx == 'STOPLORA\r\n':
                print(("FINISHED".format(rx)))
                time.sleep(1)
                break
            elif rx == 'Time out...\r\n':
                pass
            else:
                print(("INVALID PACKET:\n{}".format(rx)))

except SampleTimeoutException:
    print(">>TIMEOUT")
except KeyboardInterrupt:
    print(">>INTERRUPTED")
except serial.serialutil.SerialException: