如何通过modbus通信获取IP地址?

时间:2015-09-22 08:43:45

标签: ios objective-c sockets modbus-tcp

我正在创建一个iOS应用程序,它将通过UDP套接字程序通过Modbus通信设备访问IP地址,而不是因为项目已存在于github中而存在于wifi中的所有IP地址。我有android代码,它是用java编写的,与Objective-c平台中我需要的基本逻辑相同。它也不适用于j2objc转换器。 这里是java for android项目中的代码,因为需要相同的iOS平台代码:

     public void startTimerForNetworkAccess()
    {
        try{
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {

                @Override
                public void run() {
                    //System.out.println("TIMER starts");
                    getNetworkStatus();
                }
            }, 0, 5000);
        }catch(IllegalStateException ise)
        {
            //ise.printStackTrace();
            System.out.println("TIMER WAS CANCELLED");
        }
    }

    public void getNetworkStatus()
    {
        asyncTaskNetworkStatusCheck = new AsyncTaskNetworkStatusCheck();
        asyncTaskNetworkStatusCheck.execute();
    }

    // Async Task Class for Network status check
    public class AsyncTaskNetworkStatusCheck extends AsyncTask<Void, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            String status="";
            try {

                status = NetworkUtil.getNetConnectivityStatus(getActivity());
                if(status.equals("Wifi enabled"))
                {
                    if(timer != null)
                    {
                        //System.out.println("TIMER STOPPER");
                        timer.cancel();
                        timer = null;
                    }
                }
                System.out.println("STATUS:"+status);


            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return status;
        }

        @Override
        protected void onPostExecute(String networkStatus) {

            try{
                //Toast.makeText(getActivity(), ""+networkStatus, Toast.LENGTH_LONG).show();

                if(networkStatus.equals("Wifi enabled"))
                {
                    txt_net_error.setVisibility(View.GONE);
                    if(menu_save != null)
                    {
                        menuFlag = 0;
                        menu_progress.setActionView(R.layout.action_progressbar);
                        //menu_progress.expandActionView();

                        menu_progress.setVisible(true);
                        menu_save.setVisible(false);
                        menu_edit.setVisible(false);
                        //menu_load.setVisible(false);
                    }

                    discoverIpListView.setVisibility(View.VISIBLE);    
                    discoverIpAddressAsyncTask();

                }else if(networkStatus.equals("Mobile data enabled")){

                             //discoverIpListView.setVisibility(View.GONE);
                             //showPopDialog();
                    txt_net_error.setVisibility(View.VISIBLE);
                    try{
                    if(menuFlag != 1)
                    {
                        menuFlag = 1;
                        //menu_refresh.setVisible(true);
                        //menu_progress.setActionView(null);
                        //menu_progress.expandActionView();

                        //menu_progress.setVisible(false);
                    }
                        //menuFlag = 0;
                        //menu_refresh.setVisible(true);
                    if(timer == null)
                    {
                        startTimerForNetworkAccess();
                    }
                    }catch(NullPointerException npe){
                        npe.printStackTrace();
                    }


                }else{
                    //discoverIpListView.setVisibility(View.GONE);
                     //showPopDialog();
                    menuFlag = 0;
                    menu_refresh.setVisible(true);
                    txt_net_error.setVisibility(View.VISIBLE);
                    if(timer == null)
                    {
                        startTimerForNetworkAccess();
                    }
                }
            }catch(NullPointerException npe){
                if(timer != null)
                {
                    timer.cancel();
                }else{
                    timer = null;
                }
                startTimerForNetworkAccess();
            }
        }

    }


    public void discoverIpAddressAsyncTask()
    {
        discoverIpAsync = new DiscoverIpAsyncTask();
        discoverIpAsync.execute("");
    }
    // Async Task Class
    public class DiscoverIpAsyncTask extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... urls) {

            setUDPBroadcast();
            socketAccessCount = 0;
            return null;
        }

        @Override
        protected void onPostExecute(String result) {

            //menu_progress.setActionView(null);
            menu_progress.setVisible(false);
            menu_save.setVisible(true);
            menu_edit.setVisible(true);
            //menu_load.setVisible(true);
            if(!discoverIpAsync.isCancelled())
            {
                menuFlag = 1;
            }else{
                menuFlag = 2;
            }
        }
    }

    private int socketAccessCount = 0;
    private int countLoop = 1;
    **public boolean setUDPBroadcast()
    {
        DatagramSocket datagramSocket;
        //DatagramPacket sendPacket; 
        // Find the server using UDP broadcast
        try {
            byte[] sendData = "pe identify".getBytes();

            while(socketAccessCount < 5)
            {
              //Open a random port to send the package


            datagramSocket = new DatagramSocket();
            datagramSocket.setBroadcast(true);
            datagramSocket.setSoTimeout(5000);
                //while(IpAddr.size() < 20)
              //System.out.println("SECOND TIME----------"+socketAccessCount);


              if(discoverIpAsync.isCancelled())
              {

              }


              while(countLoop <= 30)
              {
                  if(!discoverIpAsync.isCancelled())
                  {

                      try {

                        //Try the 255.255.255.255 first
                          try {
                              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, InetAddress.getByName("255.255.255.255"), 505);
                            //System.out.println("SOCKET SENT");
                            datagramSocket.send(sendPacket);
                            //System.out.println(getClass().getName() + ">>> Request packet sent to: 255.255.255.255 (DEFAULT)");
                          } catch (Exception e) {
                              //System.out.println("DATAGRAM ERROR");
                              e.printStackTrace();
                              datagramSocket.close();
                              break;
                          }

                          // Broadcast the message over all the network interfaces
                          Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                          while (interfaces.hasMoreElements()) {
                            NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement();

                            if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                                //System.out.println("LOOPBACK");
                              continue; // Don't want to broadcast to the loopback interface
                            }

                            for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                              InetAddress broadcast = interfaceAddress.getBroadcast();
                              if (broadcast == null) {
                                continue;
                              }

                              // Send the broadcast package!

                                DatagramPacket sendPacket1 = new DatagramPacket(sendData, sendData.length, broadcast, 505);
                                datagramSocket.send(sendPacket1);

                              //System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName());
                            }
                          }

                         //System.out.println(getClass().getName() + ">>> Done looping over all network interfaces. Now waiting for a reply!");

                          //Wait for a response
                          byte[] recvBuf = new byte[15000];

                          DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length);
                          try{
                              datagramSocket.receive(receivePacket);
                          }catch(SocketTimeoutException sto)
                          {
                              //System.out.println("SOCKET TIME OUT");
                              //datagramSocket.send(sendPacket);
                               break;
                          }

                          //We have a response
                          //System.out.println(getClass().getName() + ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());

                          //Check if the message is correct
                          //String message = new String(receivePacket.getData()).trim();
                          //if(message.equals("Solar Inverter"))
                          //{
                              if(!IpAddr.contains(""+receivePacket.getAddress().getHostAddress()) || IpAddr.isEmpty())
                              {
                                  IpAddr.add(""+receivePacket.getAddress().getHostAddress());

                                  //System.out.println(getClass().getName() + ">>> Broadcast response from server: " + receivePacket.getAddress().getHostAddress());
                                  //SI_Count++;

                                  if(getActivity() != null)
                                  {
                                      getActivity().runOnUiThread (new Thread(new Runnable() { 
                                             public void run() {
                                                 listAdapter.notifyDataSetChanged();
                                                 discoverIpListView.invalidateViews();
                                                 discoverIpListView.refreshDrawableState();

                                             }
                                         }));
                                  }

                                  try {
                                    Thread.sleep(200);
                                } catch (InterruptedException e) {
                                    // TODO Auto-generated catch block
                                    //e.printStackTrace();
                                }

                              }
                          //}

                        countLoop++;
                      } catch (Exception e) {
                          e.printStackTrace();
                      }
                  }else{
                      //getTargetFragment().setMenuVisibility(false);
                      //menu_progress.setActionView(null);
                      //menu_progress.setVisible(false);
                      //discoverIpAddressAsyncTask();
                      if(menuFlag == 2)
                      {

                      }else{
                          menuFlag = 0;
                      }

                     System.out.println("CANCELLED");
                      return true;
                  }
              }
              if(IpAddr.size() > 0){}

              //Close the port!
              datagramSocket.close();
              socketAccessCount++;
            }

        } catch (IOException ex) {
          //Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            //System.out.println(""+ex);
        }

        /*for(int i=0;i<IpAddr.size();i++)
        {
            System.out.println("IP:"+IpAddr.get(i));
        }*/
        return true;
    }**

1 个答案:

答案 0 :(得分:0)

经过一些研究并得到我最好的伙伴的帮助后,我得到了解决方案。我正在使用GCDAsyncSocket和AsyncSocket是来自https://github.com/robbiehanson/CocoaAsyncSocket的TCP / IP套接字网络库,用于UDP连接。然后我将使用此链接iPhone/iPad/OSX: How to get my IP address programmatically?获取所有IP地址并存储在一个阵列中,这是我通过UDP套接字程序通过Modbus通信设备获取IP地址的逻辑。

- (void)loadAllIpNow{
self.connctedDevices = [NSMutableArray new];

currentIndex = 0;
ipaddressArray =[[NSArray alloc]initWithObjects:@"192.168.2.60",@"192.168.2.61",@"192.168.2.62",@"192.168.2.63",@"192.168.2.64",@"192.168.2.65",@"192.168.2.66",@"192.168.2.67",@"192.168.68",@"192.168.2.69",@"192.168.2.70",@"192.168.2.71",@"192.168.2.72",@"192.168.2.73",@"192.168.74",@"192.168.2.75",@"192.168.2.76",@"192.168.2.77",@"192.168.2.78",@"192.168.2.79",@"192.168.2.80",@"192.168.2.81",@"192.168.2.82",@"192.168.2.83",@"192.168.2.84",@"192.168.2.85",@"192.168.2.86",@"192.168.2.87",@"192.168.2.88",@"192.168.2.89",@"192.168.2.90",@"192.168.2.91",@"192.168.2.92",@"192.168.2.93",@"192.168.2.94",@"192.168.2.95",@"192.168.2.96",@"192.168.2.97",@"192.168.2.98",@"192.168.2.99",@"192.168.2.100",@"192.168.2.101",@"192.168.2.102", nil];

[self performSelector:@selector(callUDPsocketForIPD:) withObject:[NSString stringWithFormat:@"%d",currentIndex] afterDelay:0.3];}

-(void)callUDPsocketForIPD:(NSString*)Value{
udpSocket = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue() andtag:[Value intValue]];
NSError *error = nil;
//  [udpSocket enableBroadcast:YES error:&error];

if (![udpSocket bindToPort:505 error:&error]) {
    // NSLog(@"Error starting server (bind): %@", error.description );
    //return;
}
NSData *data = [@"pe identify" dataUsingEncoding:NSUTF8StringEncoding];

[udpSocket sendData:data toHost:[ipaddressArray objectAtIndex:[Value intValue]] port:505 withTimeout:-1 tag:1];
if (![udpSocket beginReceiving:&error]) {
    [udpSocket close];
    // NSLog(@"Error starting server (recv): %@", error.description);
    // return;
}
//  NSLog(@"Udp server started on port %@:%hu", [udpSocket localHost_IPv4], [udpSocket localPort]);
currentIndex++;
if(currentIndex<ipaddressArray.count)
{
    [self performSelector:@selector(callUDPsocketForIPD:) withObject:[NSString stringWithFormat:@"%d",currentIndex] afterDelay:0.3];
}
}

- (void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
int tag= (int)sock.tagValue;
NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"msg= %@ with tagvalue = %d and Ip = %@",msg,tag,[ipaddressArray objectAtIndex:tag]);
[self.connctedDevices addObject:[ipaddressArray objectAtIndex:tag]];
[self.lantableView reloadData];
}