Welcome to the Pycom forum Forum
    • \[\[global:header.categories\]\]
    • \[\[global:header.recent\]\]
    • \[\[global:header.tags\]\]
    • \[\[global:header.popular\]\]
    • Login

    Explore Pybytes | Official Documentation | Report a Firmware Bug/Issue | GitHub

    no execution after lora thread

    Scheduled Pinned Locked Moved LoPy
    loramqttthreading
    5 Posts 3 Posters 818 Views 3 Watching
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J Offline
      james
      last edited by

      after

      _thread.start_new_thread(self.lora_loop(),())
      

      no code execution, in another thread mqtt error!!!!!

      class LoraGateway:
          def __init__(self, fileconfig=None):
              self.lastattrsend = 0
              self.config = fileconfig if fileconfig != None else XConfigureFile()
              self.deviceid = binascii.hexlify(unique_id())
              self.device = []
              self.devicedata = []
              self.wlan = WLAN(mode=WLAN.STA)
              self.rtc = RTC()
              self.mqttc = MQTTClient(b'TRK'+binascii.hexlify(unique_id()), "io.trackr.it", port=8883, user=self.config.file['accesstoken'], password=self.config.file['accesstoken'], ssl=True, ssl_params={'ca_certs':'lib/mqttserver.pub.pem'})
              '''
              self.mqttclient = MQTTClient(server="io.trackr.it", port=8883, ssl=True, ssl_params={'ca_certs':'lib/mqttserver.pub.pem'})
              self.mqttclient.set_connected_callback(self.con_cb)
              self.mqttclient.set_puback_callback(self.puback_cb)
              self.mqttclient.set_suback_callback(self.suback_cb)
              self.mqttclient.set_message_callback(self.msg_cb)
              '''
          def lora_loop(self):
              #while not (self.wlan.isconnected() and self.rtc.synced()):
              #    time.sleep(5)
              self.counter = LoraCounter(int(self.config.file['cytime']))
              print("Counter started")
              self.lora = LoRa(mode=LoRa.LORA, rx_iq=True)
              self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
              self.sock.setblocking(self.config.file['blockmode'])
              print("Lora started")
              while True:
                  try:
                      recv_pkg = self.sock.recv(512)
                      if (len(recv_pkg) > 24):
                          print(recv_pkg)
                          recv_pkg_len = recv_pkg[25] 
                          # XXXXXXXXXXXX=mac + B=Command + B=pkgsize + %ds=package
                          device_id, gateway_id, command, pkg_len, msg = struct.unpack(_LORA_PKG_FORMAT % recv_pkg_len, recv_pkg) 
      
                          if (gateway_id==self.deviceid) or (gateway_id==b'000000000000' and command==_LORA_CMD_JOIN):
                              try:
                                  devidx = self.device.index(device_id)
                              except Exception as e:
                                  self.device.append(device_id)
                                  devidx = self.device.index(device_id)
      
                              if (command == _LORA_CMD_JOIN):
                                  ack_pkg = struct.pack(_LORA_PKG_ACK_JOINED, device_id, devidx, 200, self.deviceid)
                              elif (command == _LORA_CMD_SEND):
                                  if self.rtc.synced:
                                      ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, devidx, 200, self.counter.seconds, self.counter.epsleeptime )
                                      ## get data from struct
                                      array_s = (msg.decode('ascii')).split(';')
                                      temp = float(array_s[0])
                                      humy = float(array_s[1])
                                      volt = float(array_s[2])
                                      ## make object an push in collection
                                      self.devicedata.append(LoroData(device=device_id, temperature=temp, humidity=humy, voltage=volt))
                                  else:
                                      ack_pkg = struct.pack(_LORA_PKG_ACK_FORMAT, device_id, devidx, 200, 120, self.counter.epsleeptime )
                              '''
                              sendack = True
                              if (self.wlan.isconnected() and self.rtc.synced()):
                                  try:
                                      self.mqttc.connect()
      
                                      if (self.lastattrsend != self.counter.ms_time):
                                          self.mqttc.publish('v1/devices/me/attributes', _MQTT_GATWY_ATTRIBUTE_PKG_FORMAT % (LocalTimeToStrFormat(),str(self.deviceid,'utf-8'),self.config.file['cytime']))
                                          self.lastattrsend = self.counter.ms_time
                                      
                                      if (command == _LORA_CMD_JOIN):
                                          self.mqttc.publish('v1/gateway/connect', _MQTT_DEVICE_PKG_FORMAT % (str(device_id,'utf-8')))
                                      elif (command == _LORA_CMD_SEND):
                                          self.mqttc.publish('v1/gateway/connect', _MQTT_DEVICE_PKG_FORMAT % (str(device_id,'utf-8')))
                                          self.mqttc.publish('v1/gateway/attributes', _MQTT_SONDA_ATTRIBUTE_PKG_FORMAT % (str(device_id,'utf-8'),LocalTimeToStrFormat(),str(device_id,'utf-8'),str(self.deviceid,'utf-8')))
                                          self.mqttc.publish('v1/gateway/telemetry', _MQTT_TELEMETRY_PKG_FORMAT % (str(device_id,'utf-8'),self.counter.ms_time,temp,humy,volt))
                                      
                                      self.mqttc.disconnect()
                                  except Exception as e:
                                      sendack = False
                                      print('MQTT Exception:')
                                      print(e)
                              '''                
                              #send device ack join or package
                              print(ack_pkg)
                              self.sock.send(ack_pkg)
                              print('ACK SEND')
      
                      gc.collect() # enable garbage collector
                  except Exception as e:
                      print('LoRa loop Exception:')
                      print(e)
      
          def thread_connect(self):
              BlinkingStart(250)
              # WLAN CONFIGURE
              print("Start WLAN...")
              if self.config.file['wlan']['dhcp'] != True:
                  self.wlan.ifconfig(config=(self.config.file['wlan']['ipaddress'], self.config.file['wlan']['subnet'], self.config.file['wlan']['gateway'],  self.config.file['wlan']['dns']))
              keytype = WLAN.WPA2
              if self.config.file['wlan']['authtype']=='WEB':
                  keytype = WLAN.WEB
              elif self.config.file['wlan']['authtype']=='WPA':
                  keytype = WLAN.WPA
              elif self.config.file['wlan']['authtype']=='WPA2':  
                  keytype = WLAN.WPA2
      
              while True:
                  if not self.wlan.isconnected():
                      try:
                          print(self.config.file['wlan']['ssid'])
                          print(keytype)
                          print(self.config.file['wlan']['password'])
                          print(self.config.file['wlan']['dhcp'])
      
                          # WLAN CONNECT
                          self.wlan.connect(self.config.file['wlan']['ssid'], auth=(keytype, self.config.file['wlan']['password']))
                          while not self.wlan.isconnected():
                              time.sleep_ms(50)
                          print("WLAN Connected")
                          print(self.wlan.ifconfig())
      
                          # RTC CONFIGURE
                          ntps = self.config.file['ntpserver'] 
                          print(ntps)
                          if (ntps == ""):
                              ntps = "0.it.pool.ntp.org"
                          self.rtc.ntp_sync(ntps, 3600)
                          while not self.rtc.synced():
                              time.sleep_ms(50)     
                          print("RTC Syncronized")
                          print(self.rtc.now())
      
                          self.counter.timeupdate()
      
                          BlinkingStop()
                          LED('P20',False).On()
      
                          #_thread.start_new_thread(self.thread_mqtt(),())
                      except Exception as e:
                          print(e)
                  else:
                      time.sleep(60)
          
          ### mqtt callback begin
          #     
          def puback_cb(self, msg_id):
              print('PUBACK ID = %r' % msg_id)
      
          def suback_cb(self, msg_id, qos):
              print('SUBACK ID = %r, Accepted QOS = %r' % (msg_id, qos))
        
          def con_cb(self, connected):
              if connected:
                  pass
                  #client.subscribe('subscribe/topic')
      
          def msg_cb(self, topic, pay):
              print('Received %s: %s' % (topic.decode("utf-8"), pay.decode("utf-8")))
          #     
          ### mqtt callback end
      
          def thread_mqtt(self):
              print("MQTT loop connect")
      
              '''
              #mqttc = MQTTClient(b'TRK'+binascii.hexlify(unique_id()), server="io.trackr.it", port=8883,user=self.config.file['accesstoken'], password=self.config.file['accesstoken'])
              #mqttc.connect(ssl=True, ca_certs='lib/mqttserver.pub.pem')
      
              #mqttc = MQTTClient(b'TRK'+binascii.hexlify(unique_id()), "io.trackr.it", port=8883, user=self.config.file['accesstoken'], password=self.config.file['accesstoken'], ssl=True, ssl_params={'ca_certs':'lib/mqttserver.pub.pem'})
              #mqttc.connect()
              print("MQTT loop start")
              while self.wlan.isconnected():
                  mqttc.publish('v1/devices/me/attributes', _MQTT_GATWY_ATTRIBUTE_PKG_FORMAT % (LocalTimeToStrFormat(),str(self.deviceid,'utf-8'),self.config.file['cytime']))
                  
                  time.sleep(60)
      
              self.mqttclient.connect(client_id=b'TRK'+binascii.hexlify(unique_id()), user=self.config.file['accesstoken'], password=self.config.file['accesstoken'] )
              while True:
                  if self.mqttclient.isconnected():
                      while (len(self.devicedata)>0):
                          data = self.devicedata.pop(0)
      
                          self.mqttclient.publish(topic='v1/gateway/connect', payload=_MQTT_DEVICE_PKG_FORMAT % (str(data.Device,'utf-8')))
                          self.mqttclient.publish(topic='v1/gateway/attributes', payload=_MQTT_SONDA_ATTRIBUTE_PKG_FORMAT % (str(data.Device,'utf-8'),LocalTimeToStrFormat(),str(data.Device,'utf-8'),str(self.deviceid,'utf-8')))
                          self.mqttclient.publish(topic='v1/gateway/telemetry', payload=_MQTT_TELEMETRY_PKG_FORMAT % (str(data.Device,'utf-8'),self. counter.ms_time,data.Temperature, data.Humidity, data.Voltage))
      
                      if (self.lastattrsend != self.counter.ms_time):
                          self.mqttc.publish('v1/devices/me/attributes', _MQTT_GATWY_ATTRIBUTE_PKG_FORMAT % (LocalTimeToStrFormat(),str(self.deviceid,'utf-8'),self.config.file['cytime']))
                          self.lastattrsend = self.counter.ms_time
              '''
          def start(self):
              _thread.start_new_thread(self.thread_connect,())
              _thread.start_new_thread(self.lora_loop(),())
              print('start loop')
              while True:
                  if self.wlan.isconnected():
                      try:
                          print('mqtt connect')
                          self.mqttc.connect()
                          print('mqtt publish')
                          self.mqttc.publish('v1/devices/me/attributes', _MQTT_GATWY_ATTRIBUTE_PKG_FORMAT % (LocalTimeToStrFormat(),str(self.deviceid,'utf-8'),self.config.file['cytime']))
                          print('mqtt publish')
                          self.mqttc.disconnect()
                          time.sleep(60)
                      except:
                          continue
      
      robert-hhR 1 Reply Last reply Reply Quote 0
      • C Offline
        cdjambov
        last edited by

        I am having the same problem with my lopy/pytrack combo. I have two methods - one to handle lora comms and one to get gps coords. Both methods work ok if used as separate projects(separate main.py file executed after boot.py).

        The second thread is never executed. The print statements also never gets executed.

        lora_thread_id = _thread.start_new_thread(loraSendReceive(), None)
        gps_thread_id = _thread.start_new_thread(get_gps_coords(), None)
        print (lora_thread_id)
        print (gps_thread_id)
        
        C 1 Reply Last reply Reply Quote 0
        • C Offline
          cdjambov @cdjambov
          last edited by

          @cdjambov said in no execution after lora thread:

          print statements also never gets execute

          I have swapped the threads start lines as per above and the lora thread did not execute this time.

          1 Reply Last reply Reply Quote 0
          • robert-hhR Offline
            robert-hh @james
            last edited by

            @james You could try to insert a short utime.sleep() call. Busy while True loops tend to absorb all CPU time.

            C 1 Reply Last reply Reply Quote 0
            • C Offline
              cdjambov @robert-hh
              last edited by

              @robert-hh Hello there Robert. Thanks for the reply. Both of my threads have 60 sec sleeps inside. The lora thread have other sleeps as well.

              1 Reply Last reply Reply Quote 0

              Hello! It looks like you're interested in this conversation, but you don't have an account yet.

              Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

              With your input, this post could be even better 💗

              Register Login
              • 1 / 1
              • First post
                Last post

              Pycom on Twitter

              Pycom